potree.js 5.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641
  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('three')) :
  3. typeof define === 'function' && define.amd ? define(['exports', 'three'], factory) :
  4. (global = global || self, factory(global.Potree = {}, global.THREE$2));
  5. }(this, (function (exports, THREE$2) { 'use strict';
  6. function _OverloadYield(e, d) {
  7. this.v = e, this.k = d;
  8. }
  9. function _applyDecoratedDescriptor(i, e, r, n, l) {
  10. var a = {};
  11. return Object.keys(n).forEach(function (i) {
  12. a[i] = n[i];
  13. }), a.enumerable = !!a.enumerable, a.configurable = !!a.configurable, ("value" in a || a.initializer) && (a.writable = !0), a = r.slice().reverse().reduce(function (r, n) {
  14. return n(i, e, r) || r;
  15. }, a), l && void 0 !== a.initializer && (a.value = a.initializer ? a.initializer.call(l) : void 0, a.initializer = void 0), void 0 === a.initializer ? (Object.defineProperty(i, e, a), null) : a;
  16. }
  17. function _applyDecs2311(e, t, n, r, o, i) {
  18. var a,
  19. c,
  20. u,
  21. s,
  22. f,
  23. l,
  24. p,
  25. d = Symbol.metadata || Symbol.for("Symbol.metadata"),
  26. m = Object.defineProperty,
  27. h = Object.create,
  28. y = [h(null), h(null)],
  29. v = t.length;
  30. function g(t, n, r) {
  31. return function (o, i) {
  32. n && (i = o, o = e);
  33. for (var a = 0; a < t.length; a++) i = t[a].apply(o, r ? [i] : []);
  34. return r ? i : o;
  35. };
  36. }
  37. function b(e, t, n, r) {
  38. if ("function" != typeof e && (r || void 0 !== e)) throw new TypeError(t + " must " + (n || "be") + " a function" + (r ? "" : " or undefined"));
  39. return e;
  40. }
  41. function applyDec(e, t, n, r, o, i, u, s, f, l, p) {
  42. function d(e) {
  43. if (!p(e)) throw new TypeError("Attempted to access private element on non-instance");
  44. }
  45. var h = [].concat(t[0]),
  46. v = t[3],
  47. w = !u,
  48. D = 1 === o,
  49. S = 3 === o,
  50. j = 4 === o,
  51. E = 2 === o;
  52. function I(t, n, r) {
  53. return function (o, i) {
  54. return n && (i = o, o = e), r && r(o), P[t].call(o, i);
  55. };
  56. }
  57. if (!w) {
  58. var P = {},
  59. k = [],
  60. F = S ? "get" : j || D ? "set" : "value";
  61. if (f ? (l || D ? P = {
  62. get: _setFunctionName(function () {
  63. return v(this);
  64. }, r, "get"),
  65. set: function (e) {
  66. t[4](this, e);
  67. }
  68. } : P[F] = v, l || _setFunctionName(P[F], r, E ? "" : F)) : l || (P = Object.getOwnPropertyDescriptor(e, r)), !l && !f) {
  69. if ((c = y[+s][r]) && 7 != (c ^ o)) throw Error("Decorating two elements with the same name (" + P[F].name + ") is not supported yet");
  70. y[+s][r] = o < 3 ? 1 : o;
  71. }
  72. }
  73. for (var N = e, O = h.length - 1; O >= 0; O -= n ? 2 : 1) {
  74. var T = b(h[O], "A decorator", "be", !0),
  75. z = n ? h[O - 1] : void 0,
  76. A = {},
  77. H = {
  78. kind: ["field", "accessor", "method", "getter", "setter", "class"][o],
  79. name: r,
  80. metadata: a,
  81. addInitializer: function (e, t) {
  82. if (e.v) throw new TypeError("attempted to call addInitializer after decoration was finished");
  83. b(t, "An initializer", "be", !0), i.push(t);
  84. }.bind(null, A)
  85. };
  86. if (w) c = T.call(z, N, H), A.v = 1, b(c, "class decorators", "return") && (N = c);else if (H.static = s, H.private = f, c = H.access = {
  87. has: f ? p.bind() : function (e) {
  88. return r in e;
  89. }
  90. }, j || (c.get = f ? E ? function (e) {
  91. return d(e), P.value;
  92. } : I("get", 0, d) : function (e) {
  93. return e[r];
  94. }), E || S || (c.set = f ? I("set", 0, d) : function (e, t) {
  95. e[r] = t;
  96. }), N = T.call(z, D ? {
  97. get: P.get,
  98. set: P.set
  99. } : P[F], H), A.v = 1, D) {
  100. if ("object" == typeof N && N) (c = b(N.get, "accessor.get")) && (P.get = c), (c = b(N.set, "accessor.set")) && (P.set = c), (c = b(N.init, "accessor.init")) && k.unshift(c);else if (void 0 !== N) throw new TypeError("accessor decorators must return an object with get, set, or init properties or undefined");
  101. } else b(N, (l ? "field" : "method") + " decorators", "return") && (l ? k.unshift(N) : P[F] = N);
  102. }
  103. return o < 2 && u.push(g(k, s, 1), g(i, s, 0)), l || w || (f ? D ? u.splice(-1, 0, I("get", s), I("set", s)) : u.push(E ? P[F] : b.call.bind(P[F])) : m(e, r, P)), N;
  104. }
  105. function w(e) {
  106. return m(e, d, {
  107. configurable: !0,
  108. enumerable: !0,
  109. value: a
  110. });
  111. }
  112. return void 0 !== i && (a = i[d]), a = h(null == a ? null : a), f = [], l = function (e) {
  113. e && f.push(g(e));
  114. }, p = function (t, r) {
  115. for (var i = 0; i < n.length; i++) {
  116. var a = n[i],
  117. c = a[1],
  118. l = 7 & c;
  119. if ((8 & c) == t && !l == r) {
  120. var p = a[2],
  121. d = !!a[3],
  122. m = 16 & c;
  123. applyDec(t ? e : e.prototype, a, m, d ? "#" + p : _toPropertyKey(p), l, l < 2 ? [] : t ? s = s || [] : u = u || [], f, !!t, d, r, t && d ? function (t) {
  124. return _checkInRHS(t) === e;
  125. } : o);
  126. }
  127. }
  128. }, p(8, 0), p(0, 0), p(8, 1), p(0, 1), l(u), l(s), c = f, v || w(e), {
  129. e: c,
  130. get c() {
  131. var n = [];
  132. return v && [w(e = applyDec(e, [t], r, e.name, 5, n)), g(n, 1)];
  133. }
  134. };
  135. }
  136. function _arrayLikeToArray(r, a) {
  137. (null == a || a > r.length) && (a = r.length);
  138. for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
  139. return n;
  140. }
  141. function _arrayWithHoles(r) {
  142. if (Array.isArray(r)) return r;
  143. }
  144. function _arrayWithoutHoles(r) {
  145. if (Array.isArray(r)) return _arrayLikeToArray(r);
  146. }
  147. function _assertClassBrand(e, t, n) {
  148. if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n;
  149. throw new TypeError("Private element is not present on this object");
  150. }
  151. function _assertThisInitialized(e) {
  152. if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
  153. return e;
  154. }
  155. function _asyncGeneratorDelegate(t) {
  156. var e = {},
  157. n = !1;
  158. function pump(e, r) {
  159. return n = !0, r = new Promise(function (n) {
  160. n(t[e](r));
  161. }), {
  162. done: !1,
  163. value: new _OverloadYield(r, 1)
  164. };
  165. }
  166. return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function () {
  167. return this;
  168. }, e.next = function (t) {
  169. return n ? (n = !1, t) : pump("next", t);
  170. }, "function" == typeof t.throw && (e.throw = function (t) {
  171. if (n) throw n = !1, t;
  172. return pump("throw", t);
  173. }), "function" == typeof t.return && (e.return = function (t) {
  174. return n ? (n = !1, t) : pump("return", t);
  175. }), e;
  176. }
  177. function _asyncIterator(r) {
  178. var n,
  179. t,
  180. o,
  181. e = 2;
  182. for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
  183. if (t && null != (n = r[t])) return n.call(r);
  184. if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
  185. t = "@@asyncIterator", o = "@@iterator";
  186. }
  187. throw new TypeError("Object is not async iterable");
  188. }
  189. function AsyncFromSyncIterator(r) {
  190. function AsyncFromSyncIteratorContinuation(r) {
  191. if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
  192. var n = r.done;
  193. return Promise.resolve(r.value).then(function (r) {
  194. return {
  195. value: r,
  196. done: n
  197. };
  198. });
  199. }
  200. return AsyncFromSyncIterator = function (r) {
  201. this.s = r, this.n = r.next;
  202. }, AsyncFromSyncIterator.prototype = {
  203. s: null,
  204. n: null,
  205. next: function () {
  206. return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
  207. },
  208. return: function (r) {
  209. var n = this.s.return;
  210. return void 0 === n ? Promise.resolve({
  211. value: r,
  212. done: !0
  213. }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
  214. },
  215. throw: function (r) {
  216. var n = this.s.return;
  217. return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
  218. }
  219. }, new AsyncFromSyncIterator(r);
  220. }
  221. function asyncGeneratorStep(n, t, e, r, o, a, c) {
  222. try {
  223. var i = n[a](c),
  224. u = i.value;
  225. } catch (n) {
  226. return void e(n);
  227. }
  228. i.done ? t(u) : Promise.resolve(u).then(r, o);
  229. }
  230. function _asyncToGenerator(n) {
  231. return function () {
  232. var t = this,
  233. e = arguments;
  234. return new Promise(function (r, o) {
  235. var a = n.apply(t, e);
  236. function _next(n) {
  237. asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
  238. }
  239. function _throw(n) {
  240. asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
  241. }
  242. _next(void 0);
  243. });
  244. };
  245. }
  246. function _awaitAsyncGenerator(e) {
  247. return new _OverloadYield(e, 0);
  248. }
  249. function _callSuper(t, o, e) {
  250. return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
  251. }
  252. function _checkInRHS(e) {
  253. if (Object(e) !== e) throw TypeError("right-hand side of 'in' should be an object, got " + (null !== e ? typeof e : "null"));
  254. return e;
  255. }
  256. function _checkPrivateRedeclaration(e, t) {
  257. if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object");
  258. }
  259. function _classCallCheck(a, n) {
  260. if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
  261. }
  262. function _classNameTDZError(e) {
  263. throw new ReferenceError('Class "' + e + '" cannot be referenced in computed property keys.');
  264. }
  265. function _classPrivateFieldGet2(s, a) {
  266. return s.get(_assertClassBrand(s, a));
  267. }
  268. function _classPrivateFieldInitSpec(e, t, a) {
  269. _checkPrivateRedeclaration(e, t), t.set(e, a);
  270. }
  271. function _classPrivateFieldLooseBase(e, t) {
  272. if (!{}.hasOwnProperty.call(e, t)) throw new TypeError("attempted to use private field on non-instance");
  273. return e;
  274. }
  275. var id = 0;
  276. function _classPrivateFieldLooseKey(e) {
  277. return "__private_" + id++ + "_" + e;
  278. }
  279. function _classPrivateFieldSet2(s, a, r) {
  280. return s.set(_assertClassBrand(s, a), r), r;
  281. }
  282. function _classPrivateGetter(s, r, a) {
  283. return a(_assertClassBrand(s, r));
  284. }
  285. function _classPrivateMethodInitSpec(e, a) {
  286. _checkPrivateRedeclaration(e, a), a.add(e);
  287. }
  288. function _classPrivateSetter(s, r, a, t) {
  289. return r(_assertClassBrand(s, a), t), t;
  290. }
  291. function _classStaticPrivateMethodGet(s, a, t) {
  292. return _assertClassBrand(a, s), t;
  293. }
  294. function _construct(t, e, r) {
  295. if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
  296. var o = [null];
  297. o.push.apply(o, e);
  298. var p = new (t.bind.apply(t, o))();
  299. return r && _setPrototypeOf(p, r.prototype), p;
  300. }
  301. function _defineProperties(e, r) {
  302. for (var t = 0; t < r.length; t++) {
  303. var o = r[t];
  304. o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
  305. }
  306. }
  307. function _createClass(e, r, t) {
  308. return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
  309. writable: !1
  310. }), e;
  311. }
  312. function _createForOfIteratorHelper(r, e) {
  313. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  314. if (!t) {
  315. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
  316. t && (r = t);
  317. var n = 0,
  318. F = function () {};
  319. return {
  320. s: F,
  321. n: function () {
  322. return n >= r.length ? {
  323. done: !0
  324. } : {
  325. done: !1,
  326. value: r[n++]
  327. };
  328. },
  329. e: function (r) {
  330. throw r;
  331. },
  332. f: F
  333. };
  334. }
  335. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  336. }
  337. var o,
  338. a = !0,
  339. u = !1;
  340. return {
  341. s: function () {
  342. t = t.call(r);
  343. },
  344. n: function () {
  345. var r = t.next();
  346. return a = r.done, r;
  347. },
  348. e: function (r) {
  349. u = !0, o = r;
  350. },
  351. f: function () {
  352. try {
  353. a || null == t.return || t.return();
  354. } finally {
  355. if (u) throw o;
  356. }
  357. }
  358. };
  359. }
  360. function _createForOfIteratorHelperLoose(r, e) {
  361. var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  362. if (t) return (t = t.call(r)).next.bind(t);
  363. if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
  364. t && (r = t);
  365. var o = 0;
  366. return function () {
  367. return o >= r.length ? {
  368. done: !0
  369. } : {
  370. done: !1,
  371. value: r[o++]
  372. };
  373. };
  374. }
  375. throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  376. }
  377. function _createSuper(t) {
  378. var r = _isNativeReflectConstruct();
  379. return function () {
  380. var e,
  381. o = _getPrototypeOf(t);
  382. if (r) {
  383. var s = _getPrototypeOf(this).constructor;
  384. e = Reflect.construct(o, arguments, s);
  385. } else e = o.apply(this, arguments);
  386. return _possibleConstructorReturn(this, e);
  387. };
  388. }
  389. function _decorate(e, r, t, i) {
  390. var o = _getDecoratorsApi();
  391. if (i) for (var n = 0; n < i.length; n++) o = i[n](o);
  392. var s = r(function (e) {
  393. o.initializeInstanceElements(e, a.elements);
  394. }, t),
  395. a = o.decorateClass(_coalesceClassElements(s.d.map(_createElementDescriptor)), e);
  396. return o.initializeClassElements(s.F, a.elements), o.runClassFinishers(s.F, a.finishers);
  397. }
  398. function _getDecoratorsApi() {
  399. _getDecoratorsApi = function () {
  400. return e;
  401. };
  402. var e = {
  403. elementsDefinitionOrder: [["method"], ["field"]],
  404. initializeInstanceElements: function (e, r) {
  405. ["method", "field"].forEach(function (t) {
  406. r.forEach(function (r) {
  407. r.kind === t && "own" === r.placement && this.defineClassElement(e, r);
  408. }, this);
  409. }, this);
  410. },
  411. initializeClassElements: function (e, r) {
  412. var t = e.prototype;
  413. ["method", "field"].forEach(function (i) {
  414. r.forEach(function (r) {
  415. var o = r.placement;
  416. if (r.kind === i && ("static" === o || "prototype" === o)) {
  417. var n = "static" === o ? e : t;
  418. this.defineClassElement(n, r);
  419. }
  420. }, this);
  421. }, this);
  422. },
  423. defineClassElement: function (e, r) {
  424. var t = r.descriptor;
  425. if ("field" === r.kind) {
  426. var i = r.initializer;
  427. t = {
  428. enumerable: t.enumerable,
  429. writable: t.writable,
  430. configurable: t.configurable,
  431. value: void 0 === i ? void 0 : i.call(e)
  432. };
  433. }
  434. Object.defineProperty(e, r.key, t);
  435. },
  436. decorateClass: function (e, r) {
  437. var t = [],
  438. i = [],
  439. o = {
  440. static: [],
  441. prototype: [],
  442. own: []
  443. };
  444. if (e.forEach(function (e) {
  445. this.addElementPlacement(e, o);
  446. }, this), e.forEach(function (e) {
  447. if (!_hasDecorators(e)) return t.push(e);
  448. var r = this.decorateElement(e, o);
  449. t.push(r.element), t.push.apply(t, r.extras), i.push.apply(i, r.finishers);
  450. }, this), !r) return {
  451. elements: t,
  452. finishers: i
  453. };
  454. var n = this.decorateConstructor(t, r);
  455. return i.push.apply(i, n.finishers), n.finishers = i, n;
  456. },
  457. addElementPlacement: function (e, r, t) {
  458. var i = r[e.placement];
  459. if (!t && -1 !== i.indexOf(e.key)) throw new TypeError("Duplicated element (" + e.key + ")");
  460. i.push(e.key);
  461. },
  462. decorateElement: function (e, r) {
  463. for (var t = [], i = [], o = e.decorators, n = o.length - 1; n >= 0; n--) {
  464. var s = r[e.placement];
  465. s.splice(s.indexOf(e.key), 1);
  466. var a = this.fromElementDescriptor(e),
  467. l = this.toElementFinisherExtras((0, o[n])(a) || a);
  468. e = l.element, this.addElementPlacement(e, r), l.finisher && i.push(l.finisher);
  469. var c = l.extras;
  470. if (c) {
  471. for (var p = 0; p < c.length; p++) this.addElementPlacement(c[p], r);
  472. t.push.apply(t, c);
  473. }
  474. }
  475. return {
  476. element: e,
  477. finishers: i,
  478. extras: t
  479. };
  480. },
  481. decorateConstructor: function (e, r) {
  482. for (var t = [], i = r.length - 1; i >= 0; i--) {
  483. var o = this.fromClassDescriptor(e),
  484. n = this.toClassDescriptor((0, r[i])(o) || o);
  485. if (void 0 !== n.finisher && t.push(n.finisher), void 0 !== n.elements) {
  486. e = n.elements;
  487. for (var s = 0; s < e.length - 1; s++) for (var a = s + 1; a < e.length; a++) if (e[s].key === e[a].key && e[s].placement === e[a].placement) throw new TypeError("Duplicated element (" + e[s].key + ")");
  488. }
  489. }
  490. return {
  491. elements: e,
  492. finishers: t
  493. };
  494. },
  495. fromElementDescriptor: function (e) {
  496. var r = {
  497. kind: e.kind,
  498. key: e.key,
  499. placement: e.placement,
  500. descriptor: e.descriptor
  501. };
  502. return Object.defineProperty(r, Symbol.toStringTag, {
  503. value: "Descriptor",
  504. configurable: !0
  505. }), "field" === e.kind && (r.initializer = e.initializer), r;
  506. },
  507. toElementDescriptors: function (e) {
  508. if (void 0 !== e) return _toArray(e).map(function (e) {
  509. var r = this.toElementDescriptor(e);
  510. return this.disallowProperty(e, "finisher", "An element descriptor"), this.disallowProperty(e, "extras", "An element descriptor"), r;
  511. }, this);
  512. },
  513. toElementDescriptor: function (e) {
  514. var r = e.kind + "";
  515. if ("method" !== r && "field" !== r) throw new TypeError('An element descriptor\'s .kind property must be either "method" or "field", but a decorator created an element descriptor with .kind "' + r + '"');
  516. var t = _toPropertyKey(e.key),
  517. i = e.placement + "";
  518. if ("static" !== i && "prototype" !== i && "own" !== i) throw new TypeError('An element descriptor\'s .placement property must be one of "static", "prototype" or "own", but a decorator created an element descriptor with .placement "' + i + '"');
  519. var o = e.descriptor;
  520. this.disallowProperty(e, "elements", "An element descriptor");
  521. var n = {
  522. kind: r,
  523. key: t,
  524. placement: i,
  525. descriptor: Object.assign({}, o)
  526. };
  527. return "field" !== r ? this.disallowProperty(e, "initializer", "A method descriptor") : (this.disallowProperty(o, "get", "The property descriptor of a field descriptor"), this.disallowProperty(o, "set", "The property descriptor of a field descriptor"), this.disallowProperty(o, "value", "The property descriptor of a field descriptor"), n.initializer = e.initializer), n;
  528. },
  529. toElementFinisherExtras: function (e) {
  530. return {
  531. element: this.toElementDescriptor(e),
  532. finisher: _optionalCallableProperty(e, "finisher"),
  533. extras: this.toElementDescriptors(e.extras)
  534. };
  535. },
  536. fromClassDescriptor: function (e) {
  537. var r = {
  538. kind: "class",
  539. elements: e.map(this.fromElementDescriptor, this)
  540. };
  541. return Object.defineProperty(r, Symbol.toStringTag, {
  542. value: "Descriptor",
  543. configurable: !0
  544. }), r;
  545. },
  546. toClassDescriptor: function (e) {
  547. var r = e.kind + "";
  548. if ("class" !== r) throw new TypeError('A class descriptor\'s .kind property must be "class", but a decorator created a class descriptor with .kind "' + r + '"');
  549. this.disallowProperty(e, "key", "A class descriptor"), this.disallowProperty(e, "placement", "A class descriptor"), this.disallowProperty(e, "descriptor", "A class descriptor"), this.disallowProperty(e, "initializer", "A class descriptor"), this.disallowProperty(e, "extras", "A class descriptor");
  550. var t = _optionalCallableProperty(e, "finisher");
  551. return {
  552. elements: this.toElementDescriptors(e.elements),
  553. finisher: t
  554. };
  555. },
  556. runClassFinishers: function (e, r) {
  557. for (var t = 0; t < r.length; t++) {
  558. var i = (0, r[t])(e);
  559. if (void 0 !== i) {
  560. if ("function" != typeof i) throw new TypeError("Finishers must return a constructor.");
  561. e = i;
  562. }
  563. }
  564. return e;
  565. },
  566. disallowProperty: function (e, r, t) {
  567. if (void 0 !== e[r]) throw new TypeError(t + " can't have a ." + r + " property.");
  568. }
  569. };
  570. return e;
  571. }
  572. function _createElementDescriptor(e) {
  573. var r,
  574. t = _toPropertyKey(e.key);
  575. "method" === e.kind ? r = {
  576. value: e.value,
  577. writable: !0,
  578. configurable: !0,
  579. enumerable: !1
  580. } : "get" === e.kind ? r = {
  581. get: e.value,
  582. configurable: !0,
  583. enumerable: !1
  584. } : "set" === e.kind ? r = {
  585. set: e.value,
  586. configurable: !0,
  587. enumerable: !1
  588. } : "field" === e.kind && (r = {
  589. configurable: !0,
  590. writable: !0,
  591. enumerable: !0
  592. });
  593. var i = {
  594. kind: "field" === e.kind ? "field" : "method",
  595. key: t,
  596. placement: e.static ? "static" : "field" === e.kind ? "own" : "prototype",
  597. descriptor: r
  598. };
  599. return e.decorators && (i.decorators = e.decorators), "field" === e.kind && (i.initializer = e.value), i;
  600. }
  601. function _coalesceGetterSetter(e, r) {
  602. void 0 !== e.descriptor.get ? r.descriptor.get = e.descriptor.get : r.descriptor.set = e.descriptor.set;
  603. }
  604. function _coalesceClassElements(e) {
  605. for (var r = [], isSameElement = function (e) {
  606. return "method" === e.kind && e.key === o.key && e.placement === o.placement;
  607. }, t = 0; t < e.length; t++) {
  608. var i,
  609. o = e[t];
  610. if ("method" === o.kind && (i = r.find(isSameElement))) {
  611. if (_isDataDescriptor(o.descriptor) || _isDataDescriptor(i.descriptor)) {
  612. if (_hasDecorators(o) || _hasDecorators(i)) throw new ReferenceError("Duplicated methods (" + o.key + ") can't be decorated.");
  613. i.descriptor = o.descriptor;
  614. } else {
  615. if (_hasDecorators(o)) {
  616. if (_hasDecorators(i)) throw new ReferenceError("Decorators can't be placed on different accessors with for the same property (" + o.key + ").");
  617. i.decorators = o.decorators;
  618. }
  619. _coalesceGetterSetter(o, i);
  620. }
  621. } else r.push(o);
  622. }
  623. return r;
  624. }
  625. function _hasDecorators(e) {
  626. return e.decorators && e.decorators.length;
  627. }
  628. function _isDataDescriptor(e) {
  629. return void 0 !== e && !(void 0 === e.value && void 0 === e.writable);
  630. }
  631. function _optionalCallableProperty(e, r) {
  632. var t = e[r];
  633. if (void 0 !== t && "function" != typeof t) throw new TypeError("Expected '" + r + "' to be a function");
  634. return t;
  635. }
  636. function _defaults(e, r) {
  637. for (var t = Object.getOwnPropertyNames(r), o = 0; o < t.length; o++) {
  638. var n = t[o],
  639. a = Object.getOwnPropertyDescriptor(r, n);
  640. a && a.configurable && void 0 === e[n] && Object.defineProperty(e, n, a);
  641. }
  642. return e;
  643. }
  644. function _defineAccessor(e, r, n, t) {
  645. var c = {
  646. configurable: !0,
  647. enumerable: !0
  648. };
  649. return c[e] = t, Object.defineProperty(r, n, c);
  650. }
  651. function _defineProperty(e, r, t) {
  652. return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
  653. value: t,
  654. enumerable: !0,
  655. configurable: !0,
  656. writable: !0
  657. }) : e[r] = t, e;
  658. }
  659. function _extends() {
  660. return _extends = Object.assign ? Object.assign.bind() : function (n) {
  661. for (var e = 1; e < arguments.length; e++) {
  662. var t = arguments[e];
  663. for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
  664. }
  665. return n;
  666. }, _extends.apply(null, arguments);
  667. }
  668. function _get() {
  669. return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
  670. var p = _superPropBase(e, t);
  671. if (p) {
  672. var n = Object.getOwnPropertyDescriptor(p, t);
  673. return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
  674. }
  675. }, _get.apply(null, arguments);
  676. }
  677. function _getPrototypeOf(t) {
  678. return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
  679. return t.__proto__ || Object.getPrototypeOf(t);
  680. }, _getPrototypeOf(t);
  681. }
  682. function _identity(t) {
  683. return t;
  684. }
  685. function _importDeferProxy(e) {
  686. var t = null,
  687. constValue = function (e) {
  688. return function () {
  689. return e;
  690. };
  691. },
  692. proxy = function (r) {
  693. return function (n, o, f) {
  694. return null === t && (t = e()), r(t, o, f);
  695. };
  696. };
  697. return new Proxy({}, {
  698. defineProperty: constValue(!1),
  699. deleteProperty: constValue(!1),
  700. get: proxy(Reflect.get),
  701. getOwnPropertyDescriptor: proxy(Reflect.getOwnPropertyDescriptor),
  702. getPrototypeOf: constValue(null),
  703. isExtensible: constValue(!1),
  704. has: proxy(Reflect.has),
  705. ownKeys: proxy(Reflect.ownKeys),
  706. preventExtensions: constValue(!0),
  707. set: constValue(!1),
  708. setPrototypeOf: constValue(!1)
  709. });
  710. }
  711. function _inherits(t, e) {
  712. if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
  713. t.prototype = Object.create(e && e.prototype, {
  714. constructor: {
  715. value: t,
  716. writable: !0,
  717. configurable: !0
  718. }
  719. }), Object.defineProperty(t, "prototype", {
  720. writable: !1
  721. }), e && _setPrototypeOf(t, e);
  722. }
  723. function _inheritsLoose(t, o) {
  724. t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
  725. }
  726. function _initializerDefineProperty(e, i, r, l) {
  727. r && Object.defineProperty(e, i, {
  728. enumerable: r.enumerable,
  729. configurable: r.configurable,
  730. writable: r.writable,
  731. value: r.initializer ? r.initializer.call(l) : void 0
  732. });
  733. }
  734. function _initializerWarningHelper(r, e) {
  735. throw Error("Decorating class property failed. Please ensure that transform-class-properties is enabled and runs after the decorators transform.");
  736. }
  737. function _instanceof(n, e) {
  738. return null != e && "undefined" != typeof Symbol && e[Symbol.hasInstance] ? !!e[Symbol.hasInstance](n) : n instanceof e;
  739. }
  740. function _interopRequireDefault(e) {
  741. return e && e.__esModule ? e : {
  742. default: e
  743. };
  744. }
  745. function _getRequireWildcardCache(e) {
  746. if ("function" != typeof WeakMap) return null;
  747. var r = new WeakMap(),
  748. t = new WeakMap();
  749. return (_getRequireWildcardCache = function (e) {
  750. return e ? t : r;
  751. })(e);
  752. }
  753. function _interopRequireWildcard(e, r) {
  754. if (!r && e && e.__esModule) return e;
  755. if (null === e || "object" != typeof e && "function" != typeof e) return {
  756. default: e
  757. };
  758. var t = _getRequireWildcardCache(r);
  759. if (t && t.has(e)) return t.get(e);
  760. var n = {
  761. __proto__: null
  762. },
  763. a = Object.defineProperty && Object.getOwnPropertyDescriptor;
  764. for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) {
  765. var i = a ? Object.getOwnPropertyDescriptor(e, u) : null;
  766. i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u];
  767. }
  768. return n.default = e, t && t.set(e, n), n;
  769. }
  770. function _isNativeFunction(t) {
  771. try {
  772. return -1 !== Function.toString.call(t).indexOf("[native code]");
  773. } catch (n) {
  774. return "function" == typeof t;
  775. }
  776. }
  777. function _isNativeReflectConstruct() {
  778. try {
  779. var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
  780. } catch (t) {}
  781. return (_isNativeReflectConstruct = function () {
  782. return !!t;
  783. })();
  784. }
  785. function _iterableToArray(r) {
  786. if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
  787. }
  788. function _iterableToArrayLimit(r, l) {
  789. var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
  790. if (null != t) {
  791. var e,
  792. n,
  793. i,
  794. u,
  795. a = [],
  796. f = !0,
  797. o = !1;
  798. try {
  799. if (i = (t = t.call(r)).next, 0 === l) {
  800. if (Object(t) !== t) return;
  801. f = !1;
  802. } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
  803. } catch (r) {
  804. o = !0, n = r;
  805. } finally {
  806. try {
  807. if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
  808. } finally {
  809. if (o) throw n;
  810. }
  811. }
  812. return a;
  813. }
  814. }
  815. var REACT_ELEMENT_TYPE;
  816. function _jsx(e, r, E, l) {
  817. REACT_ELEMENT_TYPE || (REACT_ELEMENT_TYPE = "function" == typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103);
  818. var o = e && e.defaultProps,
  819. n = arguments.length - 3;
  820. if (r || 0 === n || (r = {
  821. children: void 0
  822. }), 1 === n) r.children = l;else if (n > 1) {
  823. for (var t = Array(n), f = 0; f < n; f++) t[f] = arguments[f + 3];
  824. r.children = t;
  825. }
  826. if (r && o) for (var i in o) void 0 === r[i] && (r[i] = o[i]);else r || (r = o || {});
  827. return {
  828. $$typeof: REACT_ELEMENT_TYPE,
  829. type: e,
  830. key: void 0 === E ? null : "" + E,
  831. ref: null,
  832. props: r,
  833. _owner: null
  834. };
  835. }
  836. function _maybeArrayLike(r, a, e) {
  837. if (a && !Array.isArray(a) && "number" == typeof a.length) {
  838. var y = a.length;
  839. return _arrayLikeToArray(a, void 0 !== e && e < y ? e : y);
  840. }
  841. return r(a, e);
  842. }
  843. function _newArrowCheck(n, r) {
  844. if (n !== r) throw new TypeError("Cannot instantiate an arrow function");
  845. }
  846. function _nonIterableRest() {
  847. throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  848. }
  849. function _nonIterableSpread() {
  850. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  851. }
  852. function _nullishReceiverError(r) {
  853. throw new TypeError("Cannot set property of null or undefined.");
  854. }
  855. function _objectDestructuringEmpty(t) {
  856. if (null == t) throw new TypeError("Cannot destructure " + t);
  857. }
  858. function ownKeys(e, r) {
  859. var t = Object.keys(e);
  860. if (Object.getOwnPropertySymbols) {
  861. var o = Object.getOwnPropertySymbols(e);
  862. r && (o = o.filter(function (r) {
  863. return Object.getOwnPropertyDescriptor(e, r).enumerable;
  864. })), t.push.apply(t, o);
  865. }
  866. return t;
  867. }
  868. function _objectSpread2(e) {
  869. for (var r = 1; r < arguments.length; r++) {
  870. var t = null != arguments[r] ? arguments[r] : {};
  871. r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
  872. _defineProperty(e, r, t[r]);
  873. }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
  874. Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
  875. });
  876. }
  877. return e;
  878. }
  879. function _objectWithoutProperties(e, t) {
  880. if (null == e) return {};
  881. var o,
  882. r,
  883. i = _objectWithoutPropertiesLoose(e, t);
  884. if (Object.getOwnPropertySymbols) {
  885. var s = Object.getOwnPropertySymbols(e);
  886. for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
  887. }
  888. return i;
  889. }
  890. function _objectWithoutPropertiesLoose(r, e) {
  891. if (null == r) return {};
  892. var t = {};
  893. for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
  894. if (e.includes(n)) continue;
  895. t[n] = r[n];
  896. }
  897. return t;
  898. }
  899. function _possibleConstructorReturn(t, e) {
  900. if (e && ("object" == typeof e || "function" == typeof e)) return e;
  901. if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
  902. return _assertThisInitialized(t);
  903. }
  904. function _readOnlyError(r) {
  905. throw new TypeError('"' + r + '" is read-only');
  906. }
  907. function _regeneratorRuntime() {
  908. "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
  909. _regeneratorRuntime = function () {
  910. return e;
  911. };
  912. var t,
  913. e = {},
  914. r = Object.prototype,
  915. n = r.hasOwnProperty,
  916. o = Object.defineProperty || function (t, e, r) {
  917. t[e] = r.value;
  918. },
  919. i = "function" == typeof Symbol ? Symbol : {},
  920. a = i.iterator || "@@iterator",
  921. c = i.asyncIterator || "@@asyncIterator",
  922. u = i.toStringTag || "@@toStringTag";
  923. function define(t, e, r) {
  924. return Object.defineProperty(t, e, {
  925. value: r,
  926. enumerable: !0,
  927. configurable: !0,
  928. writable: !0
  929. }), t[e];
  930. }
  931. try {
  932. define({}, "");
  933. } catch (t) {
  934. define = function (t, e, r) {
  935. return t[e] = r;
  936. };
  937. }
  938. function wrap(t, e, r, n) {
  939. var i = e && e.prototype instanceof Generator ? e : Generator,
  940. a = Object.create(i.prototype),
  941. c = new Context(n || []);
  942. return o(a, "_invoke", {
  943. value: makeInvokeMethod(t, r, c)
  944. }), a;
  945. }
  946. function tryCatch(t, e, r) {
  947. try {
  948. return {
  949. type: "normal",
  950. arg: t.call(e, r)
  951. };
  952. } catch (t) {
  953. return {
  954. type: "throw",
  955. arg: t
  956. };
  957. }
  958. }
  959. e.wrap = wrap;
  960. var h = "suspendedStart",
  961. l = "suspendedYield",
  962. f = "executing",
  963. s = "completed",
  964. y = {};
  965. function Generator() {}
  966. function GeneratorFunction() {}
  967. function GeneratorFunctionPrototype() {}
  968. var p = {};
  969. define(p, a, function () {
  970. return this;
  971. });
  972. var d = Object.getPrototypeOf,
  973. v = d && d(d(values([])));
  974. v && v !== r && n.call(v, a) && (p = v);
  975. var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
  976. function defineIteratorMethods(t) {
  977. ["next", "throw", "return"].forEach(function (e) {
  978. define(t, e, function (t) {
  979. return this._invoke(e, t);
  980. });
  981. });
  982. }
  983. function AsyncIterator(t, e) {
  984. function invoke(r, o, i, a) {
  985. var c = tryCatch(t[r], t, o);
  986. if ("throw" !== c.type) {
  987. var u = c.arg,
  988. h = u.value;
  989. return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
  990. invoke("next", t, i, a);
  991. }, function (t) {
  992. invoke("throw", t, i, a);
  993. }) : e.resolve(h).then(function (t) {
  994. u.value = t, i(u);
  995. }, function (t) {
  996. return invoke("throw", t, i, a);
  997. });
  998. }
  999. a(c.arg);
  1000. }
  1001. var r;
  1002. o(this, "_invoke", {
  1003. value: function (t, n) {
  1004. function callInvokeWithMethodAndArg() {
  1005. return new e(function (e, r) {
  1006. invoke(t, n, e, r);
  1007. });
  1008. }
  1009. return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
  1010. }
  1011. });
  1012. }
  1013. function makeInvokeMethod(e, r, n) {
  1014. var o = h;
  1015. return function (i, a) {
  1016. if (o === f) throw Error("Generator is already running");
  1017. if (o === s) {
  1018. if ("throw" === i) throw a;
  1019. return {
  1020. value: t,
  1021. done: !0
  1022. };
  1023. }
  1024. for (n.method = i, n.arg = a;;) {
  1025. var c = n.delegate;
  1026. if (c) {
  1027. var u = maybeInvokeDelegate(c, n);
  1028. if (u) {
  1029. if (u === y) continue;
  1030. return u;
  1031. }
  1032. }
  1033. if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
  1034. if (o === h) throw o = s, n.arg;
  1035. n.dispatchException(n.arg);
  1036. } else "return" === n.method && n.abrupt("return", n.arg);
  1037. o = f;
  1038. var p = tryCatch(e, r, n);
  1039. if ("normal" === p.type) {
  1040. if (o = n.done ? s : l, p.arg === y) continue;
  1041. return {
  1042. value: p.arg,
  1043. done: n.done
  1044. };
  1045. }
  1046. "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
  1047. }
  1048. };
  1049. }
  1050. function maybeInvokeDelegate(e, r) {
  1051. var n = r.method,
  1052. o = e.iterator[n];
  1053. if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
  1054. var i = tryCatch(o, e.iterator, r.arg);
  1055. if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
  1056. var a = i.arg;
  1057. return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
  1058. }
  1059. function pushTryEntry(t) {
  1060. var e = {
  1061. tryLoc: t[0]
  1062. };
  1063. 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
  1064. }
  1065. function resetTryEntry(t) {
  1066. var e = t.completion || {};
  1067. e.type = "normal", delete e.arg, t.completion = e;
  1068. }
  1069. function Context(t) {
  1070. this.tryEntries = [{
  1071. tryLoc: "root"
  1072. }], t.forEach(pushTryEntry, this), this.reset(!0);
  1073. }
  1074. function values(e) {
  1075. if (e || "" === e) {
  1076. var r = e[a];
  1077. if (r) return r.call(e);
  1078. if ("function" == typeof e.next) return e;
  1079. if (!isNaN(e.length)) {
  1080. var o = -1,
  1081. i = function next() {
  1082. for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
  1083. return next.value = t, next.done = !0, next;
  1084. };
  1085. return i.next = i;
  1086. }
  1087. }
  1088. throw new TypeError(typeof e + " is not iterable");
  1089. }
  1090. return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
  1091. value: GeneratorFunctionPrototype,
  1092. configurable: !0
  1093. }), o(GeneratorFunctionPrototype, "constructor", {
  1094. value: GeneratorFunction,
  1095. configurable: !0
  1096. }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
  1097. var e = "function" == typeof t && t.constructor;
  1098. return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
  1099. }, e.mark = function (t) {
  1100. return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
  1101. }, e.awrap = function (t) {
  1102. return {
  1103. __await: t
  1104. };
  1105. }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
  1106. return this;
  1107. }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
  1108. void 0 === i && (i = Promise);
  1109. var a = new AsyncIterator(wrap(t, r, n, o), i);
  1110. return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
  1111. return t.done ? t.value : a.next();
  1112. });
  1113. }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
  1114. return this;
  1115. }), define(g, "toString", function () {
  1116. return "[object Generator]";
  1117. }), e.keys = function (t) {
  1118. var e = Object(t),
  1119. r = [];
  1120. for (var n in e) r.push(n);
  1121. return r.reverse(), function next() {
  1122. for (; r.length;) {
  1123. var t = r.pop();
  1124. if (t in e) return next.value = t, next.done = !1, next;
  1125. }
  1126. return next.done = !0, next;
  1127. };
  1128. }, e.values = values, Context.prototype = {
  1129. constructor: Context,
  1130. reset: function (e) {
  1131. if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
  1132. },
  1133. stop: function () {
  1134. this.done = !0;
  1135. var t = this.tryEntries[0].completion;
  1136. if ("throw" === t.type) throw t.arg;
  1137. return this.rval;
  1138. },
  1139. dispatchException: function (e) {
  1140. if (this.done) throw e;
  1141. var r = this;
  1142. function handle(n, o) {
  1143. return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
  1144. }
  1145. for (var o = this.tryEntries.length - 1; o >= 0; --o) {
  1146. var i = this.tryEntries[o],
  1147. a = i.completion;
  1148. if ("root" === i.tryLoc) return handle("end");
  1149. if (i.tryLoc <= this.prev) {
  1150. var c = n.call(i, "catchLoc"),
  1151. u = n.call(i, "finallyLoc");
  1152. if (c && u) {
  1153. if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
  1154. if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
  1155. } else if (c) {
  1156. if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
  1157. } else {
  1158. if (!u) throw Error("try statement without catch or finally");
  1159. if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
  1160. }
  1161. }
  1162. }
  1163. },
  1164. abrupt: function (t, e) {
  1165. for (var r = this.tryEntries.length - 1; r >= 0; --r) {
  1166. var o = this.tryEntries[r];
  1167. if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
  1168. var i = o;
  1169. break;
  1170. }
  1171. }
  1172. i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
  1173. var a = i ? i.completion : {};
  1174. return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
  1175. },
  1176. complete: function (t, e) {
  1177. if ("throw" === t.type) throw t.arg;
  1178. return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
  1179. },
  1180. finish: function (t) {
  1181. for (var e = this.tryEntries.length - 1; e >= 0; --e) {
  1182. var r = this.tryEntries[e];
  1183. if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
  1184. }
  1185. },
  1186. catch: function (t) {
  1187. for (var e = this.tryEntries.length - 1; e >= 0; --e) {
  1188. var r = this.tryEntries[e];
  1189. if (r.tryLoc === t) {
  1190. var n = r.completion;
  1191. if ("throw" === n.type) {
  1192. var o = n.arg;
  1193. resetTryEntry(r);
  1194. }
  1195. return o;
  1196. }
  1197. }
  1198. throw Error("illegal catch attempt");
  1199. },
  1200. delegateYield: function (e, r, n) {
  1201. return this.delegate = {
  1202. iterator: values(e),
  1203. resultName: r,
  1204. nextLoc: n
  1205. }, "next" === this.method && (this.arg = t), y;
  1206. }
  1207. }, e;
  1208. }
  1209. function set(e, r, t, o) {
  1210. return set = "undefined" != typeof Reflect && Reflect.set ? Reflect.set : function (e, r, t, o) {
  1211. var f,
  1212. i = _superPropBase(e, r);
  1213. if (i) {
  1214. if ((f = Object.getOwnPropertyDescriptor(i, r)).set) return f.set.call(o, t), !0;
  1215. if (!f.writable) return !1;
  1216. }
  1217. if (f = Object.getOwnPropertyDescriptor(o, r)) {
  1218. if (!f.writable) return !1;
  1219. f.value = t, Object.defineProperty(o, r, f);
  1220. } else _defineProperty(o, r, t);
  1221. return !0;
  1222. }, set(e, r, t, o);
  1223. }
  1224. function _set(e, r, t, o, f) {
  1225. if (!set(e, r, t, o || e) && f) throw new TypeError("failed to set property");
  1226. return t;
  1227. }
  1228. function _setFunctionName(e, t, n) {
  1229. "symbol" == typeof t && (t = (t = t.description) ? "[" + t + "]" : "");
  1230. try {
  1231. Object.defineProperty(e, "name", {
  1232. configurable: !0,
  1233. value: n ? n + " " + t : t
  1234. });
  1235. } catch (e) {}
  1236. return e;
  1237. }
  1238. function _setPrototypeOf(t, e) {
  1239. return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
  1240. return t.__proto__ = e, t;
  1241. }, _setPrototypeOf(t, e);
  1242. }
  1243. function _skipFirstGeneratorNext(t) {
  1244. return function () {
  1245. var r = t.apply(this, arguments);
  1246. return r.next(), r;
  1247. };
  1248. }
  1249. function _slicedToArray(r, e) {
  1250. return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
  1251. }
  1252. function _superPropBase(t, o) {
  1253. for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
  1254. return t;
  1255. }
  1256. function _superPropGet(t, e, r, o) {
  1257. var p = _get(_getPrototypeOf(1 & o ? t.prototype : t), e, r);
  1258. return 2 & o ? function (t) {
  1259. return p.apply(r, t);
  1260. } : p;
  1261. }
  1262. function _superPropSet(t, e, o, r, p, f) {
  1263. return _set(_getPrototypeOf(f ? t.prototype : t), e, o, r, p);
  1264. }
  1265. function _taggedTemplateLiteral(e, t) {
  1266. return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, {
  1267. raw: {
  1268. value: Object.freeze(t)
  1269. }
  1270. }));
  1271. }
  1272. function _taggedTemplateLiteralLoose(e, t) {
  1273. return t || (t = e.slice(0)), e.raw = t, e;
  1274. }
  1275. function _tdz(e) {
  1276. throw new ReferenceError(e + " is not defined - temporal dead zone");
  1277. }
  1278. function _temporalRef(r, e) {
  1279. return r === _temporalUndefined ? _tdz(e) : r;
  1280. }
  1281. function _temporalUndefined() {}
  1282. function _toArray(r) {
  1283. return _arrayWithHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableRest();
  1284. }
  1285. function _toConsumableArray(r) {
  1286. return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
  1287. }
  1288. function _toPrimitive(t, r) {
  1289. if ("object" != typeof t || !t) return t;
  1290. var e = t[Symbol.toPrimitive];
  1291. if (void 0 !== e) {
  1292. var i = e.call(t, r || "default");
  1293. if ("object" != typeof i) return i;
  1294. throw new TypeError("@@toPrimitive must return a primitive value.");
  1295. }
  1296. return ("string" === r ? String : Number)(t);
  1297. }
  1298. function _toPropertyKey(t) {
  1299. var i = _toPrimitive(t, "string");
  1300. return "symbol" == typeof i ? i : i + "";
  1301. }
  1302. function _toSetter(t, e, n) {
  1303. e || (e = []);
  1304. var r = e.length++;
  1305. return Object.defineProperty({}, "_", {
  1306. set: function (o) {
  1307. e[r] = o, t.apply(n, e);
  1308. }
  1309. });
  1310. }
  1311. function _typeof(o) {
  1312. "@babel/helpers - typeof";
  1313. return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
  1314. return typeof o;
  1315. } : function (o) {
  1316. return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
  1317. }, _typeof(o);
  1318. }
  1319. function _unsupportedIterableToArray(r, a) {
  1320. if (r) {
  1321. if ("string" == typeof r) return _arrayLikeToArray(r, a);
  1322. var t = {}.toString.call(r).slice(8, -1);
  1323. return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
  1324. }
  1325. }
  1326. function _usingCtx() {
  1327. var r = "function" == typeof SuppressedError ? SuppressedError : function (r, e) {
  1328. var n = Error();
  1329. return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
  1330. },
  1331. e = {},
  1332. n = [];
  1333. function using(r, e) {
  1334. if (null != e) {
  1335. if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
  1336. if (r) var o = e[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
  1337. if (void 0 === o && (o = e[Symbol.dispose || Symbol.for("Symbol.dispose")], r)) var t = o;
  1338. if ("function" != typeof o) throw new TypeError("Object is not disposable.");
  1339. t && (o = function () {
  1340. try {
  1341. t.call(e);
  1342. } catch (r) {
  1343. return Promise.reject(r);
  1344. }
  1345. }), n.push({
  1346. v: e,
  1347. d: o,
  1348. a: r
  1349. });
  1350. } else r && n.push({
  1351. d: e,
  1352. a: r
  1353. });
  1354. return e;
  1355. }
  1356. return {
  1357. e: e,
  1358. u: using.bind(null, !1),
  1359. a: using.bind(null, !0),
  1360. d: function () {
  1361. var o,
  1362. t = this.e,
  1363. s = 0;
  1364. function next() {
  1365. for (; o = n.pop();) try {
  1366. if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
  1367. if (o.d) {
  1368. var r = o.d.call(o.v);
  1369. if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
  1370. } else s |= 1;
  1371. } catch (r) {
  1372. return err(r);
  1373. }
  1374. if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
  1375. if (t !== e) throw t;
  1376. }
  1377. function err(n) {
  1378. return t = t !== e ? new r(n, t) : n, next();
  1379. }
  1380. return next();
  1381. }
  1382. };
  1383. }
  1384. function _wrapAsyncGenerator(e) {
  1385. return function () {
  1386. return new AsyncGenerator(e.apply(this, arguments));
  1387. };
  1388. }
  1389. function AsyncGenerator(e) {
  1390. var r, t;
  1391. function resume(r, t) {
  1392. try {
  1393. var n = e[r](t),
  1394. o = n.value,
  1395. u = o instanceof _OverloadYield;
  1396. Promise.resolve(u ? o.v : o).then(function (t) {
  1397. if (u) {
  1398. var i = "return" === r ? "return" : "next";
  1399. if (!o.k || t.done) return resume(i, t);
  1400. t = e[i](t).value;
  1401. }
  1402. settle(n.done ? "return" : "normal", t);
  1403. }, function (e) {
  1404. resume("throw", e);
  1405. });
  1406. } catch (e) {
  1407. settle("throw", e);
  1408. }
  1409. }
  1410. function settle(e, n) {
  1411. switch (e) {
  1412. case "return":
  1413. r.resolve({
  1414. value: n,
  1415. done: !0
  1416. });
  1417. break;
  1418. case "throw":
  1419. r.reject(n);
  1420. break;
  1421. default:
  1422. r.resolve({
  1423. value: n,
  1424. done: !1
  1425. });
  1426. }
  1427. (r = r.next) ? resume(r.key, r.arg) : t = null;
  1428. }
  1429. this._invoke = function (e, n) {
  1430. return new Promise(function (o, u) {
  1431. var i = {
  1432. key: e,
  1433. arg: n,
  1434. resolve: o,
  1435. reject: u,
  1436. next: null
  1437. };
  1438. t ? t = t.next = i : (r = t = i, resume(e, n));
  1439. });
  1440. }, "function" != typeof e.return && (this.return = void 0);
  1441. }
  1442. AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function () {
  1443. return this;
  1444. }, AsyncGenerator.prototype.next = function (e) {
  1445. return this._invoke("next", e);
  1446. }, AsyncGenerator.prototype.throw = function (e) {
  1447. return this._invoke("throw", e);
  1448. }, AsyncGenerator.prototype.return = function (e) {
  1449. return this._invoke("return", e);
  1450. };
  1451. function _wrapNativeSuper(t) {
  1452. var r = "function" == typeof Map ? new Map() : void 0;
  1453. return _wrapNativeSuper = function (t) {
  1454. if (null === t || !_isNativeFunction(t)) return t;
  1455. if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
  1456. if (void 0 !== r) {
  1457. if (r.has(t)) return r.get(t);
  1458. r.set(t, Wrapper);
  1459. }
  1460. function Wrapper() {
  1461. return _construct(t, arguments, _getPrototypeOf(this).constructor);
  1462. }
  1463. return Wrapper.prototype = Object.create(t.prototype, {
  1464. constructor: {
  1465. value: Wrapper,
  1466. enumerable: !1,
  1467. writable: !0,
  1468. configurable: !0
  1469. }
  1470. }), _setPrototypeOf(Wrapper, t);
  1471. }, _wrapNativeSuper(t);
  1472. }
  1473. function _wrapRegExp() {
  1474. _wrapRegExp = function (e, r) {
  1475. return new BabelRegExp(e, void 0, r);
  1476. };
  1477. var e = RegExp.prototype,
  1478. r = new WeakMap();
  1479. function BabelRegExp(e, t, p) {
  1480. var o = RegExp(e, t);
  1481. return r.set(o, p || r.get(e)), _setPrototypeOf(o, BabelRegExp.prototype);
  1482. }
  1483. function buildGroups(e, t) {
  1484. var p = r.get(t);
  1485. return Object.keys(p).reduce(function (r, t) {
  1486. var o = p[t];
  1487. if ("number" == typeof o) r[t] = e[o];else {
  1488. for (var i = 0; void 0 === e[o[i]] && i + 1 < o.length;) i++;
  1489. r[t] = e[o[i]];
  1490. }
  1491. return r;
  1492. }, Object.create(null));
  1493. }
  1494. return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (r) {
  1495. var t = e.exec.call(this, r);
  1496. if (t) {
  1497. t.groups = buildGroups(t, this);
  1498. var p = t.indices;
  1499. p && (p.groups = buildGroups(p, this));
  1500. }
  1501. return t;
  1502. }, BabelRegExp.prototype[Symbol.replace] = function (t, p) {
  1503. if ("string" == typeof p) {
  1504. var o = r.get(this);
  1505. return e[Symbol.replace].call(this, t, p.replace(/\$<([^>]+)>/g, function (e, r) {
  1506. var t = o[r];
  1507. return "$" + (Array.isArray(t) ? t.join("$") : t);
  1508. }));
  1509. }
  1510. if ("function" == typeof p) {
  1511. var i = this;
  1512. return e[Symbol.replace].call(this, t, function () {
  1513. var e = arguments;
  1514. return "object" != typeof e[e.length - 1] && (e = [].slice.call(e)).push(buildGroups(e, i)), p.apply(this, e);
  1515. });
  1516. }
  1517. return e[Symbol.replace].call(this, t, p);
  1518. }, _wrapRegExp.apply(this, arguments);
  1519. }
  1520. function _writeOnlyError(r) {
  1521. throw new TypeError('"' + r + '" is write-only');
  1522. }
  1523. function _AwaitValue(t) {
  1524. this.wrapped = t;
  1525. }
  1526. function old_createMetadataMethodsForProperty(e, t, a, r) {
  1527. return {
  1528. getMetadata: function (o) {
  1529. old_assertNotFinished(r, "getMetadata"), old_assertMetadataKey(o);
  1530. var i = e[o];
  1531. if (void 0 !== i) if (1 === t) {
  1532. var n = i.public;
  1533. if (void 0 !== n) return n[a];
  1534. } else if (2 === t) {
  1535. var l = i.private;
  1536. if (void 0 !== l) return l.get(a);
  1537. } else if (Object.hasOwnProperty.call(i, "constructor")) return i.constructor;
  1538. },
  1539. setMetadata: function (o, i) {
  1540. old_assertNotFinished(r, "setMetadata"), old_assertMetadataKey(o);
  1541. var n = e[o];
  1542. if (void 0 === n && (n = e[o] = {}), 1 === t) {
  1543. var l = n.public;
  1544. void 0 === l && (l = n.public = {}), l[a] = i;
  1545. } else if (2 === t) {
  1546. var s = n.priv;
  1547. void 0 === s && (s = n.private = new Map()), s.set(a, i);
  1548. } else n.constructor = i;
  1549. }
  1550. };
  1551. }
  1552. function old_convertMetadataMapToFinal(e, t) {
  1553. var a = e[Symbol.metadata || Symbol.for("Symbol.metadata")],
  1554. r = Object.getOwnPropertySymbols(t);
  1555. if (0 !== r.length) {
  1556. for (var o = 0; o < r.length; o++) {
  1557. var i = r[o],
  1558. n = t[i],
  1559. l = a ? a[i] : null,
  1560. s = n.public,
  1561. c = l ? l.public : null;
  1562. s && c && Object.setPrototypeOf(s, c);
  1563. var d = n.private;
  1564. if (d) {
  1565. var u = Array.from(d.values()),
  1566. f = l ? l.private : null;
  1567. f && (u = u.concat(f)), n.private = u;
  1568. }
  1569. l && Object.setPrototypeOf(n, l);
  1570. }
  1571. a && Object.setPrototypeOf(t, a), e[Symbol.metadata || Symbol.for("Symbol.metadata")] = t;
  1572. }
  1573. }
  1574. function old_createAddInitializerMethod(e, t) {
  1575. return function (a) {
  1576. old_assertNotFinished(t, "addInitializer"), old_assertCallable(a, "An initializer"), e.push(a);
  1577. };
  1578. }
  1579. function old_memberDec(e, t, a, r, o, i, n, l, s) {
  1580. var c;
  1581. switch (i) {
  1582. case 1:
  1583. c = "accessor";
  1584. break;
  1585. case 2:
  1586. c = "method";
  1587. break;
  1588. case 3:
  1589. c = "getter";
  1590. break;
  1591. case 4:
  1592. c = "setter";
  1593. break;
  1594. default:
  1595. c = "field";
  1596. }
  1597. var d,
  1598. u,
  1599. f = {
  1600. kind: c,
  1601. name: l ? "#" + t : _toPropertyKey(t),
  1602. isStatic: n,
  1603. isPrivate: l
  1604. },
  1605. p = {
  1606. v: !1
  1607. };
  1608. if (0 !== i && (f.addInitializer = old_createAddInitializerMethod(o, p)), l) {
  1609. d = 2, u = Symbol(t);
  1610. var v = {};
  1611. 0 === i ? (v.get = a.get, v.set = a.set) : 2 === i ? v.get = function () {
  1612. return a.value;
  1613. } : (1 !== i && 3 !== i || (v.get = function () {
  1614. return a.get.call(this);
  1615. }), 1 !== i && 4 !== i || (v.set = function (e) {
  1616. a.set.call(this, e);
  1617. })), f.access = v;
  1618. } else d = 1, u = t;
  1619. try {
  1620. return e(s, Object.assign(f, old_createMetadataMethodsForProperty(r, d, u, p)));
  1621. } finally {
  1622. p.v = !0;
  1623. }
  1624. }
  1625. function old_assertNotFinished(e, t) {
  1626. if (e.v) throw Error("attempted to call " + t + " after decoration was finished");
  1627. }
  1628. function old_assertMetadataKey(e) {
  1629. if ("symbol" != typeof e) throw new TypeError("Metadata keys must be symbols, received: " + e);
  1630. }
  1631. function old_assertCallable(e, t) {
  1632. if ("function" != typeof e) throw new TypeError(t + " must be a function");
  1633. }
  1634. function old_assertValidReturnValue(e, t) {
  1635. var a = typeof t;
  1636. if (1 === e) {
  1637. if ("object" !== a || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
  1638. void 0 !== t.get && old_assertCallable(t.get, "accessor.get"), void 0 !== t.set && old_assertCallable(t.set, "accessor.set"), void 0 !== t.init && old_assertCallable(t.init, "accessor.init"), void 0 !== t.initializer && old_assertCallable(t.initializer, "accessor.initializer");
  1639. } else if ("function" !== a) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
  1640. }
  1641. function old_getInit(e) {
  1642. var t;
  1643. return null == (t = e.init) && (t = e.initializer) && void 0 !== console && console.warn(".initializer has been renamed to .init as of March 2022"), t;
  1644. }
  1645. function old_applyMemberDec(e, t, a, r, o, i, n, l, s) {
  1646. var c,
  1647. d,
  1648. u,
  1649. f,
  1650. p,
  1651. v,
  1652. y,
  1653. h = a[0];
  1654. if (n ? (0 === o || 1 === o ? (c = {
  1655. get: a[3],
  1656. set: a[4]
  1657. }, u = "get") : 3 === o ? (c = {
  1658. get: a[3]
  1659. }, u = "get") : 4 === o ? (c = {
  1660. set: a[3]
  1661. }, u = "set") : c = {
  1662. value: a[3]
  1663. }, 0 !== o && (1 === o && _setFunctionName(a[4], "#" + r, "set"), _setFunctionName(a[3], "#" + r, u))) : 0 !== o && (c = Object.getOwnPropertyDescriptor(t, r)), 1 === o ? f = {
  1664. get: c.get,
  1665. set: c.set
  1666. } : 2 === o ? f = c.value : 3 === o ? f = c.get : 4 === o && (f = c.set), "function" == typeof h) void 0 !== (p = old_memberDec(h, r, c, l, s, o, i, n, f)) && (old_assertValidReturnValue(o, p), 0 === o ? d = p : 1 === o ? (d = old_getInit(p), v = p.get || f.get, y = p.set || f.set, f = {
  1667. get: v,
  1668. set: y
  1669. }) : f = p);else for (var m = h.length - 1; m >= 0; m--) {
  1670. var b;
  1671. void 0 !== (p = old_memberDec(h[m], r, c, l, s, o, i, n, f)) && (old_assertValidReturnValue(o, p), 0 === o ? b = p : 1 === o ? (b = old_getInit(p), v = p.get || f.get, y = p.set || f.set, f = {
  1672. get: v,
  1673. set: y
  1674. }) : f = p, void 0 !== b && (void 0 === d ? d = b : "function" == typeof d ? d = [d, b] : d.push(b)));
  1675. }
  1676. if (0 === o || 1 === o) {
  1677. if (void 0 === d) d = function (e, t) {
  1678. return t;
  1679. };else if ("function" != typeof d) {
  1680. var g = d;
  1681. d = function (e, t) {
  1682. for (var a = t, r = 0; r < g.length; r++) a = g[r].call(e, a);
  1683. return a;
  1684. };
  1685. } else {
  1686. var _ = d;
  1687. d = function (e, t) {
  1688. return _.call(e, t);
  1689. };
  1690. }
  1691. e.push(d);
  1692. }
  1693. 0 !== o && (1 === o ? (c.get = f.get, c.set = f.set) : 2 === o ? c.value = f : 3 === o ? c.get = f : 4 === o && (c.set = f), n ? 1 === o ? (e.push(function (e, t) {
  1694. return f.get.call(e, t);
  1695. }), e.push(function (e, t) {
  1696. return f.set.call(e, t);
  1697. })) : 2 === o ? e.push(f) : e.push(function (e, t) {
  1698. return f.call(e, t);
  1699. }) : Object.defineProperty(t, r, c));
  1700. }
  1701. function old_applyMemberDecs(e, t, a, r, o) {
  1702. for (var i, n, l = new Map(), s = new Map(), c = 0; c < o.length; c++) {
  1703. var d = o[c];
  1704. if (Array.isArray(d)) {
  1705. var u,
  1706. f,
  1707. p,
  1708. v = d[1],
  1709. y = d[2],
  1710. h = d.length > 3,
  1711. m = v >= 5;
  1712. if (m ? (u = t, f = r, 0 != (v -= 5) && (p = n = n || [])) : (u = t.prototype, f = a, 0 !== v && (p = i = i || [])), 0 !== v && !h) {
  1713. var b = m ? s : l,
  1714. g = b.get(y) || 0;
  1715. if (!0 === g || 3 === g && 4 !== v || 4 === g && 3 !== v) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + y);
  1716. !g && v > 2 ? b.set(y, v) : b.set(y, !0);
  1717. }
  1718. old_applyMemberDec(e, u, d, y, v, m, h, f, p);
  1719. }
  1720. }
  1721. old_pushInitializers(e, i), old_pushInitializers(e, n);
  1722. }
  1723. function old_pushInitializers(e, t) {
  1724. t && e.push(function (e) {
  1725. for (var a = 0; a < t.length; a++) t[a].call(e);
  1726. return e;
  1727. });
  1728. }
  1729. function old_applyClassDecs(e, t, a, r) {
  1730. if (r.length > 0) {
  1731. for (var o = [], i = t, n = t.name, l = r.length - 1; l >= 0; l--) {
  1732. var s = {
  1733. v: !1
  1734. };
  1735. try {
  1736. var c = Object.assign({
  1737. kind: "class",
  1738. name: n,
  1739. addInitializer: old_createAddInitializerMethod(o, s)
  1740. }, old_createMetadataMethodsForProperty(a, 0, n, s)),
  1741. d = r[l](i, c);
  1742. } finally {
  1743. s.v = !0;
  1744. }
  1745. void 0 !== d && (old_assertValidReturnValue(10, d), i = d);
  1746. }
  1747. e.push(i, function () {
  1748. for (var e = 0; e < o.length; e++) o[e].call(i);
  1749. });
  1750. }
  1751. }
  1752. function _applyDecs(e, t, a) {
  1753. var r = [],
  1754. o = {},
  1755. i = {};
  1756. return old_applyMemberDecs(r, e, i, o, t), old_convertMetadataMapToFinal(e.prototype, i), old_applyClassDecs(r, e, o, a), old_convertMetadataMapToFinal(e, o), r;
  1757. }
  1758. function applyDecs2203Factory() {
  1759. function createAddInitializerMethod(e, t) {
  1760. return function (r) {
  1761. !function (e, t) {
  1762. if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
  1763. }(t), assertCallable(r, "An initializer"), e.push(r);
  1764. };
  1765. }
  1766. function memberDec(e, t, r, a, n, i, s, o) {
  1767. var c;
  1768. switch (n) {
  1769. case 1:
  1770. c = "accessor";
  1771. break;
  1772. case 2:
  1773. c = "method";
  1774. break;
  1775. case 3:
  1776. c = "getter";
  1777. break;
  1778. case 4:
  1779. c = "setter";
  1780. break;
  1781. default:
  1782. c = "field";
  1783. }
  1784. var l,
  1785. u,
  1786. f = {
  1787. kind: c,
  1788. name: s ? "#" + t : t,
  1789. static: i,
  1790. private: s
  1791. },
  1792. p = {
  1793. v: !1
  1794. };
  1795. 0 !== n && (f.addInitializer = createAddInitializerMethod(a, p)), 0 === n ? s ? (l = r.get, u = r.set) : (l = function () {
  1796. return this[t];
  1797. }, u = function (e) {
  1798. this[t] = e;
  1799. }) : 2 === n ? l = function () {
  1800. return r.value;
  1801. } : (1 !== n && 3 !== n || (l = function () {
  1802. return r.get.call(this);
  1803. }), 1 !== n && 4 !== n || (u = function (e) {
  1804. r.set.call(this, e);
  1805. })), f.access = l && u ? {
  1806. get: l,
  1807. set: u
  1808. } : l ? {
  1809. get: l
  1810. } : {
  1811. set: u
  1812. };
  1813. try {
  1814. return e(o, f);
  1815. } finally {
  1816. p.v = !0;
  1817. }
  1818. }
  1819. function assertCallable(e, t) {
  1820. if ("function" != typeof e) throw new TypeError(t + " must be a function");
  1821. }
  1822. function assertValidReturnValue(e, t) {
  1823. var r = typeof t;
  1824. if (1 === e) {
  1825. if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
  1826. void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
  1827. } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
  1828. }
  1829. function applyMemberDec(e, t, r, a, n, i, s, o) {
  1830. var c,
  1831. l,
  1832. u,
  1833. f,
  1834. p,
  1835. d,
  1836. h = r[0];
  1837. if (s ? c = 0 === n || 1 === n ? {
  1838. get: r[3],
  1839. set: r[4]
  1840. } : 3 === n ? {
  1841. get: r[3]
  1842. } : 4 === n ? {
  1843. set: r[3]
  1844. } : {
  1845. value: r[3]
  1846. } : 0 !== n && (c = Object.getOwnPropertyDescriptor(t, a)), 1 === n ? u = {
  1847. get: c.get,
  1848. set: c.set
  1849. } : 2 === n ? u = c.value : 3 === n ? u = c.get : 4 === n && (u = c.set), "function" == typeof h) void 0 !== (f = memberDec(h, a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? l = f : 1 === n ? (l = f.init, p = f.get || u.get, d = f.set || u.set, u = {
  1850. get: p,
  1851. set: d
  1852. }) : u = f);else for (var v = h.length - 1; v >= 0; v--) {
  1853. var g;
  1854. void 0 !== (f = memberDec(h[v], a, c, o, n, i, s, u)) && (assertValidReturnValue(n, f), 0 === n ? g = f : 1 === n ? (g = f.init, p = f.get || u.get, d = f.set || u.set, u = {
  1855. get: p,
  1856. set: d
  1857. }) : u = f, void 0 !== g && (void 0 === l ? l = g : "function" == typeof l ? l = [l, g] : l.push(g)));
  1858. }
  1859. if (0 === n || 1 === n) {
  1860. if (void 0 === l) l = function (e, t) {
  1861. return t;
  1862. };else if ("function" != typeof l) {
  1863. var y = l;
  1864. l = function (e, t) {
  1865. for (var r = t, a = 0; a < y.length; a++) r = y[a].call(e, r);
  1866. return r;
  1867. };
  1868. } else {
  1869. var m = l;
  1870. l = function (e, t) {
  1871. return m.call(e, t);
  1872. };
  1873. }
  1874. e.push(l);
  1875. }
  1876. 0 !== n && (1 === n ? (c.get = u.get, c.set = u.set) : 2 === n ? c.value = u : 3 === n ? c.get = u : 4 === n && (c.set = u), s ? 1 === n ? (e.push(function (e, t) {
  1877. return u.get.call(e, t);
  1878. }), e.push(function (e, t) {
  1879. return u.set.call(e, t);
  1880. })) : 2 === n ? e.push(u) : e.push(function (e, t) {
  1881. return u.call(e, t);
  1882. }) : Object.defineProperty(t, a, c));
  1883. }
  1884. function pushInitializers(e, t) {
  1885. t && e.push(function (e) {
  1886. for (var r = 0; r < t.length; r++) t[r].call(e);
  1887. return e;
  1888. });
  1889. }
  1890. return function (e, t, r) {
  1891. var a = [];
  1892. return function (e, t, r) {
  1893. for (var a, n, i = new Map(), s = new Map(), o = 0; o < r.length; o++) {
  1894. var c = r[o];
  1895. if (Array.isArray(c)) {
  1896. var l,
  1897. u,
  1898. f = c[1],
  1899. p = c[2],
  1900. d = c.length > 3,
  1901. h = f >= 5;
  1902. if (h ? (l = t, 0 != (f -= 5) && (u = n = n || [])) : (l = t.prototype, 0 !== f && (u = a = a || [])), 0 !== f && !d) {
  1903. var v = h ? s : i,
  1904. g = v.get(p) || 0;
  1905. if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p);
  1906. !g && f > 2 ? v.set(p, f) : v.set(p, !0);
  1907. }
  1908. applyMemberDec(e, l, c, p, f, h, d, u);
  1909. }
  1910. }
  1911. pushInitializers(e, a), pushInitializers(e, n);
  1912. }(a, e, t), function (e, t, r) {
  1913. if (r.length > 0) {
  1914. for (var a = [], n = t, i = t.name, s = r.length - 1; s >= 0; s--) {
  1915. var o = {
  1916. v: !1
  1917. };
  1918. try {
  1919. var c = r[s](n, {
  1920. kind: "class",
  1921. name: i,
  1922. addInitializer: createAddInitializerMethod(a, o)
  1923. });
  1924. } finally {
  1925. o.v = !0;
  1926. }
  1927. void 0 !== c && (assertValidReturnValue(10, c), n = c);
  1928. }
  1929. e.push(n, function () {
  1930. for (var e = 0; e < a.length; e++) a[e].call(n);
  1931. });
  1932. }
  1933. }(a, e, r), a;
  1934. };
  1935. }
  1936. var applyDecs2203Impl;
  1937. function _applyDecs2203(e, t, r) {
  1938. return (applyDecs2203Impl = applyDecs2203Impl || applyDecs2203Factory())(e, t, r);
  1939. }
  1940. function applyDecs2203RFactory() {
  1941. function createAddInitializerMethod(e, t) {
  1942. return function (r) {
  1943. !function (e, t) {
  1944. if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
  1945. }(t), assertCallable(r, "An initializer"), e.push(r);
  1946. };
  1947. }
  1948. function memberDec(e, t, r, n, a, i, o, s) {
  1949. var c;
  1950. switch (a) {
  1951. case 1:
  1952. c = "accessor";
  1953. break;
  1954. case 2:
  1955. c = "method";
  1956. break;
  1957. case 3:
  1958. c = "getter";
  1959. break;
  1960. case 4:
  1961. c = "setter";
  1962. break;
  1963. default:
  1964. c = "field";
  1965. }
  1966. var l,
  1967. u,
  1968. f = {
  1969. kind: c,
  1970. name: o ? "#" + t : _toPropertyKey(t),
  1971. static: i,
  1972. private: o
  1973. },
  1974. p = {
  1975. v: !1
  1976. };
  1977. 0 !== a && (f.addInitializer = createAddInitializerMethod(n, p)), 0 === a ? o ? (l = r.get, u = r.set) : (l = function () {
  1978. return this[t];
  1979. }, u = function (e) {
  1980. this[t] = e;
  1981. }) : 2 === a ? l = function () {
  1982. return r.value;
  1983. } : (1 !== a && 3 !== a || (l = function () {
  1984. return r.get.call(this);
  1985. }), 1 !== a && 4 !== a || (u = function (e) {
  1986. r.set.call(this, e);
  1987. })), f.access = l && u ? {
  1988. get: l,
  1989. set: u
  1990. } : l ? {
  1991. get: l
  1992. } : {
  1993. set: u
  1994. };
  1995. try {
  1996. return e(s, f);
  1997. } finally {
  1998. p.v = !0;
  1999. }
  2000. }
  2001. function assertCallable(e, t) {
  2002. if ("function" != typeof e) throw new TypeError(t + " must be a function");
  2003. }
  2004. function assertValidReturnValue(e, t) {
  2005. var r = typeof t;
  2006. if (1 === e) {
  2007. if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
  2008. void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
  2009. } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
  2010. }
  2011. function applyMemberDec(e, t, r, n, a, i, o, s) {
  2012. var c,
  2013. l,
  2014. u,
  2015. f,
  2016. p,
  2017. d,
  2018. h,
  2019. v = r[0];
  2020. if (o ? (0 === a || 1 === a ? (c = {
  2021. get: r[3],
  2022. set: r[4]
  2023. }, u = "get") : 3 === a ? (c = {
  2024. get: r[3]
  2025. }, u = "get") : 4 === a ? (c = {
  2026. set: r[3]
  2027. }, u = "set") : c = {
  2028. value: r[3]
  2029. }, 0 !== a && (1 === a && _setFunctionName(r[4], "#" + n, "set"), _setFunctionName(r[3], "#" + n, u))) : 0 !== a && (c = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? f = {
  2030. get: c.get,
  2031. set: c.set
  2032. } : 2 === a ? f = c.value : 3 === a ? f = c.get : 4 === a && (f = c.set), "function" == typeof v) void 0 !== (p = memberDec(v, n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? l = p : 1 === a ? (l = p.init, d = p.get || f.get, h = p.set || f.set, f = {
  2033. get: d,
  2034. set: h
  2035. }) : f = p);else for (var g = v.length - 1; g >= 0; g--) {
  2036. var y;
  2037. void 0 !== (p = memberDec(v[g], n, c, s, a, i, o, f)) && (assertValidReturnValue(a, p), 0 === a ? y = p : 1 === a ? (y = p.init, d = p.get || f.get, h = p.set || f.set, f = {
  2038. get: d,
  2039. set: h
  2040. }) : f = p, void 0 !== y && (void 0 === l ? l = y : "function" == typeof l ? l = [l, y] : l.push(y)));
  2041. }
  2042. if (0 === a || 1 === a) {
  2043. if (void 0 === l) l = function (e, t) {
  2044. return t;
  2045. };else if ("function" != typeof l) {
  2046. var m = l;
  2047. l = function (e, t) {
  2048. for (var r = t, n = 0; n < m.length; n++) r = m[n].call(e, r);
  2049. return r;
  2050. };
  2051. } else {
  2052. var b = l;
  2053. l = function (e, t) {
  2054. return b.call(e, t);
  2055. };
  2056. }
  2057. e.push(l);
  2058. }
  2059. 0 !== a && (1 === a ? (c.get = f.get, c.set = f.set) : 2 === a ? c.value = f : 3 === a ? c.get = f : 4 === a && (c.set = f), o ? 1 === a ? (e.push(function (e, t) {
  2060. return f.get.call(e, t);
  2061. }), e.push(function (e, t) {
  2062. return f.set.call(e, t);
  2063. })) : 2 === a ? e.push(f) : e.push(function (e, t) {
  2064. return f.call(e, t);
  2065. }) : Object.defineProperty(t, n, c));
  2066. }
  2067. function applyMemberDecs(e, t) {
  2068. for (var r, n, a = [], i = new Map(), o = new Map(), s = 0; s < t.length; s++) {
  2069. var c = t[s];
  2070. if (Array.isArray(c)) {
  2071. var l,
  2072. u,
  2073. f = c[1],
  2074. p = c[2],
  2075. d = c.length > 3,
  2076. h = f >= 5;
  2077. if (h ? (l = e, 0 != (f -= 5) && (u = n = n || [])) : (l = e.prototype, 0 !== f && (u = r = r || [])), 0 !== f && !d) {
  2078. var v = h ? o : i,
  2079. g = v.get(p) || 0;
  2080. if (!0 === g || 3 === g && 4 !== f || 4 === g && 3 !== f) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + p);
  2081. !g && f > 2 ? v.set(p, f) : v.set(p, !0);
  2082. }
  2083. applyMemberDec(a, l, c, p, f, h, d, u);
  2084. }
  2085. }
  2086. return pushInitializers(a, r), pushInitializers(a, n), a;
  2087. }
  2088. function pushInitializers(e, t) {
  2089. t && e.push(function (e) {
  2090. for (var r = 0; r < t.length; r++) t[r].call(e);
  2091. return e;
  2092. });
  2093. }
  2094. return function (e, t, r) {
  2095. return {
  2096. e: applyMemberDecs(e, t),
  2097. get c() {
  2098. return function (e, t) {
  2099. if (t.length > 0) {
  2100. for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) {
  2101. var o = {
  2102. v: !1
  2103. };
  2104. try {
  2105. var s = t[i](n, {
  2106. kind: "class",
  2107. name: a,
  2108. addInitializer: createAddInitializerMethod(r, o)
  2109. });
  2110. } finally {
  2111. o.v = !0;
  2112. }
  2113. void 0 !== s && (assertValidReturnValue(10, s), n = s);
  2114. }
  2115. return [n, function () {
  2116. for (var e = 0; e < r.length; e++) r[e].call(n);
  2117. }];
  2118. }
  2119. }(e, r);
  2120. }
  2121. };
  2122. };
  2123. }
  2124. function _applyDecs2203R(e, t, r) {
  2125. return (_applyDecs2203R = applyDecs2203RFactory())(e, t, r);
  2126. }
  2127. function applyDecs2301Factory() {
  2128. function createAddInitializerMethod(e, t) {
  2129. return function (r) {
  2130. !function (e, t) {
  2131. if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
  2132. }(t), assertCallable(r, "An initializer"), e.push(r);
  2133. };
  2134. }
  2135. function assertInstanceIfPrivate(e, t) {
  2136. if (!e(t)) throw new TypeError("Attempted to access private element on non-instance");
  2137. }
  2138. function memberDec(e, t, r, n, a, i, s, o, c) {
  2139. var u;
  2140. switch (a) {
  2141. case 1:
  2142. u = "accessor";
  2143. break;
  2144. case 2:
  2145. u = "method";
  2146. break;
  2147. case 3:
  2148. u = "getter";
  2149. break;
  2150. case 4:
  2151. u = "setter";
  2152. break;
  2153. default:
  2154. u = "field";
  2155. }
  2156. var l,
  2157. f,
  2158. p = {
  2159. kind: u,
  2160. name: s ? "#" + t : _toPropertyKey(t),
  2161. static: i,
  2162. private: s
  2163. },
  2164. d = {
  2165. v: !1
  2166. };
  2167. if (0 !== a && (p.addInitializer = createAddInitializerMethod(n, d)), s || 0 !== a && 2 !== a) {
  2168. if (2 === a) l = function (e) {
  2169. return assertInstanceIfPrivate(c, e), r.value;
  2170. };else {
  2171. var h = 0 === a || 1 === a;
  2172. (h || 3 === a) && (l = s ? function (e) {
  2173. return assertInstanceIfPrivate(c, e), r.get.call(e);
  2174. } : function (e) {
  2175. return r.get.call(e);
  2176. }), (h || 4 === a) && (f = s ? function (e, t) {
  2177. assertInstanceIfPrivate(c, e), r.set.call(e, t);
  2178. } : function (e, t) {
  2179. r.set.call(e, t);
  2180. });
  2181. }
  2182. } else l = function (e) {
  2183. return e[t];
  2184. }, 0 === a && (f = function (e, r) {
  2185. e[t] = r;
  2186. });
  2187. var v = s ? c.bind() : function (e) {
  2188. return t in e;
  2189. };
  2190. p.access = l && f ? {
  2191. get: l,
  2192. set: f,
  2193. has: v
  2194. } : l ? {
  2195. get: l,
  2196. has: v
  2197. } : {
  2198. set: f,
  2199. has: v
  2200. };
  2201. try {
  2202. return e(o, p);
  2203. } finally {
  2204. d.v = !0;
  2205. }
  2206. }
  2207. function assertCallable(e, t) {
  2208. if ("function" != typeof e) throw new TypeError(t + " must be a function");
  2209. }
  2210. function assertValidReturnValue(e, t) {
  2211. var r = typeof t;
  2212. if (1 === e) {
  2213. if ("object" !== r || null === t) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
  2214. void 0 !== t.get && assertCallable(t.get, "accessor.get"), void 0 !== t.set && assertCallable(t.set, "accessor.set"), void 0 !== t.init && assertCallable(t.init, "accessor.init");
  2215. } else if ("function" !== r) throw new TypeError((0 === e ? "field" : 10 === e ? "class" : "method") + " decorators must return a function or void 0");
  2216. }
  2217. function curryThis2(e) {
  2218. return function (t) {
  2219. e(this, t);
  2220. };
  2221. }
  2222. function applyMemberDec(e, t, r, n, a, i, s, o, c) {
  2223. var u,
  2224. l,
  2225. f,
  2226. p,
  2227. d,
  2228. h,
  2229. v,
  2230. y,
  2231. g = r[0];
  2232. if (s ? (0 === a || 1 === a ? (u = {
  2233. get: (d = r[3], function () {
  2234. return d(this);
  2235. }),
  2236. set: curryThis2(r[4])
  2237. }, f = "get") : 3 === a ? (u = {
  2238. get: r[3]
  2239. }, f = "get") : 4 === a ? (u = {
  2240. set: r[3]
  2241. }, f = "set") : u = {
  2242. value: r[3]
  2243. }, 0 !== a && (1 === a && _setFunctionName(u.set, "#" + n, "set"), _setFunctionName(u[f || "value"], "#" + n, f))) : 0 !== a && (u = Object.getOwnPropertyDescriptor(t, n)), 1 === a ? p = {
  2244. get: u.get,
  2245. set: u.set
  2246. } : 2 === a ? p = u.value : 3 === a ? p = u.get : 4 === a && (p = u.set), "function" == typeof g) void 0 !== (h = memberDec(g, n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? l = h : 1 === a ? (l = h.init, v = h.get || p.get, y = h.set || p.set, p = {
  2247. get: v,
  2248. set: y
  2249. }) : p = h);else for (var m = g.length - 1; m >= 0; m--) {
  2250. var b;
  2251. void 0 !== (h = memberDec(g[m], n, u, o, a, i, s, p, c)) && (assertValidReturnValue(a, h), 0 === a ? b = h : 1 === a ? (b = h.init, v = h.get || p.get, y = h.set || p.set, p = {
  2252. get: v,
  2253. set: y
  2254. }) : p = h, void 0 !== b && (void 0 === l ? l = b : "function" == typeof l ? l = [l, b] : l.push(b)));
  2255. }
  2256. if (0 === a || 1 === a) {
  2257. if (void 0 === l) l = function (e, t) {
  2258. return t;
  2259. };else if ("function" != typeof l) {
  2260. var I = l;
  2261. l = function (e, t) {
  2262. for (var r = t, n = 0; n < I.length; n++) r = I[n].call(e, r);
  2263. return r;
  2264. };
  2265. } else {
  2266. var w = l;
  2267. l = function (e, t) {
  2268. return w.call(e, t);
  2269. };
  2270. }
  2271. e.push(l);
  2272. }
  2273. 0 !== a && (1 === a ? (u.get = p.get, u.set = p.set) : 2 === a ? u.value = p : 3 === a ? u.get = p : 4 === a && (u.set = p), s ? 1 === a ? (e.push(function (e, t) {
  2274. return p.get.call(e, t);
  2275. }), e.push(function (e, t) {
  2276. return p.set.call(e, t);
  2277. })) : 2 === a ? e.push(p) : e.push(function (e, t) {
  2278. return p.call(e, t);
  2279. }) : Object.defineProperty(t, n, u));
  2280. }
  2281. function applyMemberDecs(e, t, r) {
  2282. for (var n, a, i, s = [], o = new Map(), c = new Map(), u = 0; u < t.length; u++) {
  2283. var l = t[u];
  2284. if (Array.isArray(l)) {
  2285. var f,
  2286. p,
  2287. d = l[1],
  2288. h = l[2],
  2289. v = l.length > 3,
  2290. y = d >= 5,
  2291. g = r;
  2292. if (y ? (f = e, 0 != (d -= 5) && (p = a = a || []), v && !i && (i = function (t) {
  2293. return _checkInRHS(t) === e;
  2294. }), g = i) : (f = e.prototype, 0 !== d && (p = n = n || [])), 0 !== d && !v) {
  2295. var m = y ? c : o,
  2296. b = m.get(h) || 0;
  2297. if (!0 === b || 3 === b && 4 !== d || 4 === b && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h);
  2298. !b && d > 2 ? m.set(h, d) : m.set(h, !0);
  2299. }
  2300. applyMemberDec(s, f, l, h, d, y, v, p, g);
  2301. }
  2302. }
  2303. return pushInitializers(s, n), pushInitializers(s, a), s;
  2304. }
  2305. function pushInitializers(e, t) {
  2306. t && e.push(function (e) {
  2307. for (var r = 0; r < t.length; r++) t[r].call(e);
  2308. return e;
  2309. });
  2310. }
  2311. return function (e, t, r, n) {
  2312. return {
  2313. e: applyMemberDecs(e, t, n),
  2314. get c() {
  2315. return function (e, t) {
  2316. if (t.length > 0) {
  2317. for (var r = [], n = e, a = e.name, i = t.length - 1; i >= 0; i--) {
  2318. var s = {
  2319. v: !1
  2320. };
  2321. try {
  2322. var o = t[i](n, {
  2323. kind: "class",
  2324. name: a,
  2325. addInitializer: createAddInitializerMethod(r, s)
  2326. });
  2327. } finally {
  2328. s.v = !0;
  2329. }
  2330. void 0 !== o && (assertValidReturnValue(10, o), n = o);
  2331. }
  2332. return [n, function () {
  2333. for (var e = 0; e < r.length; e++) r[e].call(n);
  2334. }];
  2335. }
  2336. }(e, r);
  2337. }
  2338. };
  2339. };
  2340. }
  2341. function _applyDecs2301(e, t, r, n) {
  2342. return (_applyDecs2301 = applyDecs2301Factory())(e, t, r, n);
  2343. }
  2344. function _applyDecs2305(e, t, r, n, o, a) {
  2345. function i(e, t, r) {
  2346. return function (n, o) {
  2347. return r && r(n), e[t].call(n, o);
  2348. };
  2349. }
  2350. function c(e, t) {
  2351. for (var r = 0; r < e.length; r++) e[r].call(t);
  2352. return t;
  2353. }
  2354. function s(e, t, r, n) {
  2355. if ("function" != typeof e && (n || void 0 !== e)) throw new TypeError(t + " must " + (r || "be") + " a function" + (n ? "" : " or undefined"));
  2356. return e;
  2357. }
  2358. function applyDec(e, t, r, n, o, a, c, u, l, f, p, d, h) {
  2359. function m(e) {
  2360. if (!h(e)) throw new TypeError("Attempted to access private element on non-instance");
  2361. }
  2362. var y,
  2363. v = t[0],
  2364. g = t[3],
  2365. b = !u;
  2366. if (!b) {
  2367. r || Array.isArray(v) || (v = [v]);
  2368. var w = {},
  2369. S = [],
  2370. A = 3 === o ? "get" : 4 === o || d ? "set" : "value";
  2371. f ? (p || d ? w = {
  2372. get: _setFunctionName(function () {
  2373. return g(this);
  2374. }, n, "get"),
  2375. set: function (e) {
  2376. t[4](this, e);
  2377. }
  2378. } : w[A] = g, p || _setFunctionName(w[A], n, 2 === o ? "" : A)) : p || (w = Object.getOwnPropertyDescriptor(e, n));
  2379. }
  2380. for (var P = e, j = v.length - 1; j >= 0; j -= r ? 2 : 1) {
  2381. var D = v[j],
  2382. E = r ? v[j - 1] : void 0,
  2383. I = {},
  2384. O = {
  2385. kind: ["field", "accessor", "method", "getter", "setter", "class"][o],
  2386. name: n,
  2387. metadata: a,
  2388. addInitializer: function (e, t) {
  2389. if (e.v) throw Error("attempted to call addInitializer after decoration was finished");
  2390. s(t, "An initializer", "be", !0), c.push(t);
  2391. }.bind(null, I)
  2392. };
  2393. try {
  2394. if (b) (y = s(D.call(E, P, O), "class decorators", "return")) && (P = y);else {
  2395. var k, F;
  2396. O.static = l, O.private = f, f ? 2 === o ? k = function (e) {
  2397. return m(e), w.value;
  2398. } : (o < 4 && (k = i(w, "get", m)), 3 !== o && (F = i(w, "set", m))) : (k = function (e) {
  2399. return e[n];
  2400. }, (o < 2 || 4 === o) && (F = function (e, t) {
  2401. e[n] = t;
  2402. }));
  2403. var N = O.access = {
  2404. has: f ? h.bind() : function (e) {
  2405. return n in e;
  2406. }
  2407. };
  2408. if (k && (N.get = k), F && (N.set = F), P = D.call(E, d ? {
  2409. get: w.get,
  2410. set: w.set
  2411. } : w[A], O), d) {
  2412. if ("object" == typeof P && P) (y = s(P.get, "accessor.get")) && (w.get = y), (y = s(P.set, "accessor.set")) && (w.set = y), (y = s(P.init, "accessor.init")) && S.push(y);else if (void 0 !== P) throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
  2413. } else s(P, (p ? "field" : "method") + " decorators", "return") && (p ? S.push(P) : w[A] = P);
  2414. }
  2415. } finally {
  2416. I.v = !0;
  2417. }
  2418. }
  2419. return (p || d) && u.push(function (e, t) {
  2420. for (var r = S.length - 1; r >= 0; r--) t = S[r].call(e, t);
  2421. return t;
  2422. }), p || b || (f ? d ? u.push(i(w, "get"), i(w, "set")) : u.push(2 === o ? w[A] : i.call.bind(w[A])) : Object.defineProperty(e, n, w)), P;
  2423. }
  2424. function u(e, t) {
  2425. return Object.defineProperty(e, Symbol.metadata || Symbol.for("Symbol.metadata"), {
  2426. configurable: !0,
  2427. enumerable: !0,
  2428. value: t
  2429. });
  2430. }
  2431. if (arguments.length >= 6) var l = a[Symbol.metadata || Symbol.for("Symbol.metadata")];
  2432. var f = Object.create(null == l ? null : l),
  2433. p = function (e, t, r, n) {
  2434. var o,
  2435. a,
  2436. i = [],
  2437. s = function (t) {
  2438. return _checkInRHS(t) === e;
  2439. },
  2440. u = new Map();
  2441. function l(e) {
  2442. e && i.push(c.bind(null, e));
  2443. }
  2444. for (var f = 0; f < t.length; f++) {
  2445. var p = t[f];
  2446. if (Array.isArray(p)) {
  2447. var d = p[1],
  2448. h = p[2],
  2449. m = p.length > 3,
  2450. y = 16 & d,
  2451. v = !!(8 & d),
  2452. g = 0 == (d &= 7),
  2453. b = h + "/" + v;
  2454. if (!g && !m) {
  2455. var w = u.get(b);
  2456. if (!0 === w || 3 === w && 4 !== d || 4 === w && 3 !== d) throw Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + h);
  2457. u.set(b, !(d > 2) || d);
  2458. }
  2459. applyDec(v ? e : e.prototype, p, y, m ? "#" + h : _toPropertyKey(h), d, n, v ? a = a || [] : o = o || [], i, v, m, g, 1 === d, v && m ? s : r);
  2460. }
  2461. }
  2462. return l(o), l(a), i;
  2463. }(e, t, o, f);
  2464. return r.length || u(e, f), {
  2465. e: p,
  2466. get c() {
  2467. var t = [];
  2468. return r.length && [u(applyDec(e, [r], n, e.name, 5, f, t), f), c.bind(null, t, e)];
  2469. }
  2470. };
  2471. }
  2472. function _classApplyDescriptorDestructureSet(e, t) {
  2473. if (t.set) return "__destrObj" in t || (t.__destrObj = {
  2474. set value(r) {
  2475. t.set.call(e, r);
  2476. }
  2477. }), t.__destrObj;
  2478. if (!t.writable) throw new TypeError("attempted to set read only private field");
  2479. return t;
  2480. }
  2481. function _classApplyDescriptorGet(e, t) {
  2482. return t.get ? t.get.call(e) : t.value;
  2483. }
  2484. function _classApplyDescriptorSet(e, t, l) {
  2485. if (t.set) t.set.call(e, l);else {
  2486. if (!t.writable) throw new TypeError("attempted to set read only private field");
  2487. t.value = l;
  2488. }
  2489. }
  2490. function _classCheckPrivateStaticAccess(s, a, r) {
  2491. return _assertClassBrand(a, s, r);
  2492. }
  2493. function _classCheckPrivateStaticFieldDescriptor(t, e) {
  2494. if (void 0 === t) throw new TypeError("attempted to " + e + " private static field before its declaration");
  2495. }
  2496. function _classExtractFieldDescriptor(e, t) {
  2497. return _classPrivateFieldGet2(t, e);
  2498. }
  2499. function _classPrivateFieldDestructureSet(e, t) {
  2500. var r = _classPrivateFieldGet2(t, e);
  2501. return _classApplyDescriptorDestructureSet(e, r);
  2502. }
  2503. function _classPrivateFieldGet(e, t) {
  2504. var r = _classPrivateFieldGet2(t, e);
  2505. return _classApplyDescriptorGet(e, r);
  2506. }
  2507. function _classPrivateFieldSet(e, t, r) {
  2508. var s = _classPrivateFieldGet2(t, e);
  2509. return _classApplyDescriptorSet(e, s, r), r;
  2510. }
  2511. function _classPrivateMethodGet(s, a, r) {
  2512. return _assertClassBrand(a, s), r;
  2513. }
  2514. function _classPrivateMethodSet() {
  2515. throw new TypeError("attempted to reassign private method");
  2516. }
  2517. function _classStaticPrivateFieldDestructureSet(t, r, s) {
  2518. return _assertClassBrand(r, t), _classCheckPrivateStaticFieldDescriptor(s, "set"), _classApplyDescriptorDestructureSet(t, s);
  2519. }
  2520. function _classStaticPrivateFieldSpecGet(t, s, r) {
  2521. return _assertClassBrand(s, t), _classCheckPrivateStaticFieldDescriptor(r, "get"), _classApplyDescriptorGet(t, r);
  2522. }
  2523. function _classStaticPrivateFieldSpecSet(s, t, r, e) {
  2524. return _assertClassBrand(t, s), _classCheckPrivateStaticFieldDescriptor(r, "set"), _classApplyDescriptorSet(s, r, e), e;
  2525. }
  2526. function _classStaticPrivateMethodSet() {
  2527. throw new TypeError("attempted to set read only static private field");
  2528. }
  2529. function _defineEnumerableProperties(e, r) {
  2530. for (var t in r) {
  2531. var n = r[t];
  2532. n.configurable = n.enumerable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, t, n);
  2533. }
  2534. if (Object.getOwnPropertySymbols) for (var a = Object.getOwnPropertySymbols(r), b = 0; b < a.length; b++) {
  2535. var i = a[b];
  2536. (n = r[i]).configurable = n.enumerable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, i, n);
  2537. }
  2538. return e;
  2539. }
  2540. function dispose_SuppressedError(r, e) {
  2541. return "undefined" != typeof SuppressedError ? dispose_SuppressedError = SuppressedError : (dispose_SuppressedError = function (r, e) {
  2542. this.suppressed = e, this.error = r, this.stack = Error().stack;
  2543. }, dispose_SuppressedError.prototype = Object.create(Error.prototype, {
  2544. constructor: {
  2545. value: dispose_SuppressedError,
  2546. writable: !0,
  2547. configurable: !0
  2548. }
  2549. })), new dispose_SuppressedError(r, e);
  2550. }
  2551. function _dispose(r, e, s) {
  2552. function next() {
  2553. for (; r.length > 0;) try {
  2554. var o = r.pop(),
  2555. p = o.d.call(o.v);
  2556. if (o.a) return Promise.resolve(p).then(next, err);
  2557. } catch (r) {
  2558. return err(r);
  2559. }
  2560. if (s) throw e;
  2561. }
  2562. function err(r) {
  2563. return e = s ? new dispose_SuppressedError(e, r) : r, s = !0, next();
  2564. }
  2565. return next();
  2566. }
  2567. function _objectSpread(e) {
  2568. for (var r = 1; r < arguments.length; r++) {
  2569. var t = null != arguments[r] ? Object(arguments[r]) : {},
  2570. o = Object.keys(t);
  2571. "function" == typeof Object.getOwnPropertySymbols && o.push.apply(o, Object.getOwnPropertySymbols(t).filter(function (e) {
  2572. return Object.getOwnPropertyDescriptor(t, e).enumerable;
  2573. })), o.forEach(function (r) {
  2574. _defineProperty(e, r, t[r]);
  2575. });
  2576. }
  2577. return e;
  2578. }
  2579. function _using(o, n, e) {
  2580. if (null == n) return n;
  2581. if (Object(n) !== n) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
  2582. if (e) var r = n[Symbol.asyncDispose || Symbol.for("Symbol.asyncDispose")];
  2583. if (null == r && (r = n[Symbol.dispose || Symbol.for("Symbol.dispose")]), "function" != typeof r) throw new TypeError("Property [Symbol.dispose] is not a function.");
  2584. return o.push({
  2585. v: n,
  2586. d: r,
  2587. a: e
  2588. }), n;
  2589. }
  2590. // threejs.org/license
  2591. var REVISION='124';var MOUSE={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2};var TOUCH={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3};var CullFaceNone=0;var CullFaceBack=1;var CullFaceFront=2;var CullFaceFrontBack=3;var BasicShadowMap=0;var PCFShadowMap=1;var PCFSoftShadowMap=2;var VSMShadowMap=3;var FrontSide=0;var BackSide=1;var DoubleSide=2;var FlatShading$1=1;var SmoothShading=2;var NoBlending=0;var NormalBlending=1;var AdditiveBlending=2;var SubtractiveBlending=3;var MultiplyBlending=4;var CustomBlending=5;var AddEquation=100;var SubtractEquation=101;var ReverseSubtractEquation=102;var MinEquation=103;var MaxEquation=104;var ZeroFactor=200;var OneFactor=201;var SrcColorFactor=202;var OneMinusSrcColorFactor=203;var SrcAlphaFactor=204;var OneMinusSrcAlphaFactor=205;var DstAlphaFactor=206;var OneMinusDstAlphaFactor=207;var DstColorFactor=208;var OneMinusDstColorFactor=209;var SrcAlphaSaturateFactor=210;var NeverDepth=0;var AlwaysDepth=1;var LessDepth=2;var LessEqualDepth=3;var EqualDepth=4;var GreaterEqualDepth=5;var GreaterDepth=6;var NotEqualDepth=7;var MultiplyOperation=0;var MixOperation=1;var AddOperation=2;var NoToneMapping=0;var LinearToneMapping=1;var ReinhardToneMapping=2;var CineonToneMapping=3;var ACESFilmicToneMapping=4;var CustomToneMapping=5;var UVMapping=300;var CubeReflectionMapping=301;var CubeRefractionMapping=302;var EquirectangularReflectionMapping=303;var EquirectangularRefractionMapping=304;var CubeUVReflectionMapping=306;var CubeUVRefractionMapping=307;var RepeatWrapping=1000;var ClampToEdgeWrapping=1001;var MirroredRepeatWrapping=1002;var NearestFilter=1003;var NearestMipmapNearestFilter=1004;var NearestMipMapNearestFilter=1004;var NearestMipmapLinearFilter=1005;var NearestMipMapLinearFilter=1005;var LinearFilter=1006;var LinearMipmapNearestFilter=1007;var LinearMipMapNearestFilter=1007;var LinearMipmapLinearFilter=1008;var LinearMipMapLinearFilter=1008;var UnsignedByteType=1009;var ByteType=1010;var ShortType=1011;var UnsignedShortType=1012;var IntType=1013;var UnsignedIntType=1014;var FloatType=1015;var HalfFloatType=1016;var UnsignedShort4444Type=1017;var UnsignedShort5551Type=1018;var UnsignedShort565Type=1019;var UnsignedInt248Type$1=1020;var AlphaFormat=1021;var RGBFormat=1022;var RGBAFormat=1023;var LuminanceFormat=1024;var LuminanceAlphaFormat=1025;var RGBEFormat=RGBAFormat;var DepthFormat=1026;var DepthStencilFormat=1027;var RedFormat=1028;var RedIntegerFormat=1029;var RGFormat=1030;var RGIntegerFormat=1031;var RGBIntegerFormat=1032;var RGBAIntegerFormat=1033;var RGB_S3TC_DXT1_Format=33776;var RGBA_S3TC_DXT1_Format$1=33777;var RGBA_S3TC_DXT3_Format=33778;var RGBA_S3TC_DXT5_Format$1=33779;var RGB_PVRTC_4BPPV1_Format=35840;var RGB_PVRTC_2BPPV1_Format=35841;var RGBA_PVRTC_4BPPV1_Format=35842;var RGBA_PVRTC_2BPPV1_Format=35843;var RGB_ETC1_Format=36196;var RGB_ETC2_Format=37492;var RGBA_ETC2_EAC_Format=37496;var RGBA_ASTC_4x4_Format=37808;var RGBA_ASTC_5x4_Format=37809;var RGBA_ASTC_5x5_Format=37810;var RGBA_ASTC_6x5_Format=37811;var RGBA_ASTC_6x6_Format=37812;var RGBA_ASTC_8x5_Format=37813;var RGBA_ASTC_8x6_Format=37814;var RGBA_ASTC_8x8_Format=37815;var RGBA_ASTC_10x5_Format=37816;var RGBA_ASTC_10x6_Format=37817;var RGBA_ASTC_10x8_Format=37818;var RGBA_ASTC_10x10_Format=37819;var RGBA_ASTC_12x10_Format=37820;var RGBA_ASTC_12x12_Format=37821;var RGBA_BPTC_Format=36492;var SRGB8_ALPHA8_ASTC_4x4_Format=37840;var SRGB8_ALPHA8_ASTC_5x4_Format=37841;var SRGB8_ALPHA8_ASTC_5x5_Format=37842;var SRGB8_ALPHA8_ASTC_6x5_Format=37843;var SRGB8_ALPHA8_ASTC_6x6_Format=37844;var SRGB8_ALPHA8_ASTC_8x5_Format=37845;var SRGB8_ALPHA8_ASTC_8x6_Format=37846;var SRGB8_ALPHA8_ASTC_8x8_Format=37847;var SRGB8_ALPHA8_ASTC_10x5_Format=37848;var SRGB8_ALPHA8_ASTC_10x6_Format=37849;var SRGB8_ALPHA8_ASTC_10x8_Format=37850;var SRGB8_ALPHA8_ASTC_10x10_Format=37851;var SRGB8_ALPHA8_ASTC_12x10_Format=37852;var SRGB8_ALPHA8_ASTC_12x12_Format=37853;var LoopOnce=2200;var LoopRepeat=2201;var LoopPingPong=2202;var InterpolateDiscrete=2300;var InterpolateLinear=2301;var InterpolateSmooth=2302;var ZeroCurvatureEnding=2400;var ZeroSlopeEnding=2401;var WrapAroundEnding=2402;var NormalAnimationBlendMode=2500;var AdditiveAnimationBlendMode=2501;var TrianglesDrawMode=0;var TriangleStripDrawMode=1;var TriangleFanDrawMode=2;var LinearEncoding=3000;var sRGBEncoding=3001;var GammaEncoding=3007;var RGBEEncoding=3002;var LogLuvEncoding=3003;var RGBM7Encoding=3004;var RGBM16Encoding=3005;var RGBDEncoding=3006;var BasicDepthPacking=3200;var RGBADepthPacking=3201;var TangentSpaceNormalMap=0;var ObjectSpaceNormalMap=1;var ZeroStencilOp=0;var KeepStencilOp=7680;var ReplaceStencilOp=7681;var IncrementStencilOp=7682;var DecrementStencilOp=7683;var IncrementWrapStencilOp=34055;var DecrementWrapStencilOp=34056;var InvertStencilOp=5386;var NeverStencilFunc=512;var LessStencilFunc=513;var EqualStencilFunc=514;var LessEqualStencilFunc=515;var GreaterStencilFunc=516;var NotEqualStencilFunc=517;var GreaterEqualStencilFunc=518;var AlwaysStencilFunc=519;var StaticDrawUsage=35044;var DynamicDrawUsage=35048;var StreamDrawUsage=35040;var StaticReadUsage=35045;var DynamicReadUsage=35049;var StreamReadUsage=35041;var StaticCopyUsage=35046;var DynamicCopyUsage=35050;var StreamCopyUsage=35042;var GLSL1='100';var GLSL3='300 es';/**
  2592. * https://github.com/mrdoob/eventdispatcher.js/
  2593. */function EventDispatcher(){}Object.assign(EventDispatcher.prototype,{addEventListener:function addEventListener(type,listener){if(this._listeners===undefined)this._listeners={};var listeners=this._listeners;if(listeners[type]===undefined){listeners[type]=[];}if(listeners[type].indexOf(listener)===-1){listeners[type].push(listener);}},hasEventListener:function hasEventListener(type,listener){if(this._listeners===undefined)return false;var listeners=this._listeners;return listeners[type]!==undefined&&listeners[type].indexOf(listener)!==-1;},dispatchEvent:function dispatchEvent(event){if(this._listeners===undefined)return;var listeners=this._listeners;var listenerArray=listeners[event.type];if(listenerArray!==undefined){event.target=this;// Make a copy, in case listeners are removed while iterating.
  2594. var array=listenerArray.slice(0);for(var i=0,l=array.length;i<l;i++){array[i].call(this,event);}}}});var _lut=[];for(var i=0;i<256;i++){_lut[i]=(i<16?'0':'')+i.toString(16);}var _seed=1234567;var MathUtils={DEG2RAD:Math.PI/180,RAD2DEG:180/Math.PI,generateUUID:function generateUUID(){// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  2595. var d0=Math.random()*0xffffffff|0;var d1=Math.random()*0xffffffff|0;var d2=Math.random()*0xffffffff|0;var d3=Math.random()*0xffffffff|0;var uuid=_lut[d0&0xff]+_lut[d0>>8&0xff]+_lut[d0>>16&0xff]+_lut[d0>>24&0xff]+'-'+_lut[d1&0xff]+_lut[d1>>8&0xff]+'-'+_lut[d1>>16&0x0f|0x40]+_lut[d1>>24&0xff]+'-'+_lut[d2&0x3f|0x80]+_lut[d2>>8&0xff]+'-'+_lut[d2>>16&0xff]+_lut[d2>>24&0xff]+_lut[d3&0xff]+_lut[d3>>8&0xff]+_lut[d3>>16&0xff]+_lut[d3>>24&0xff];// .toUpperCase() here flattens concatenated strings to save heap memory space.
  2596. return uuid.toUpperCase();},clamp:function clamp(value,min,max){return Math.max(min,Math.min(max,value));},// compute euclidian modulo of m % n
  2597. // https://en.wikipedia.org/wiki/Modulo_operation
  2598. euclideanModulo:function euclideanModulo(n,m){return (n%m+m)%m;},// Linear mapping from range <a1, a2> to range <b1, b2>
  2599. mapLinear:function mapLinear(x,a1,a2,b1,b2){return b1+(x-a1)*(b2-b1)/(a2-a1);},// https://en.wikipedia.org/wiki/Linear_interpolation
  2600. lerp:function lerp(x,y,t){return (1-t)*x+t*y;},// http://en.wikipedia.org/wiki/Smoothstep
  2601. smoothstep:function smoothstep(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*(3-2*x);},smootherstep:function smootherstep(x,min,max){if(x<=min)return 0;if(x>=max)return 1;x=(x-min)/(max-min);return x*x*x*(x*(x*6-15)+10);},// Random integer from <low, high> interval
  2602. randInt:function randInt(low,high){return low+Math.floor(Math.random()*(high-low+1));},// Random float from <low, high> interval
  2603. randFloat:function randFloat(low,high){return low+Math.random()*(high-low);},// Random float from <-range/2, range/2> interval
  2604. randFloatSpread:function randFloatSpread(range){return range*(0.5-Math.random());},// Deterministic pseudo-random float in the interval [ 0, 1 ]
  2605. seededRandom:function seededRandom(s){if(s!==undefined)_seed=s%2147483647;// Park-Miller algorithm
  2606. _seed=_seed*16807%2147483647;return (_seed-1)/2147483646;},degToRad:function degToRad(degrees){return degrees*MathUtils.DEG2RAD;},radToDeg:function radToDeg(radians){return radians*MathUtils.RAD2DEG;},isPowerOfTwo:function isPowerOfTwo(value){return (value&value-1)===0&&value!==0;},ceilPowerOfTwo:function ceilPowerOfTwo(value){return Math.pow(2,Math.ceil(Math.log(value)/Math.LN2));},floorPowerOfTwo:function floorPowerOfTwo(value){return Math.pow(2,Math.floor(Math.log(value)/Math.LN2));},setQuaternionFromProperEuler:function setQuaternionFromProperEuler(q,a,b,c,order){// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  2607. // rotations are applied to the axes in the order specified by 'order'
  2608. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  2609. // angles are in radians
  2610. var cos=Math.cos;var sin=Math.sin;var c2=cos(b/2);var s2=sin(b/2);var c13=cos((a+c)/2);var s13=sin((a+c)/2);var c1_3=cos((a-c)/2);var s1_3=sin((a-c)/2);var c3_1=cos((c-a)/2);var s3_1=sin((c-a)/2);switch(order){case'XYX':q.set(c2*s13,s2*c1_3,s2*s1_3,c2*c13);break;case'YZY':q.set(s2*s1_3,c2*s13,s2*c1_3,c2*c13);break;case'ZXZ':q.set(s2*c1_3,s2*s1_3,c2*s13,c2*c13);break;case'XZX':q.set(c2*s13,s2*s3_1,s2*c3_1,c2*c13);break;case'YXY':q.set(s2*c3_1,c2*s13,s2*s3_1,c2*c13);break;case'ZYZ':q.set(s2*s3_1,s2*c3_1,c2*s13,c2*c13);break;default:console.warn('THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: '+order);}}};class Vector2{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;Object.defineProperty(this,'isVector2',{value:true});this.x=x;this.y=y;}get width(){return this.x;}set width(value){this.x=value;}get height(){return this.y;}set height(value){this.y=value;}set(x,y){this.x=x;this.y=y;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;default:throw new Error('index is out of range: '+index);}return this;}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;default:throw new Error('index is out of range: '+index);}}clone(){return new this.constructor(this.x,this.y);}copy(v){this.x=v.x;this.y=v.y;return this;}add(v,w){if(w!==undefined){console.warn('THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;return this;}addScalar(s){this.x+=s;this.y+=s;return this;}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;return this;}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;return this;}sub(v,w){if(w!==undefined){console.warn('THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;return this;}subScalar(s){this.x-=s;this.y-=s;return this;}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;return this;}multiply(v){this.x*=v.x;this.y*=v.y;return this;}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;return this;}divide(v){this.x/=v.x;this.y/=v.y;return this;}divideScalar(scalar){return this.multiplyScalar(1/scalar);}applyMatrix3(m){var x=this.x,y=this.y;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6];this.y=e[1]*x+e[4]*y+e[7];return this;}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);return this;}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);return this;}clamp(min,max){// assumes min < max, componentwise
  2611. this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));return this;}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));return this;}clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this;}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this;}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);return this;}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);return this;}negate(){this.x=-this.x;this.y=-this.y;return this;}dot(v){return this.x*v.x+this.y*v.y;}cross(v){return this.x*v.y-this.y*v.x;}lengthSq(){return this.x*this.x+this.y*this.y;}length(){return Math.sqrt(this.x*this.x+this.y*this.y);}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y);}normalize(){return this.divideScalar(this.length()||1);}angle(){// computes the angle in radians with respect to the positive x-axis
  2612. var angle=Math.atan2(-this.y,-this.x)+Math.PI;return angle;}distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y;return dx*dx+dy*dy;}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y);}setLength(length){return this.normalize().multiplyScalar(length);}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;return this;}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;return this;}equals(v){return v.x===this.x&&v.y===this.y;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;return array;}fromBufferAttribute(attribute,index,offset){if(offset!==undefined){console.warn('THREE.Vector2: offset has been removed from .fromBufferAttribute().');}this.x=attribute.getX(index);this.y=attribute.getY(index);return this;}rotateAround(center,angle){var c=Math.cos(angle),s=Math.sin(angle);var x=this.x-center.x;var y=this.y-center.y;this.x=x*c-y*s+center.x;this.y=x*s+y*c+center.y;return this;}random(){this.x=Math.random();this.y=Math.random();return this;}}class Matrix3{constructor(){Object.defineProperty(this,'isMatrix3',{value:true});this.elements=[1,0,0,0,1,0,0,0,1];if(arguments.length>0){console.error('THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.');}}set(n11,n12,n13,n21,n22,n23,n31,n32,n33){var te=this.elements;te[0]=n11;te[1]=n21;te[2]=n31;te[3]=n12;te[4]=n22;te[5]=n32;te[6]=n13;te[7]=n23;te[8]=n33;return this;}identity(){this.set(1,0,0,0,1,0,0,0,1);return this;}clone(){return new this.constructor().fromArray(this.elements);}copy(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];return this;}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrix3Column(this,0);yAxis.setFromMatrix3Column(this,1);zAxis.setFromMatrix3Column(this,2);return this;}setFromMatrix4(m){var me=m.elements;this.set(me[0],me[4],me[8],me[1],me[5],me[9],me[2],me[6],me[10]);return this;}multiply(m){return this.multiplyMatrices(this,m);}premultiply(m){return this.multiplyMatrices(m,this);}multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[3],a13=ae[6];var a21=ae[1],a22=ae[4],a23=ae[7];var a31=ae[2],a32=ae[5],a33=ae[8];var b11=be[0],b12=be[3],b13=be[6];var b21=be[1],b22=be[4],b23=be[7];var b31=be[2],b32=be[5],b33=be[8];te[0]=a11*b11+a12*b21+a13*b31;te[3]=a11*b12+a12*b22+a13*b32;te[6]=a11*b13+a12*b23+a13*b33;te[1]=a21*b11+a22*b21+a23*b31;te[4]=a21*b12+a22*b22+a23*b32;te[7]=a21*b13+a22*b23+a23*b33;te[2]=a31*b11+a32*b21+a33*b31;te[5]=a31*b12+a32*b22+a33*b32;te[8]=a31*b13+a32*b23+a33*b33;return this;}multiplyScalar(s){var te=this.elements;te[0]*=s;te[3]*=s;te[6]*=s;te[1]*=s;te[4]*=s;te[7]*=s;te[2]*=s;te[5]*=s;te[8]*=s;return this;}determinant(){var te=this.elements;var a=te[0],b=te[1],c=te[2],d=te[3],e=te[4],f=te[5],g=te[6],h=te[7],i=te[8];return a*e*i-a*f*h-b*d*i+b*f*g+c*d*h-c*e*g;}invert(){var te=this.elements,n11=te[0],n21=te[1],n31=te[2],n12=te[3],n22=te[4],n32=te[5],n13=te[6],n23=te[7],n33=te[8],t11=n33*n22-n32*n23,t12=n32*n13-n33*n12,t13=n23*n12-n22*n13,det=n11*t11+n21*t12+n31*t13;if(det===0)return this.set(0,0,0,0,0,0,0,0,0);var detInv=1/det;te[0]=t11*detInv;te[1]=(n31*n23-n33*n21)*detInv;te[2]=(n32*n21-n31*n22)*detInv;te[3]=t12*detInv;te[4]=(n33*n11-n31*n13)*detInv;te[5]=(n31*n12-n32*n11)*detInv;te[6]=t13*detInv;te[7]=(n21*n13-n23*n11)*detInv;te[8]=(n22*n11-n21*n12)*detInv;return this;}transpose(){var tmp;var m=this.elements;tmp=m[1];m[1]=m[3];m[3]=tmp;tmp=m[2];m[2]=m[6];m[6]=tmp;tmp=m[5];m[5]=m[7];m[7]=tmp;return this;}getNormalMatrix(matrix4){return this.setFromMatrix4(matrix4).copy(this).invert().transpose();}transposeIntoArray(r){var m=this.elements;r[0]=m[0];r[1]=m[3];r[2]=m[6];r[3]=m[1];r[4]=m[4];r[5]=m[7];r[6]=m[2];r[7]=m[5];r[8]=m[8];return this;}setUvTransform(tx,ty,sx,sy,rotation,cx,cy){var c=Math.cos(rotation);var s=Math.sin(rotation);this.set(sx*c,sx*s,-sx*(c*cx+s*cy)+cx+tx,-sy*s,sy*c,-sy*(-s*cx+c*cy)+cy+ty,0,0,1);return this;}scale(sx,sy){var te=this.elements;te[0]*=sx;te[3]*=sx;te[6]*=sx;te[1]*=sy;te[4]*=sy;te[7]*=sy;return this;}rotate(theta){var c=Math.cos(theta);var s=Math.sin(theta);var te=this.elements;var a11=te[0],a12=te[3],a13=te[6];var a21=te[1],a22=te[4],a23=te[7];te[0]=c*a11+s*a21;te[3]=c*a12+s*a22;te[6]=c*a13+s*a23;te[1]=-s*a11+c*a21;te[4]=-s*a12+c*a22;te[7]=-s*a13+c*a23;return this;}translate(tx,ty){var te=this.elements;te[0]+=tx*te[2];te[3]+=tx*te[5];te[6]+=tx*te[8];te[1]+=ty*te[2];te[4]+=ty*te[5];te[7]+=ty*te[8];return this;}equals(matrix){var te=this.elements;var me=matrix.elements;for(var _i=0;_i<9;_i++){if(te[_i]!==me[_i])return false;}return true;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i2=0;_i2<9;_i2++){this.elements[_i2]=array[_i2+offset];}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];return array;}}var _canvas;var ImageUtils={getDataURL:function getDataURL(image){if(/^data:/i.test(image.src)){return image.src;}if(typeof HTMLCanvasElement=='undefined'){return image.src;}var canvas;if(image instanceof HTMLCanvasElement){canvas=image;}else {if(_canvas===undefined)_canvas=document.createElementNS('http://www.w3.org/1999/xhtml','canvas');_canvas.width=image.width;_canvas.height=image.height;var context=_canvas.getContext('2d');if(image instanceof ImageData){context.putImageData(image,0,0);}else {context.drawImage(image,0,0,image.width,image.height);}canvas=_canvas;}if(canvas.width>2048||canvas.height>2048){return canvas.toDataURL('image/jpeg',0.6);}else {return canvas.toDataURL('image/png');}}};var textureId=0;function Texture(){var image=arguments.length>0&&arguments[0]!==undefined?arguments[0]:Texture.DEFAULT_IMAGE;var mapping=arguments.length>1&&arguments[1]!==undefined?arguments[1]:Texture.DEFAULT_MAPPING;var wrapS=arguments.length>2&&arguments[2]!==undefined?arguments[2]:ClampToEdgeWrapping;var wrapT=arguments.length>3&&arguments[3]!==undefined?arguments[3]:ClampToEdgeWrapping;var magFilter=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LinearFilter;var minFilter=arguments.length>5&&arguments[5]!==undefined?arguments[5]:LinearMipmapLinearFilter;var format=arguments.length>6&&arguments[6]!==undefined?arguments[6]:RGBAFormat;var type=arguments.length>7&&arguments[7]!==undefined?arguments[7]:UnsignedByteType;var anisotropy=arguments.length>8&&arguments[8]!==undefined?arguments[8]:1;var encoding=arguments.length>9&&arguments[9]!==undefined?arguments[9]:LinearEncoding;Object.defineProperty(this,'id',{value:textureId++});this.uuid=MathUtils.generateUUID();this.name='';this.image=image;this.mipmaps=[];this.mapping=mapping;this.wrapS=wrapS;this.wrapT=wrapT;this.magFilter=magFilter;this.minFilter=minFilter;this.anisotropy=anisotropy;this.format=format;this.internalFormat=null;this.type=type;this.offset=new Vector2(0,0);this.repeat=new Vector2(1,1);this.center=new Vector2(0,0);this.rotation=0;this.matrixAutoUpdate=true;this.matrix=new Matrix3();this.generateMipmaps=true;this.premultiplyAlpha=false;this.flipY=true;this.unpackAlignment=4;// valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  2613. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  2614. //
  2615. // Also changing the encoding after already used by a Material will not automatically make the Material
  2616. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  2617. this.encoding=encoding;this.version=0;this.onUpdate=null;}Texture.DEFAULT_IMAGE=undefined;Texture.DEFAULT_MAPPING=UVMapping;Texture.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Texture,isTexture:true,updateMatrix:function updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y);},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.name=source.name;this.image=source.image;this.mipmaps=source.mipmaps.slice(0);this.mapping=source.mapping;this.wrapS=source.wrapS;this.wrapT=source.wrapT;this.magFilter=source.magFilter;this.minFilter=source.minFilter;this.anisotropy=source.anisotropy;this.format=source.format;this.internalFormat=source.internalFormat;this.type=source.type;this.offset.copy(source.offset);this.repeat.copy(source.repeat);this.center.copy(source.center);this.rotation=source.rotation;this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrix.copy(source.matrix);this.generateMipmaps=source.generateMipmaps;this.premultiplyAlpha=source.premultiplyAlpha;this.flipY=source.flipY;this.unpackAlignment=source.unpackAlignment;this.encoding=source.encoding;return this;},toJSON:function toJSON(meta){var isRootObject=meta===undefined||typeof meta==='string';if(!isRootObject&&meta.textures[this.uuid]!==undefined){return meta.textures[this.uuid];}var output={metadata:{version:4.5,type:'Texture',generator:'Texture.toJSON'},uuid:this.uuid,name:this.name,mapping:this.mapping,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,type:this.type,encoding:this.encoding,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};if(this.image!==undefined){// TODO: Move to THREE.Image
  2618. var image=this.image;if(image.uuid===undefined){image.uuid=MathUtils.generateUUID();// UGH
  2619. }if(!isRootObject&&meta.images[image.uuid]===undefined){var url;if(Array.isArray(image)){// process array of images e.g. CubeTexture
  2620. url=[];for(var _i3=0,l=image.length;_i3<l;_i3++){// check cube texture with data textures
  2621. if(image[_i3].isDataTexture){url.push(serializeImage(image[_i3].image));}else {url.push(serializeImage(image[_i3]));}}}else {// process single image
  2622. url=serializeImage(image);}meta.images[image.uuid]={uuid:image.uuid,url:url};}output.image=image.uuid;}if(!isRootObject){meta.textures[this.uuid]=output;}return output;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});},transformUv:function transformUv(uv){if(this.mapping!==UVMapping)return uv;uv.applyMatrix3(this.matrix);if(uv.x<0||uv.x>1){switch(this.wrapS){case RepeatWrapping:uv.x=uv.x-Math.floor(uv.x);break;case ClampToEdgeWrapping:uv.x=uv.x<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.x)%2)===1){uv.x=Math.ceil(uv.x)-uv.x;}else {uv.x=uv.x-Math.floor(uv.x);}break;}}if(uv.y<0||uv.y>1){switch(this.wrapT){case RepeatWrapping:uv.y=uv.y-Math.floor(uv.y);break;case ClampToEdgeWrapping:uv.y=uv.y<0?0:1;break;case MirroredRepeatWrapping:if(Math.abs(Math.floor(uv.y)%2)===1){uv.y=Math.ceil(uv.y)-uv.y;}else {uv.y=uv.y-Math.floor(uv.y);}break;}}if(this.flipY){uv.y=1-uv.y;}return uv;}});Object.defineProperty(Texture.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});function serializeImage(image){if(typeof HTMLImageElement!=='undefined'&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=='undefined'&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=='undefined'&&image instanceof ImageBitmap){// default images
  2623. return ImageUtils.getDataURL(image);}else {if(image.data){// images of DataTexture
  2624. return {data:Array.prototype.slice.call(image.data),width:image.width,height:image.height,type:image.data.constructor.name};}else {console.warn('THREE.Texture: Unable to serialize Texture.');return {};}}}class Vector4{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Object.defineProperty(this,'isVector4',{value:true});this.x=x;this.y=y;this.z=z;this.w=w;}get width(){return this.z;}set width(value){this.z=value;}get height(){return this.w;}set height(value){this.w=value;}set(x,y,z,w){this.x=x;this.y=y;this.z=z;this.w=w;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;this.w=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setZ(z){this.z=z;return this;}setW(w){this.w=w;return this;}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;case 3:this.w=value;break;default:throw new Error('index is out of range: '+index);}return this;}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error('index is out of range: '+index);}}clone(){return new this.constructor(this.x,this.y,this.z,this.w);}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;this.w=v.w!==undefined?v.w:1;return this;}add(v,w){if(w!==undefined){console.warn('THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;this.z+=v.z;this.w+=v.w;return this;}addScalar(s){this.x+=s;this.y+=s;this.z+=s;this.w+=s;return this;}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;this.w=a.w+b.w;return this;}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;this.w+=v.w*s;return this;}sub(v,w){if(w!==undefined){console.warn('THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;this.z-=v.z;this.w-=v.w;return this;}subScalar(s){this.x-=s;this.y-=s;this.z-=s;this.w-=s;return this;}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;this.w=a.w-b.w;return this;}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;this.w*=scalar;return this;}applyMatrix4(m){var x=this.x,y=this.y,z=this.z,w=this.w;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z+e[12]*w;this.y=e[1]*x+e[5]*y+e[9]*z+e[13]*w;this.z=e[2]*x+e[6]*y+e[10]*z+e[14]*w;this.w=e[3]*x+e[7]*y+e[11]*z+e[15]*w;return this;}divideScalar(scalar){return this.multiplyScalar(1/scalar);}setAxisAngleFromQuaternion(q){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2625. // q is assumed to be normalized
  2626. this.w=2*Math.acos(q.w);var s=Math.sqrt(1-q.w*q.w);if(s<0.0001){this.x=1;this.y=0;this.z=0;}else {this.x=q.x/s;this.y=q.y/s;this.z=q.z/s;}return this;}setAxisAngleFromRotationMatrix(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2627. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2628. var angle,x,y,z;// variables for result
  2629. var epsilon=0.01,// margin to allow for rounding errors
  2630. epsilon2=0.1,// margin to distinguish between 0 and 180 degrees
  2631. te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10];if(Math.abs(m12-m21)<epsilon&&Math.abs(m13-m31)<epsilon&&Math.abs(m23-m32)<epsilon){// singularity found
  2632. // first check for identity matrix which must have +1 for all terms
  2633. // in leading diagonal and zero in other terms
  2634. if(Math.abs(m12+m21)<epsilon2&&Math.abs(m13+m31)<epsilon2&&Math.abs(m23+m32)<epsilon2&&Math.abs(m11+m22+m33-3)<epsilon2){// this singularity is identity matrix so angle = 0
  2635. this.set(1,0,0,0);return this;// zero angle, arbitrary axis
  2636. }// otherwise this singularity is angle = 180
  2637. angle=Math.PI;var xx=(m11+1)/2;var yy=(m22+1)/2;var zz=(m33+1)/2;var xy=(m12+m21)/4;var xz=(m13+m31)/4;var yz=(m23+m32)/4;if(xx>yy&&xx>zz){// m11 is the largest diagonal term
  2638. if(xx<epsilon){x=0;y=0.707106781;z=0.707106781;}else {x=Math.sqrt(xx);y=xy/x;z=xz/x;}}else if(yy>zz){// m22 is the largest diagonal term
  2639. if(yy<epsilon){x=0.707106781;y=0;z=0.707106781;}else {y=Math.sqrt(yy);x=xy/y;z=yz/y;}}else {// m33 is the largest diagonal term so base result on this
  2640. if(zz<epsilon){x=0.707106781;y=0.707106781;z=0;}else {z=Math.sqrt(zz);x=xz/z;y=yz/z;}}this.set(x,y,z,angle);return this;// return 180 deg rotation
  2641. }// as we have reached here there are no singularities so we can handle normally
  2642. var s=Math.sqrt((m32-m23)*(m32-m23)+(m13-m31)*(m13-m31)+(m21-m12)*(m21-m12));// used to normalize
  2643. if(Math.abs(s)<0.001)s=1;// prevent divide by zero, should not happen if matrix is orthogonal and should be
  2644. // caught by singularity test above, but I've left it in just in case
  2645. this.x=(m32-m23)/s;this.y=(m13-m31)/s;this.z=(m21-m12)/s;this.w=Math.acos((m11+m22+m33-1)/2);return this;}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);this.w=Math.min(this.w,v.w);return this;}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);this.w=Math.max(this.w,v.w);return this;}clamp(min,max){// assumes min < max, componentwise
  2646. this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));this.w=Math.max(min.w,Math.min(max.w,this.w));return this;}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));this.w=Math.max(minVal,Math.min(maxVal,this.w));return this;}clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);this.w=Math.floor(this.w);return this;}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);this.w=Math.ceil(this.w);return this;}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);this.w=Math.round(this.w);return this;}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);this.w=this.w<0?Math.ceil(this.w):Math.floor(this.w);return this;}negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;this.w=-this.w;return this;}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z+this.w*v.w;}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w;}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w);}normalize(){return this.divideScalar(this.length()||1);}setLength(length){return this.normalize().multiplyScalar(length);}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;this.w+=(v.w-this.w)*alpha;return this;}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;this.w=v1.w+(v2.w-v1.w)*alpha;return this;}equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z&&v.w===this.w;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];this.w=array[offset+3];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;array[offset+3]=this.w;return array;}fromBufferAttribute(attribute,index,offset){if(offset!==undefined){console.warn('THREE.Vector4: offset has been removed from .fromBufferAttribute().');}this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);this.w=attribute.getW(index);return this;}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();this.w=Math.random();return this;}}/*
  2647. In options, we can specify:
  2648. * Texture parameters for an auto-generated target texture
  2649. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2650. */function WebGLRenderTarget(width,height,options){this.width=width;this.height=height;this.scissor=new Vector4(0,0,width,height);this.scissorTest=false;this.viewport=new Vector4(0,0,width,height);options=options||{};this.texture=new Texture(undefined,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture.image={};this.texture.image.width=width;this.texture.image.height=height;this.texture.generateMipmaps=options.generateMipmaps!==undefined?options.generateMipmaps:false;this.texture.minFilter=options.minFilter!==undefined?options.minFilter:LinearFilter;this.depthBuffer=options.depthBuffer!==undefined?options.depthBuffer:true;this.stencilBuffer=options.stencilBuffer!==undefined?options.stencilBuffer:false;this.depthTexture=options.depthTexture!==undefined?options.depthTexture:null;}WebGLRenderTarget.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:WebGLRenderTarget,isWebGLRenderTarget:true,setSize:function setSize(width,height){if(this.width!==width||this.height!==height){this.width=width;this.height=height;this.texture.image.width=width;this.texture.image.height=height;this.dispose();}this.viewport.set(0,0,width,height);this.scissor.set(0,0,width,height);},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.width=source.width;this.height=source.height;this.viewport.copy(source.viewport);this.texture=source.texture.clone();this.depthBuffer=source.depthBuffer;this.stencilBuffer=source.stencilBuffer;this.depthTexture=source.depthTexture;return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});function WebGLMultisampleRenderTarget(width,height,options){WebGLRenderTarget.call(this,width,height,options);this.samples=4;}WebGLMultisampleRenderTarget.prototype=Object.assign(Object.create(WebGLRenderTarget.prototype),{constructor:WebGLMultisampleRenderTarget,isWebGLMultisampleRenderTarget:true,copy:function copy(source){WebGLRenderTarget.prototype.copy.call(this,source);this.samples=source.samples;return this;}});class Quaternion{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Object.defineProperty(this,'isQuaternion',{value:true});this._x=x;this._y=y;this._z=z;this._w=w;}static slerp(qa,qb,qm,t){return qm.copy(qa).slerp(qb,t);}static slerpFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1,t){// fuzz-free, array-based Quaternion SLERP operation
  2651. var x0=src0[srcOffset0+0],y0=src0[srcOffset0+1],z0=src0[srcOffset0+2],w0=src0[srcOffset0+3];var x1=src1[srcOffset1+0],y1=src1[srcOffset1+1],z1=src1[srcOffset1+2],w1=src1[srcOffset1+3];if(w0!==w1||x0!==x1||y0!==y1||z0!==z1){var s=1-t;var cos=x0*x1+y0*y1+z0*z1+w0*w1,dir=cos>=0?1:-1,sqrSin=1-cos*cos;// Skip the Slerp for tiny steps to avoid numeric problems:
  2652. if(sqrSin>Number.EPSILON){var sin=Math.sqrt(sqrSin),len=Math.atan2(sin,cos*dir);s=Math.sin(s*len)/sin;t=Math.sin(t*len)/sin;}var tDir=t*dir;x0=x0*s+x1*tDir;y0=y0*s+y1*tDir;z0=z0*s+z1*tDir;w0=w0*s+w1*tDir;// Normalize in case we just did a lerp:
  2653. if(s===1-t){var f=1/Math.sqrt(x0*x0+y0*y0+z0*z0+w0*w0);x0*=f;y0*=f;z0*=f;w0*=f;}}dst[dstOffset]=x0;dst[dstOffset+1]=y0;dst[dstOffset+2]=z0;dst[dstOffset+3]=w0;}static multiplyQuaternionsFlat(dst,dstOffset,src0,srcOffset0,src1,srcOffset1){var x0=src0[srcOffset0];var y0=src0[srcOffset0+1];var z0=src0[srcOffset0+2];var w0=src0[srcOffset0+3];var x1=src1[srcOffset1];var y1=src1[srcOffset1+1];var z1=src1[srcOffset1+2];var w1=src1[srcOffset1+3];dst[dstOffset]=x0*w1+w0*x1+y0*z1-z0*y1;dst[dstOffset+1]=y0*w1+w0*y1+z0*x1-x0*z1;dst[dstOffset+2]=z0*w1+w0*z1+x0*y1-y0*x1;dst[dstOffset+3]=w0*w1-x0*x1-y0*y1-z0*z1;return dst;}get x(){return this._x;}set x(value){this._x=value;this._onChangeCallback();}get y(){return this._y;}set y(value){this._y=value;this._onChangeCallback();}get z(){return this._z;}set z(value){this._z=value;this._onChangeCallback();}get w(){return this._w;}set w(value){this._w=value;this._onChangeCallback();}set(x,y,z,w){this._x=x;this._y=y;this._z=z;this._w=w;this._onChangeCallback();return this;}clone(){return new this.constructor(this._x,this._y,this._z,this._w);}copy(quaternion){this._x=quaternion.x;this._y=quaternion.y;this._z=quaternion.z;this._w=quaternion.w;this._onChangeCallback();return this;}setFromEuler(euler,update){if(!(euler&&euler.isEuler)){throw new Error('THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.');}var x=euler._x,y=euler._y,z=euler._z,order=euler._order;// http://www.mathworks.com/matlabcentral/fileexchange/
  2654. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2655. // content/SpinCalc.m
  2656. var cos=Math.cos;var sin=Math.sin;var c1=cos(x/2);var c2=cos(y/2);var c3=cos(z/2);var s1=sin(x/2);var s2=sin(y/2);var s3=sin(z/2);switch(order){case'XYZ':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'YXZ':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case'ZXY':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'ZYX':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;case'YZX':this._x=s1*c2*c3+c1*s2*s3;this._y=c1*s2*c3+s1*c2*s3;this._z=c1*c2*s3-s1*s2*c3;this._w=c1*c2*c3-s1*s2*s3;break;case'XZY':this._x=s1*c2*c3-c1*s2*s3;this._y=c1*s2*c3-s1*c2*s3;this._z=c1*c2*s3+s1*s2*c3;this._w=c1*c2*c3+s1*s2*s3;break;default:console.warn('THREE.Quaternion: .setFromEuler() encountered an unknown order: '+order);}if(update!==false)this._onChangeCallback();return this;}setFromAxisAngle(axis,angle){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2657. // assumes axis is normalized
  2658. var halfAngle=angle/2,s=Math.sin(halfAngle);this._x=axis.x*s;this._y=axis.y*s;this._z=axis.z*s;this._w=Math.cos(halfAngle);this._onChangeCallback();return this;}setFromRotationMatrix(m){// http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2659. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2660. var te=m.elements,m11=te[0],m12=te[4],m13=te[8],m21=te[1],m22=te[5],m23=te[9],m31=te[2],m32=te[6],m33=te[10],trace=m11+m22+m33;if(trace>0){var s=0.5/Math.sqrt(trace+1.0);this._w=0.25/s;this._x=(m32-m23)*s;this._y=(m13-m31)*s;this._z=(m21-m12)*s;}else if(m11>m22&&m11>m33){var _s=2.0*Math.sqrt(1.0+m11-m22-m33);this._w=(m32-m23)/_s;this._x=0.25*_s;this._y=(m12+m21)/_s;this._z=(m13+m31)/_s;}else if(m22>m33){var _s2=2.0*Math.sqrt(1.0+m22-m11-m33);this._w=(m13-m31)/_s2;this._x=(m12+m21)/_s2;this._y=0.25*_s2;this._z=(m23+m32)/_s2;}else {var _s3=2.0*Math.sqrt(1.0+m33-m11-m22);this._w=(m21-m12)/_s3;this._x=(m13+m31)/_s3;this._y=(m23+m32)/_s3;this._z=0.25*_s3;}this._onChangeCallback();return this;}setFromUnitVectors(vFrom,vTo){// assumes direction vectors vFrom and vTo are normalized
  2661. var EPS=0.000001;var r=vFrom.dot(vTo)+1;if(r<EPS){r=0;if(Math.abs(vFrom.x)>Math.abs(vFrom.z)){this._x=-vFrom.y;this._y=vFrom.x;this._z=0;this._w=r;}else {this._x=0;this._y=-vFrom.z;this._z=vFrom.y;this._w=r;}}else {// crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2662. this._x=vFrom.y*vTo.z-vFrom.z*vTo.y;this._y=vFrom.z*vTo.x-vFrom.x*vTo.z;this._z=vFrom.x*vTo.y-vFrom.y*vTo.x;this._w=r;}return this.normalize();}angleTo(q){return 2*Math.acos(Math.abs(MathUtils.clamp(this.dot(q),-1,1)));}rotateTowards(q,step){var angle=this.angleTo(q);if(angle===0)return this;var t=Math.min(1,step/angle);this.slerp(q,t);return this;}identity(){return this.set(0,0,0,1);}invert(){// quaternion is assumed to have unit length
  2663. return this.conjugate();}conjugate(){this._x*=-1;this._y*=-1;this._z*=-1;this._onChangeCallback();return this;}dot(v){return this._x*v._x+this._y*v._y+this._z*v._z+this._w*v._w;}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w;}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w);}normalize(){var l=this.length();if(l===0){this._x=0;this._y=0;this._z=0;this._w=1;}else {l=1/l;this._x=this._x*l;this._y=this._y*l;this._z=this._z*l;this._w=this._w*l;}this._onChangeCallback();return this;}multiply(q,p){if(p!==undefined){console.warn('THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.');return this.multiplyQuaternions(q,p);}return this.multiplyQuaternions(this,q);}premultiply(q){return this.multiplyQuaternions(q,this);}multiplyQuaternions(a,b){// from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2664. var qax=a._x,qay=a._y,qaz=a._z,qaw=a._w;var qbx=b._x,qby=b._y,qbz=b._z,qbw=b._w;this._x=qax*qbw+qaw*qbx+qay*qbz-qaz*qby;this._y=qay*qbw+qaw*qby+qaz*qbx-qax*qbz;this._z=qaz*qbw+qaw*qbz+qax*qby-qay*qbx;this._w=qaw*qbw-qax*qbx-qay*qby-qaz*qbz;this._onChangeCallback();return this;}slerp(qb,t){if(t===0)return this;if(t===1)return this.copy(qb);var x=this._x,y=this._y,z=this._z,w=this._w;// http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2665. var cosHalfTheta=w*qb._w+x*qb._x+y*qb._y+z*qb._z;if(cosHalfTheta<0){this._w=-qb._w;this._x=-qb._x;this._y=-qb._y;this._z=-qb._z;cosHalfTheta=-cosHalfTheta;}else {this.copy(qb);}if(cosHalfTheta>=1.0){this._w=w;this._x=x;this._y=y;this._z=z;return this;}var sqrSinHalfTheta=1.0-cosHalfTheta*cosHalfTheta;if(sqrSinHalfTheta<=Number.EPSILON){var s=1-t;this._w=s*w+t*this._w;this._x=s*x+t*this._x;this._y=s*y+t*this._y;this._z=s*z+t*this._z;this.normalize();this._onChangeCallback();return this;}var sinHalfTheta=Math.sqrt(sqrSinHalfTheta);var halfTheta=Math.atan2(sinHalfTheta,cosHalfTheta);var ratioA=Math.sin((1-t)*halfTheta)/sinHalfTheta,ratioB=Math.sin(t*halfTheta)/sinHalfTheta;this._w=w*ratioA+this._w*ratioB;this._x=x*ratioA+this._x*ratioB;this._y=y*ratioA+this._y*ratioB;this._z=z*ratioA+this._z*ratioB;this._onChangeCallback();return this;}equals(quaternion){return quaternion._x===this._x&&quaternion._y===this._y&&quaternion._z===this._z&&quaternion._w===this._w;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this._x=array[offset];this._y=array[offset+1];this._z=array[offset+2];this._w=array[offset+3];this._onChangeCallback();return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._w;return array;}fromBufferAttribute(attribute,index){this._x=attribute.getX(index);this._y=attribute.getY(index);this._z=attribute.getZ(index);this._w=attribute.getW(index);return this;}_onChange(callback){this._onChangeCallback=callback;return this;}_onChangeCallback(){}}class Vector3{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;Object.defineProperty(this,'isVector3',{value:true});this.x=x;this.y=y;this.z=z;}set(x,y,z){if(z===undefined)z=this.z;// sprite.scale.set(x,y)
  2666. this.x=x;this.y=y;this.z=z;return this;}setScalar(scalar){this.x=scalar;this.y=scalar;this.z=scalar;return this;}setX(x){this.x=x;return this;}setY(y){this.y=y;return this;}setZ(z){this.z=z;return this;}setComponent(index,value){switch(index){case 0:this.x=value;break;case 1:this.y=value;break;case 2:this.z=value;break;default:throw new Error('index is out of range: '+index);}return this;}getComponent(index){switch(index){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error('index is out of range: '+index);}}clone(){return new this.constructor(this.x,this.y,this.z);}copy(v){this.x=v.x;this.y=v.y;this.z=v.z;return this;}add(v,w){if(w!==undefined){console.warn('THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.');return this.addVectors(v,w);}this.x+=v.x;this.y+=v.y;this.z+=v.z;return this;}addScalar(s){this.x+=s;this.y+=s;this.z+=s;return this;}addVectors(a,b){this.x=a.x+b.x;this.y=a.y+b.y;this.z=a.z+b.z;return this;}addScaledVector(v,s){this.x+=v.x*s;this.y+=v.y*s;this.z+=v.z*s;return this;}sub(v,w){if(w!==undefined){console.warn('THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.');return this.subVectors(v,w);}this.x-=v.x;this.y-=v.y;this.z-=v.z;return this;}subScalar(s){this.x-=s;this.y-=s;this.z-=s;return this;}subVectors(a,b){this.x=a.x-b.x;this.y=a.y-b.y;this.z=a.z-b.z;return this;}multiply(v,w){if(w!==undefined){console.warn('THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.');return this.multiplyVectors(v,w);}this.x*=v.x;this.y*=v.y;this.z*=v.z;return this;}multiplyScalar(scalar){this.x*=scalar;this.y*=scalar;this.z*=scalar;return this;}multiplyVectors(a,b){this.x=a.x*b.x;this.y=a.y*b.y;this.z=a.z*b.z;return this;}applyEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.');}return this.applyQuaternion(_quaternion.setFromEuler(euler));}applyAxisAngle(axis,angle){return this.applyQuaternion(_quaternion.setFromAxisAngle(axis,angle));}applyMatrix3(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[3]*y+e[6]*z;this.y=e[1]*x+e[4]*y+e[7]*z;this.z=e[2]*x+e[5]*y+e[8]*z;return this;}applyNormalMatrix(m){return this.applyMatrix3(m).normalize();}applyMatrix4(m){var x=this.x,y=this.y,z=this.z;var e=m.elements;var w=1/(e[3]*x+e[7]*y+e[11]*z+e[15]);this.x=(e[0]*x+e[4]*y+e[8]*z+e[12])*w;this.y=(e[1]*x+e[5]*y+e[9]*z+e[13])*w;this.z=(e[2]*x+e[6]*y+e[10]*z+e[14])*w;return this;}applyQuaternion(q){var x=this.x,y=this.y,z=this.z;var qx=q.x,qy=q.y,qz=q.z,qw=q.w;// calculate quat * vector
  2667. var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;// calculate result * inverse quat
  2668. this.x=ix*qw+iw*-qx+iy*-qz-iz*-qy;this.y=iy*qw+iw*-qy+iz*-qx-ix*-qz;this.z=iz*qw+iw*-qz+ix*-qy-iy*-qx;return this;}project(camera){return this.applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);}unproject(camera){return this.applyMatrix4(camera.projectionMatrixInverse).applyMatrix4(camera.matrixWorld);}transformDirection(m){// input: THREE.Matrix4 affine matrix
  2669. // vector interpreted as a direction
  2670. var x=this.x,y=this.y,z=this.z;var e=m.elements;this.x=e[0]*x+e[4]*y+e[8]*z;this.y=e[1]*x+e[5]*y+e[9]*z;this.z=e[2]*x+e[6]*y+e[10]*z;return this.normalize();}divide(v){this.x/=v.x;this.y/=v.y;this.z/=v.z;return this;}divideScalar(scalar){return this.multiplyScalar(1/scalar);}min(v){this.x=Math.min(this.x,v.x);this.y=Math.min(this.y,v.y);this.z=Math.min(this.z,v.z);return this;}max(v){this.x=Math.max(this.x,v.x);this.y=Math.max(this.y,v.y);this.z=Math.max(this.z,v.z);return this;}clamp(min,max){// assumes min < max, componentwise
  2671. this.x=Math.max(min.x,Math.min(max.x,this.x));this.y=Math.max(min.y,Math.min(max.y,this.y));this.z=Math.max(min.z,Math.min(max.z,this.z));return this;}clampScalar(minVal,maxVal){this.x=Math.max(minVal,Math.min(maxVal,this.x));this.y=Math.max(minVal,Math.min(maxVal,this.y));this.z=Math.max(minVal,Math.min(maxVal,this.z));return this;}clampLength(min,max){var length=this.length();return this.divideScalar(length||1).multiplyScalar(Math.max(min,Math.min(max,length)));}floor(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);this.z=Math.floor(this.z);return this;}ceil(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);this.z=Math.ceil(this.z);return this;}round(){this.x=Math.round(this.x);this.y=Math.round(this.y);this.z=Math.round(this.z);return this;}roundToZero(){this.x=this.x<0?Math.ceil(this.x):Math.floor(this.x);this.y=this.y<0?Math.ceil(this.y):Math.floor(this.y);this.z=this.z<0?Math.ceil(this.z):Math.floor(this.z);return this;}negate(){this.x=-this.x;this.y=-this.y;this.z=-this.z;return this;}dot(v){return this.x*v.x+this.y*v.y+this.z*v.z;}// TODO lengthSquared?
  2672. lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z;}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z);}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z);}normalize(){return this.divideScalar(this.length()||1);}setLength(length){return this.normalize().multiplyScalar(length);}lerp(v,alpha){this.x+=(v.x-this.x)*alpha;this.y+=(v.y-this.y)*alpha;this.z+=(v.z-this.z)*alpha;return this;}lerpVectors(v1,v2,alpha){this.x=v1.x+(v2.x-v1.x)*alpha;this.y=v1.y+(v2.y-v1.y)*alpha;this.z=v1.z+(v2.z-v1.z)*alpha;return this;}cross(v,w){if(w!==undefined){console.warn('THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.');return this.crossVectors(v,w);}return this.crossVectors(this,v);}crossVectors(a,b){var ax=a.x,ay=a.y,az=a.z;var bx=b.x,by=b.y,bz=b.z;this.x=ay*bz-az*by;this.y=az*bx-ax*bz;this.z=ax*by-ay*bx;return this;}projectOnVector(v){var denominator=v.lengthSq();if(denominator===0)return this.set(0,0,0);var scalar=v.dot(this)/denominator;return this.copy(v).multiplyScalar(scalar);}projectOnPlane(planeNormal){_vector.copy(this).projectOnVector(planeNormal);return this.sub(_vector);}reflect(normal){// reflect incident vector off plane orthogonal to normal
  2673. // normal is assumed to have unit length
  2674. return this.sub(_vector.copy(normal).multiplyScalar(2*this.dot(normal)));}angleTo(v){var denominator=Math.sqrt(this.lengthSq()*v.lengthSq());if(denominator===0)return Math.PI/2;var theta=this.dot(v)/denominator;// clamp, to handle numerical problems
  2675. return Math.acos(MathUtils.clamp(theta,-1,1));}distanceTo(v){return Math.sqrt(this.distanceToSquared(v));}distanceToSquared(v){var dx=this.x-v.x,dy=this.y-v.y,dz=this.z-v.z;return dx*dx+dy*dy+dz*dz;}manhattanDistanceTo(v){return Math.abs(this.x-v.x)+Math.abs(this.y-v.y)+Math.abs(this.z-v.z);}setFromSpherical(s){return this.setFromSphericalCoords(s.radius,s.phi,s.theta);}setFromSphericalCoords(radius,phi,theta){var sinPhiRadius=Math.sin(phi)*radius;this.x=sinPhiRadius*Math.sin(theta);this.y=Math.cos(phi)*radius;this.z=sinPhiRadius*Math.cos(theta);return this;}setFromCylindrical(c){return this.setFromCylindricalCoords(c.radius,c.theta,c.y);}setFromCylindricalCoords(radius,theta,y){this.x=radius*Math.sin(theta);this.y=y;this.z=radius*Math.cos(theta);return this;}setFromMatrixPosition(m){var e=m.elements;this.x=e[12];this.y=e[13];this.z=e[14];return this;}setFromMatrixScale(m){var sx=this.setFromMatrixColumn(m,0).length();var sy=this.setFromMatrixColumn(m,1).length();var sz=this.setFromMatrixColumn(m,2).length();this.x=sx;this.y=sy;this.z=sz;return this;}setFromMatrixColumn(m,index){return this.fromArray(m.elements,index*4);}setFromMatrix3Column(m,index){return this.fromArray(m.elements,index*3);}equals(v){return v.x===this.x&&v.y===this.y&&v.z===this.z;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.x=array[offset];this.y=array[offset+1];this.z=array[offset+2];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.x;array[offset+1]=this.y;array[offset+2]=this.z;return array;}fromBufferAttribute(attribute,index,offset){if(offset!==undefined){console.warn('THREE.Vector3: offset has been removed from .fromBufferAttribute().');}this.x=attribute.getX(index);this.y=attribute.getY(index);this.z=attribute.getZ(index);return this;}random(){this.x=Math.random();this.y=Math.random();this.z=Math.random();return this;}}var _vector=/*@__PURE__*/new Vector3();var _quaternion=/*@__PURE__*/new Quaternion();class Box3{constructor(min,max){Object.defineProperty(this,'isBox3',{value:true});this.min=min!==undefined?min:new Vector3(+Infinity,+Infinity,+Infinity);this.max=max!==undefined?max:new Vector3(-Infinity,-Infinity,-Infinity);}set(min,max){this.min.copy(min);this.max.copy(max);return this;}setFromArray(array){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i4=0,l=array.length;_i4<l;_i4+=3){var x=array[_i4];var y=array[_i4+1];var z=array[_i4+2];if(x<minX)minX=x;if(y<minY)minY=y;if(z<minZ)minZ=z;if(x>maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z;}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this;}setFromBufferAttribute(attribute){var minX=+Infinity;var minY=+Infinity;var minZ=+Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;for(var _i5=0,l=attribute.count;_i5<l;_i5++){var x=attribute.getX(_i5);var y=attribute.getY(_i5);var z=attribute.getZ(_i5);if(x<minX)minX=x;if(y<minY)minY=y;if(z<minZ)minZ=z;if(x>maxX)maxX=x;if(y>maxY)maxY=y;if(z>maxZ)maxZ=z;}this.min.set(minX,minY,minZ);this.max.set(maxX,maxY,maxZ);return this;}setFromPoints(points){this.makeEmpty();for(var _i6=0,il=points.length;_i6<il;_i6++){this.expandByPoint(points[_i6]);}return this;}setFromCenterAndSize(center,size){var halfSize=_vector$1.copy(size).multiplyScalar(0.5);this.min.copy(center).sub(halfSize);this.max.copy(center).add(halfSize);return this;}setFromObject(object){this.makeEmpty();return this.expandByObject(object);}clone(){return new this.constructor().copy(this);}copy(box){this.min.copy(box.min);this.max.copy(box.max);return this;}makeEmpty(){this.min.x=this.min.y=this.min.z=+Infinity;this.max.x=this.max.y=this.max.z=-Infinity;return this;}isEmpty(){// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2676. return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z;}getCenter(target){if(target===undefined){console.warn('THREE.Box3: .getCenter() target is now required');target=new Vector3();}return this.isEmpty()?target.set(0,0,0):target.addVectors(this.min,this.max).multiplyScalar(0.5);}getSize(target){if(target===undefined){console.warn('THREE.Box3: .getSize() target is now required');target=new Vector3();}return this.isEmpty()?target.set(0,0,0):target.subVectors(this.max,this.min);}expandByPoint(point){this.min.min(point);this.max.max(point);return this;}expandByVector(vector){this.min.sub(vector);this.max.add(vector);return this;}expandByScalar(scalar){this.min.addScalar(-scalar);this.max.addScalar(scalar);return this;}expandByObject(object){// Computes the world-axis-aligned bounding box of an object (including its children),
  2677. // accounting for both the object's, and children's, world transforms
  2678. object.updateWorldMatrix(false,false);var geometry=object.geometry;if(geometry!==undefined){if(geometry.boundingBox===null){geometry.computeBoundingBox();}_box.copy(geometry.boundingBox);_box.applyMatrix4(object.matrixWorld);this.union(_box);}var children=object.children;for(var _i7=0,l=children.length;_i7<l;_i7++){this.expandByObject(children[_i7]);}return this;}containsPoint(point){return point.x<this.min.x||point.x>this.max.x||point.y<this.min.y||point.y>this.max.y||point.z<this.min.z||point.z>this.max.z?false:true;}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y&&this.min.z<=box.min.z&&box.max.z<=this.max.z;}getParameter(point,target){// This can potentially have a divide by zero if the box
  2679. // has a size dimension of 0.
  2680. if(target===undefined){console.warn('THREE.Box3: .getParameter() target is now required');target=new Vector3();}return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y),(point.z-this.min.z)/(this.max.z-this.min.z));}intersectsBox(box){// using 6 splitting planes to rule out intersections.
  2681. return box.max.x<this.min.x||box.min.x>this.max.x||box.max.y<this.min.y||box.min.y>this.max.y||box.max.z<this.min.z||box.min.z>this.max.z?false:true;}intersectsSphere(sphere){// Find the point on the AABB closest to the sphere center.
  2682. this.clampPoint(sphere.center,_vector$1);// If that point is inside the sphere, the AABB and sphere intersect.
  2683. return _vector$1.distanceToSquared(sphere.center)<=sphere.radius*sphere.radius;}intersectsPlane(plane){// We compute the minimum and maximum dot product values. If those values
  2684. // are on the same side (back or front) of the plane, then there is no intersection.
  2685. var min,max;if(plane.normal.x>0){min=plane.normal.x*this.min.x;max=plane.normal.x*this.max.x;}else {min=plane.normal.x*this.max.x;max=plane.normal.x*this.min.x;}if(plane.normal.y>0){min+=plane.normal.y*this.min.y;max+=plane.normal.y*this.max.y;}else {min+=plane.normal.y*this.max.y;max+=plane.normal.y*this.min.y;}if(plane.normal.z>0){min+=plane.normal.z*this.min.z;max+=plane.normal.z*this.max.z;}else {min+=plane.normal.z*this.max.z;max+=plane.normal.z*this.min.z;}return min<=-plane.constant&&max>=-plane.constant;}intersectsTriangle(triangle){if(this.isEmpty()){return false;}// compute box center and extents
  2686. this.getCenter(_center);_extents.subVectors(this.max,_center);// translate triangle to aabb origin
  2687. _v0.subVectors(triangle.a,_center);_v1.subVectors(triangle.b,_center);_v2.subVectors(triangle.c,_center);// compute edge vectors for triangle
  2688. _f0.subVectors(_v1,_v0);_f1.subVectors(_v2,_v1);_f2.subVectors(_v0,_v2);// test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2689. // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
  2690. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2691. var axes=[0,-_f0.z,_f0.y,0,-_f1.z,_f1.y,0,-_f2.z,_f2.y,_f0.z,0,-_f0.x,_f1.z,0,-_f1.x,_f2.z,0,-_f2.x,-_f0.y,_f0.x,0,-_f1.y,_f1.x,0,-_f2.y,_f2.x,0];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// test 3 face normals from the aabb
  2692. axes=[1,0,0,0,1,0,0,0,1];if(!satForAxes(axes,_v0,_v1,_v2,_extents)){return false;}// finally testing the face normal of the triangle
  2693. // use already existing triangle edge vectors here
  2694. _triangleNormal.crossVectors(_f0,_f1);axes=[_triangleNormal.x,_triangleNormal.y,_triangleNormal.z];return satForAxes(axes,_v0,_v1,_v2,_extents);}clampPoint(point,target){if(target===undefined){console.warn('THREE.Box3: .clampPoint() target is now required');target=new Vector3();}return target.copy(point).clamp(this.min,this.max);}distanceToPoint(point){var clampedPoint=_vector$1.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}getBoundingSphere(target){if(target===undefined){console.error('THREE.Box3: .getBoundingSphere() target is now required');//target = new Sphere(); // removed to avoid cyclic dependency
  2695. }this.getCenter(target.center);target.radius=this.getSize(_vector$1).length()*0.5;return target;}intersect(box){this.min.max(box.min);this.max.min(box.max);// ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  2696. if(this.isEmpty())this.makeEmpty();return this;}union(box){this.min.min(box.min);this.max.max(box.max);return this;}applyMatrix4(matrix){// transform of empty box is an empty box.
  2697. if(this.isEmpty())return this;// NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2698. _points[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(matrix);// 000
  2699. _points[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(matrix);// 001
  2700. _points[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(matrix);// 010
  2701. _points[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(matrix);// 011
  2702. _points[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(matrix);// 100
  2703. _points[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(matrix);// 101
  2704. _points[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(matrix);// 110
  2705. _points[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(matrix);// 111
  2706. this.setFromPoints(_points);return this;}translate(offset){this.min.add(offset);this.max.add(offset);return this;}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}function satForAxes(axes,v0,v1,v2,extents){for(var _i8=0,j=axes.length-3;_i8<=j;_i8+=3){_testAxis.fromArray(axes,_i8);// project the aabb onto the seperating axis
  2707. var r=extents.x*Math.abs(_testAxis.x)+extents.y*Math.abs(_testAxis.y)+extents.z*Math.abs(_testAxis.z);// project all 3 vertices of the triangle onto the seperating axis
  2708. var p0=v0.dot(_testAxis);var p1=v1.dot(_testAxis);var p2=v2.dot(_testAxis);// actual test, basically see if either of the most extreme of the triangle points intersects r
  2709. if(Math.max(-Math.max(p0,p1,p2),Math.min(p0,p1,p2))>r){// points of the projected triangle are outside the projected half-length of the aabb
  2710. // the axis is seperating and we can exit
  2711. return false;}}return true;}var _points=[/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3(),/*@__PURE__*/new Vector3()];var _vector$1=/*@__PURE__*/new Vector3();var _box=/*@__PURE__*/new Box3();// triangle centered vertices
  2712. var _v0=/*@__PURE__*/new Vector3();var _v1=/*@__PURE__*/new Vector3();var _v2=/*@__PURE__*/new Vector3();// triangle edge vectors
  2713. var _f0=/*@__PURE__*/new Vector3();var _f1=/*@__PURE__*/new Vector3();var _f2=/*@__PURE__*/new Vector3();var _center=/*@__PURE__*/new Vector3();var _extents=/*@__PURE__*/new Vector3();var _triangleNormal=/*@__PURE__*/new Vector3();var _testAxis=/*@__PURE__*/new Vector3();var _box$1=/*@__PURE__*/new Box3();class Sphere{constructor(center,radius){this.center=center!==undefined?center:new Vector3();this.radius=radius!==undefined?radius:-1;}set(center,radius){this.center.copy(center);this.radius=radius;return this;}setFromPoints(points,optionalCenter){var center=this.center;if(optionalCenter!==undefined){center.copy(optionalCenter);}else {_box$1.setFromPoints(points).getCenter(center);}var maxRadiusSq=0;for(var _i9=0,il=points.length;_i9<il;_i9++){maxRadiusSq=Math.max(maxRadiusSq,center.distanceToSquared(points[_i9]));}this.radius=Math.sqrt(maxRadiusSq);return this;}clone(){return new this.constructor().copy(this);}copy(sphere){this.center.copy(sphere.center);this.radius=sphere.radius;return this;}isEmpty(){return this.radius<0;}makeEmpty(){this.center.set(0,0,0);this.radius=-1;return this;}containsPoint(point){return point.distanceToSquared(this.center)<=this.radius*this.radius;}distanceToPoint(point){return point.distanceTo(this.center)-this.radius;}intersectsSphere(sphere){var radiusSum=this.radius+sphere.radius;return sphere.center.distanceToSquared(this.center)<=radiusSum*radiusSum;}intersectsBox(box){return box.intersectsSphere(this);}intersectsPlane(plane){return Math.abs(plane.distanceToPoint(this.center))<=this.radius;}clampPoint(point,target){var deltaLengthSq=this.center.distanceToSquared(point);if(target===undefined){console.warn('THREE.Sphere: .clampPoint() target is now required');target=new Vector3();}target.copy(point);if(deltaLengthSq>this.radius*this.radius){target.sub(this.center).normalize();target.multiplyScalar(this.radius).add(this.center);}return target;}getBoundingBox(target){if(target===undefined){console.warn('THREE.Sphere: .getBoundingBox() target is now required');target=new Box3();}if(this.isEmpty()){// Empty sphere produces empty bounding box
  2714. target.makeEmpty();return target;}target.set(this.center,this.center);target.expandByScalar(this.radius);return target;}applyMatrix4(matrix){this.center.applyMatrix4(matrix);this.radius=this.radius*matrix.getMaxScaleOnAxis();return this;}translate(offset){this.center.add(offset);return this;}equals(sphere){return sphere.center.equals(this.center)&&sphere.radius===this.radius;}}var _vector$2=/*@__PURE__*/new Vector3();var _segCenter=/*@__PURE__*/new Vector3();var _segDir=/*@__PURE__*/new Vector3();var _diff=/*@__PURE__*/new Vector3();var _edge1=/*@__PURE__*/new Vector3();var _edge2=/*@__PURE__*/new Vector3();var _normal=/*@__PURE__*/new Vector3();class Ray{constructor(origin,direction){this.origin=origin!==undefined?origin:new Vector3();this.direction=direction!==undefined?direction:new Vector3(0,0,-1);}set(origin,direction){this.origin.copy(origin);this.direction.copy(direction);return this;}clone(){return new this.constructor().copy(this);}copy(ray){this.origin.copy(ray.origin);this.direction.copy(ray.direction);return this;}at(t,target){if(target===undefined){console.warn('THREE.Ray: .at() target is now required');target=new Vector3();}return target.copy(this.direction).multiplyScalar(t).add(this.origin);}lookAt(v){this.direction.copy(v).sub(this.origin).normalize();return this;}recast(t){this.origin.copy(this.at(t,_vector$2));return this;}closestPointToPoint(point,target){if(target===undefined){console.warn('THREE.Ray: .closestPointToPoint() target is now required');target=new Vector3();}target.subVectors(point,this.origin);var directionDistance=target.dot(this.direction);if(directionDistance<0){return target.copy(this.origin);}return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);}distanceToPoint(point){return Math.sqrt(this.distanceSqToPoint(point));}distanceSqToPoint(point){var directionDistance=_vector$2.subVectors(point,this.origin).dot(this.direction);// point behind the ray
  2715. if(directionDistance<0){return this.origin.distanceToSquared(point);}_vector$2.copy(this.direction).multiplyScalar(directionDistance).add(this.origin);return _vector$2.distanceToSquared(point);}distanceSqToSegment(v0,v1,optionalPointOnRay,optionalPointOnSegment){// from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  2716. // It returns the min distance between the ray and the segment
  2717. // defined by v0 and v1
  2718. // It can also set two optional targets :
  2719. // - The closest point on the ray
  2720. // - The closest point on the segment
  2721. _segCenter.copy(v0).add(v1).multiplyScalar(0.5);_segDir.copy(v1).sub(v0).normalize();_diff.copy(this.origin).sub(_segCenter);var segExtent=v0.distanceTo(v1)*0.5;var a01=-this.direction.dot(_segDir);var b0=_diff.dot(this.direction);var b1=-_diff.dot(_segDir);var c=_diff.lengthSq();var det=Math.abs(1-a01*a01);var s0,s1,sqrDist,extDet;if(det>0){// The ray and segment are not parallel.
  2722. s0=a01*b1-b0;s1=a01*b0-b1;extDet=segExtent*det;if(s0>=0){if(s1>=-extDet){if(s1<=extDet){// region 0
  2723. // Minimum at interior points of ray and segment.
  2724. var invDet=1/det;s0*=invDet;s1*=invDet;sqrDist=s0*(s0+a01*s1+2*b0)+s1*(a01*s0+s1+2*b1)+c;}else {// region 1
  2725. s1=segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else {// region 5
  2726. s1=-segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}else {if(s1<=-extDet){// region 4
  2727. s0=Math.max(0,-(-a01*segExtent+b0));s1=s0>0?-segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c;}else if(s1<=extDet){// region 3
  2728. s0=0;s1=Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=s1*(s1+2*b1)+c;}else {// region 2
  2729. s0=Math.max(0,-(a01*segExtent+b0));s1=s0>0?segExtent:Math.min(Math.max(-segExtent,-b1),segExtent);sqrDist=-s0*s0+s1*(s1+2*b1)+c;}}}else {// Ray and segment are parallel.
  2730. s1=a01>0?-segExtent:segExtent;s0=Math.max(0,-(a01*s1+b0));sqrDist=-s0*s0+s1*(s1+2*b1)+c;}if(optionalPointOnRay){optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin);}if(optionalPointOnSegment){optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter);}return sqrDist;}intersectSphere(sphere,target){_vector$2.subVectors(sphere.center,this.origin);var tca=_vector$2.dot(this.direction);var d2=_vector$2.dot(_vector$2)-tca*tca;var radius2=sphere.radius*sphere.radius;if(d2>radius2)return null;var thc=Math.sqrt(radius2-d2);// t0 = first intersect point - entrance on front of sphere
  2731. var t0=tca-thc;// t1 = second intersect point - exit point on back of sphere
  2732. var t1=tca+thc;// test to see if both t0 and t1 are behind the ray - if so, return null
  2733. if(t0<0&&t1<0)return null;// test to see if t0 is behind the ray:
  2734. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  2735. // in order to always return an intersect point that is in front of the ray.
  2736. if(t0<0)return this.at(t1,target);// else t0 is in front of the ray, so return the first collision point scaled by t0
  2737. return this.at(t0,target);}intersectsSphere(sphere){return this.distanceSqToPoint(sphere.center)<=sphere.radius*sphere.radius;}distanceToPlane(plane){var denominator=plane.normal.dot(this.direction);if(denominator===0){// line is coplanar, return origin
  2738. if(plane.distanceToPoint(this.origin)===0){return 0;}// Null is preferable to undefined since undefined means.... it is undefined
  2739. return null;}var t=-(this.origin.dot(plane.normal)+plane.constant)/denominator;// Return if the ray never intersects the plane
  2740. return t>=0?t:null;}intersectPlane(plane,target){var t=this.distanceToPlane(plane);if(t===null){return null;}return this.at(t,target);}intersectsPlane(plane){// check if the ray lies on the plane first
  2741. var distToPoint=plane.distanceToPoint(this.origin);if(distToPoint===0){return true;}var denominator=plane.normal.dot(this.direction);if(denominator*distToPoint<0){return true;}// ray origin is behind the plane (and is pointing behind it)
  2742. return false;}intersectBox(box,target){var tmin,tmax,tymin,tymax,tzmin,tzmax;var invdirx=1/this.direction.x,invdiry=1/this.direction.y,invdirz=1/this.direction.z;var origin=this.origin;if(invdirx>=0){tmin=(box.min.x-origin.x)*invdirx;tmax=(box.max.x-origin.x)*invdirx;}else {tmin=(box.max.x-origin.x)*invdirx;tmax=(box.min.x-origin.x)*invdirx;}if(invdiry>=0){tymin=(box.min.y-origin.y)*invdiry;tymax=(box.max.y-origin.y)*invdiry;}else {tymin=(box.max.y-origin.y)*invdiry;tymax=(box.min.y-origin.y)*invdiry;}if(tmin>tymax||tymin>tmax)return null;// These lines also handle the case where tmin or tmax is NaN
  2743. // (result of 0 * Infinity). x !== x returns true if x is NaN
  2744. if(tymin>tmin||tmin!==tmin)tmin=tymin;if(tymax<tmax||tmax!==tmax)tmax=tymax;if(invdirz>=0){tzmin=(box.min.z-origin.z)*invdirz;tzmax=(box.max.z-origin.z)*invdirz;}else {tzmin=(box.max.z-origin.z)*invdirz;tzmax=(box.min.z-origin.z)*invdirz;}if(tmin>tzmax||tzmin>tmax)return null;if(tzmin>tmin||tmin!==tmin)tmin=tzmin;if(tzmax<tmax||tmax!==tmax)tmax=tzmax;//return point closest to the ray (positive side)
  2745. if(tmax<0)return null;return this.at(tmin>=0?tmin:tmax,target);}intersectsBox(box){return this.intersectBox(box,_vector$2)!==null;}intersectTriangle(a,b,c,backfaceCulling,target){// Compute the offset origin, edges, and normal.
  2746. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  2747. _edge1.subVectors(b,a);_edge2.subVectors(c,a);_normal.crossVectors(_edge1,_edge2);// Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  2748. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  2749. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  2750. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  2751. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  2752. var DdN=this.direction.dot(_normal);var sign;if(DdN>0){if(backfaceCulling)return null;sign=1;}else if(DdN<0){sign=-1;DdN=-DdN;}else {return null;}_diff.subVectors(this.origin,a);var DdQxE2=sign*this.direction.dot(_edge2.crossVectors(_diff,_edge2));// b1 < 0, no intersection
  2753. if(DdQxE2<0){return null;}var DdE1xQ=sign*this.direction.dot(_edge1.cross(_diff));// b2 < 0, no intersection
  2754. if(DdE1xQ<0){return null;}// b1+b2 > 1, no intersection
  2755. if(DdQxE2+DdE1xQ>DdN){return null;}// Line intersects triangle, check if ray does.
  2756. var QdN=-sign*_diff.dot(_normal);// t < 0, no intersection
  2757. if(QdN<0){return null;}// Ray intersects triangle.
  2758. return this.at(QdN/DdN,target);}applyMatrix4(matrix4){this.origin.applyMatrix4(matrix4);this.direction.transformDirection(matrix4);return this;}equals(ray){return ray.origin.equals(this.origin)&&ray.direction.equals(this.direction);}}class Matrix4{constructor(){Object.defineProperty(this,'isMatrix4',{value:true});this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];if(arguments.length>0){console.error('THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.');}}set(n11,n12,n13,n14,n21,n22,n23,n24,n31,n32,n33,n34,n41,n42,n43,n44){var te=this.elements;te[0]=n11;te[4]=n12;te[8]=n13;te[12]=n14;te[1]=n21;te[5]=n22;te[9]=n23;te[13]=n24;te[2]=n31;te[6]=n32;te[10]=n33;te[14]=n34;te[3]=n41;te[7]=n42;te[11]=n43;te[15]=n44;return this;}identity(){this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1);return this;}clone(){return new Matrix4().fromArray(this.elements);}copy(m){var te=this.elements;var me=m.elements;te[0]=me[0];te[1]=me[1];te[2]=me[2];te[3]=me[3];te[4]=me[4];te[5]=me[5];te[6]=me[6];te[7]=me[7];te[8]=me[8];te[9]=me[9];te[10]=me[10];te[11]=me[11];te[12]=me[12];te[13]=me[13];te[14]=me[14];te[15]=me[15];return this;}copyPosition(m){var te=this.elements,me=m.elements;te[12]=me[12];te[13]=me[13];te[14]=me[14];return this;}extractBasis(xAxis,yAxis,zAxis){xAxis.setFromMatrixColumn(this,0);yAxis.setFromMatrixColumn(this,1);zAxis.setFromMatrixColumn(this,2);return this;}makeBasis(xAxis,yAxis,zAxis){this.set(xAxis.x,yAxis.x,zAxis.x,0,xAxis.y,yAxis.y,zAxis.y,0,xAxis.z,yAxis.z,zAxis.z,0,0,0,0,1);return this;}extractRotation(m){// this method does not support reflection matrices
  2759. var te=this.elements;var me=m.elements;var scaleX=1/_v1$1.setFromMatrixColumn(m,0).length();var scaleY=1/_v1$1.setFromMatrixColumn(m,1).length();var scaleZ=1/_v1$1.setFromMatrixColumn(m,2).length();te[0]=me[0]*scaleX;te[1]=me[1]*scaleX;te[2]=me[2]*scaleX;te[3]=0;te[4]=me[4]*scaleY;te[5]=me[5]*scaleY;te[6]=me[6]*scaleY;te[7]=0;te[8]=me[8]*scaleZ;te[9]=me[9]*scaleZ;te[10]=me[10]*scaleZ;te[11]=0;te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}makeRotationFromEuler(euler){if(!(euler&&euler.isEuler)){console.error('THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.');}var te=this.elements;var x=euler.x,y=euler.y,z=euler.z;var a=Math.cos(x),b=Math.sin(x);var c=Math.cos(y),d=Math.sin(y);var e=Math.cos(z),f=Math.sin(z);if(euler.order==='XYZ'){var ae=a*e,af=a*f,be=b*e,bf=b*f;te[0]=c*e;te[4]=-c*f;te[8]=d;te[1]=af+be*d;te[5]=ae-bf*d;te[9]=-b*c;te[2]=bf-ae*d;te[6]=be+af*d;te[10]=a*c;}else if(euler.order==='YXZ'){var ce=c*e,cf=c*f,de=d*e,df=d*f;te[0]=ce+df*b;te[4]=de*b-cf;te[8]=a*d;te[1]=a*f;te[5]=a*e;te[9]=-b;te[2]=cf*b-de;te[6]=df+ce*b;te[10]=a*c;}else if(euler.order==='ZXY'){var _ce=c*e,_cf=c*f,_de=d*e,_df=d*f;te[0]=_ce-_df*b;te[4]=-a*f;te[8]=_de+_cf*b;te[1]=_cf+_de*b;te[5]=a*e;te[9]=_df-_ce*b;te[2]=-a*d;te[6]=b;te[10]=a*c;}else if(euler.order==='ZYX'){var _ae=a*e,_af=a*f,_be=b*e,_bf=b*f;te[0]=c*e;te[4]=_be*d-_af;te[8]=_ae*d+_bf;te[1]=c*f;te[5]=_bf*d+_ae;te[9]=_af*d-_be;te[2]=-d;te[6]=b*c;te[10]=a*c;}else if(euler.order==='YZX'){var ac=a*c,ad=a*d,bc=b*c,bd=b*d;te[0]=c*e;te[4]=bd-ac*f;te[8]=bc*f+ad;te[1]=f;te[5]=a*e;te[9]=-b*e;te[2]=-d*e;te[6]=ad*f+bc;te[10]=ac-bd*f;}else if(euler.order==='XZY'){var _ac=a*c,_ad=a*d,_bc=b*c,_bd=b*d;te[0]=c*e;te[4]=-f;te[8]=d*e;te[1]=_ac*f+_bd;te[5]=a*e;te[9]=_ad*f-_bc;te[2]=_bc*f-_ad;te[6]=b*e;te[10]=_bd*f+_ac;}// bottom row
  2760. te[3]=0;te[7]=0;te[11]=0;// last column
  2761. te[12]=0;te[13]=0;te[14]=0;te[15]=1;return this;}makeRotationFromQuaternion(q){return this.compose(_zero,q,_one);}lookAt(eye,target,up){var te=this.elements;_z.subVectors(eye,target);if(_z.lengthSq()===0){// eye and target are in the same position
  2762. _z.z=1;}_z.normalize();_x.crossVectors(up,_z);if(_x.lengthSq()===0){// up and z are parallel
  2763. if(Math.abs(up.z)===1){_z.x+=0.0001;}else {_z.z+=0.0001;}_z.normalize();_x.crossVectors(up,_z);}_x.normalize();_y.crossVectors(_z,_x);te[0]=_x.x;te[4]=_y.x;te[8]=_z.x;te[1]=_x.y;te[5]=_y.y;te[9]=_z.y;te[2]=_x.z;te[6]=_y.z;te[10]=_z.z;return this;}multiply(m,n){if(n!==undefined){console.warn('THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.');return this.multiplyMatrices(m,n);}return this.multiplyMatrices(this,m);}premultiply(m){return this.multiplyMatrices(m,this);}multiplyMatrices(a,b){var ae=a.elements;var be=b.elements;var te=this.elements;var a11=ae[0],a12=ae[4],a13=ae[8],a14=ae[12];var a21=ae[1],a22=ae[5],a23=ae[9],a24=ae[13];var a31=ae[2],a32=ae[6],a33=ae[10],a34=ae[14];var a41=ae[3],a42=ae[7],a43=ae[11],a44=ae[15];var b11=be[0],b12=be[4],b13=be[8],b14=be[12];var b21=be[1],b22=be[5],b23=be[9],b24=be[13];var b31=be[2],b32=be[6],b33=be[10],b34=be[14];var b41=be[3],b42=be[7],b43=be[11],b44=be[15];te[0]=a11*b11+a12*b21+a13*b31+a14*b41;te[4]=a11*b12+a12*b22+a13*b32+a14*b42;te[8]=a11*b13+a12*b23+a13*b33+a14*b43;te[12]=a11*b14+a12*b24+a13*b34+a14*b44;te[1]=a21*b11+a22*b21+a23*b31+a24*b41;te[5]=a21*b12+a22*b22+a23*b32+a24*b42;te[9]=a21*b13+a22*b23+a23*b33+a24*b43;te[13]=a21*b14+a22*b24+a23*b34+a24*b44;te[2]=a31*b11+a32*b21+a33*b31+a34*b41;te[6]=a31*b12+a32*b22+a33*b32+a34*b42;te[10]=a31*b13+a32*b23+a33*b33+a34*b43;te[14]=a31*b14+a32*b24+a33*b34+a34*b44;te[3]=a41*b11+a42*b21+a43*b31+a44*b41;te[7]=a41*b12+a42*b22+a43*b32+a44*b42;te[11]=a41*b13+a42*b23+a43*b33+a44*b43;te[15]=a41*b14+a42*b24+a43*b34+a44*b44;return this;}multiplyScalar(s){var te=this.elements;te[0]*=s;te[4]*=s;te[8]*=s;te[12]*=s;te[1]*=s;te[5]*=s;te[9]*=s;te[13]*=s;te[2]*=s;te[6]*=s;te[10]*=s;te[14]*=s;te[3]*=s;te[7]*=s;te[11]*=s;te[15]*=s;return this;}determinant(){var te=this.elements;var n11=te[0],n12=te[4],n13=te[8],n14=te[12];var n21=te[1],n22=te[5],n23=te[9],n24=te[13];var n31=te[2],n32=te[6],n33=te[10],n34=te[14];var n41=te[3],n42=te[7],n43=te[11],n44=te[15];//TODO: make this more efficient
  2764. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2765. return n41*(+n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34)+n42*(+n11*n23*n34-n11*n24*n33+n14*n21*n33-n13*n21*n34+n13*n24*n31-n14*n23*n31)+n43*(+n11*n24*n32-n11*n22*n34-n14*n21*n32+n12*n21*n34+n14*n22*n31-n12*n24*n31)+n44*(-n13*n22*n31-n11*n23*n32+n11*n22*n33+n13*n21*n32-n12*n21*n33+n12*n23*n31);}transpose(){var te=this.elements;var tmp;tmp=te[1];te[1]=te[4];te[4]=tmp;tmp=te[2];te[2]=te[8];te[8]=tmp;tmp=te[6];te[6]=te[9];te[9]=tmp;tmp=te[3];te[3]=te[12];te[12]=tmp;tmp=te[7];te[7]=te[13];te[13]=tmp;tmp=te[11];te[11]=te[14];te[14]=tmp;return this;}setPosition(x,y,z){var te=this.elements;if(x.isVector3){te[12]=x.x;te[13]=x.y;te[14]=x.z;}else {te[12]=x;te[13]=y;te[14]=z;}return this;}invert(){// based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2766. var te=this.elements,n11=te[0],n21=te[1],n31=te[2],n41=te[3],n12=te[4],n22=te[5],n32=te[6],n42=te[7],n13=te[8],n23=te[9],n33=te[10],n43=te[11],n14=te[12],n24=te[13],n34=te[14],n44=te[15],t11=n23*n34*n42-n24*n33*n42+n24*n32*n43-n22*n34*n43-n23*n32*n44+n22*n33*n44,t12=n14*n33*n42-n13*n34*n42-n14*n32*n43+n12*n34*n43+n13*n32*n44-n12*n33*n44,t13=n13*n24*n42-n14*n23*n42+n14*n22*n43-n12*n24*n43-n13*n22*n44+n12*n23*n44,t14=n14*n23*n32-n13*n24*n32-n14*n22*n33+n12*n24*n33+n13*n22*n34-n12*n23*n34;var det=n11*t11+n21*t12+n31*t13+n41*t14;if(det===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);var detInv=1/det;te[0]=t11*detInv;te[1]=(n24*n33*n41-n23*n34*n41-n24*n31*n43+n21*n34*n43+n23*n31*n44-n21*n33*n44)*detInv;te[2]=(n22*n34*n41-n24*n32*n41+n24*n31*n42-n21*n34*n42-n22*n31*n44+n21*n32*n44)*detInv;te[3]=(n23*n32*n41-n22*n33*n41-n23*n31*n42+n21*n33*n42+n22*n31*n43-n21*n32*n43)*detInv;te[4]=t12*detInv;te[5]=(n13*n34*n41-n14*n33*n41+n14*n31*n43-n11*n34*n43-n13*n31*n44+n11*n33*n44)*detInv;te[6]=(n14*n32*n41-n12*n34*n41-n14*n31*n42+n11*n34*n42+n12*n31*n44-n11*n32*n44)*detInv;te[7]=(n12*n33*n41-n13*n32*n41+n13*n31*n42-n11*n33*n42-n12*n31*n43+n11*n32*n43)*detInv;te[8]=t13*detInv;te[9]=(n14*n23*n41-n13*n24*n41-n14*n21*n43+n11*n24*n43+n13*n21*n44-n11*n23*n44)*detInv;te[10]=(n12*n24*n41-n14*n22*n41+n14*n21*n42-n11*n24*n42-n12*n21*n44+n11*n22*n44)*detInv;te[11]=(n13*n22*n41-n12*n23*n41-n13*n21*n42+n11*n23*n42+n12*n21*n43-n11*n22*n43)*detInv;te[12]=t14*detInv;te[13]=(n13*n24*n31-n14*n23*n31+n14*n21*n33-n11*n24*n33-n13*n21*n34+n11*n23*n34)*detInv;te[14]=(n14*n22*n31-n12*n24*n31-n14*n21*n32+n11*n24*n32+n12*n21*n34-n11*n22*n34)*detInv;te[15]=(n12*n23*n31-n13*n22*n31+n13*n21*n32-n11*n23*n32-n12*n21*n33+n11*n22*n33)*detInv;return this;}scale(v){var te=this.elements;var x=v.x,y=v.y,z=v.z;te[0]*=x;te[4]*=y;te[8]*=z;te[1]*=x;te[5]*=y;te[9]*=z;te[2]*=x;te[6]*=y;te[10]*=z;te[3]*=x;te[7]*=y;te[11]*=z;return this;}getMaxScaleOnAxis(){var te=this.elements;var scaleXSq=te[0]*te[0]+te[1]*te[1]+te[2]*te[2];var scaleYSq=te[4]*te[4]+te[5]*te[5]+te[6]*te[6];var scaleZSq=te[8]*te[8]+te[9]*te[9]+te[10]*te[10];return Math.sqrt(Math.max(scaleXSq,scaleYSq,scaleZSq));}makeTranslation(x,y,z){this.set(1,0,0,x,0,1,0,y,0,0,1,z,0,0,0,1);return this;}makeRotationX(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(1,0,0,0,0,c,-s,0,0,s,c,0,0,0,0,1);return this;}makeRotationY(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,0,s,0,0,1,0,0,-s,0,c,0,0,0,0,1);return this;}makeRotationZ(theta){var c=Math.cos(theta),s=Math.sin(theta);this.set(c,-s,0,0,s,c,0,0,0,0,1,0,0,0,0,1);return this;}makeRotationAxis(axis,angle){// Based on http://www.gamedev.net/reference/articles/article1199.asp
  2767. var c=Math.cos(angle);var s=Math.sin(angle);var t=1-c;var x=axis.x,y=axis.y,z=axis.z;var tx=t*x,ty=t*y;this.set(tx*x+c,tx*y-s*z,tx*z+s*y,0,tx*y+s*z,ty*y+c,ty*z-s*x,0,tx*z-s*y,ty*z+s*x,t*z*z+c,0,0,0,0,1);return this;}makeScale(x,y,z){this.set(x,0,0,0,0,y,0,0,0,0,z,0,0,0,0,1);return this;}makeShear(x,y,z){this.set(1,y,z,0,x,1,z,0,x,y,1,0,0,0,0,1);return this;}compose(position,quaternion,scale){var te=this.elements;var x=quaternion._x,y=quaternion._y,z=quaternion._z,w=quaternion._w;var x2=x+x,y2=y+y,z2=z+z;var xx=x*x2,xy=x*y2,xz=x*z2;var yy=y*y2,yz=y*z2,zz=z*z2;var wx=w*x2,wy=w*y2,wz=w*z2;var sx=scale.x,sy=scale.y,sz=scale.z;te[0]=(1-(yy+zz))*sx;te[1]=(xy+wz)*sx;te[2]=(xz-wy)*sx;te[3]=0;te[4]=(xy-wz)*sy;te[5]=(1-(xx+zz))*sy;te[6]=(yz+wx)*sy;te[7]=0;te[8]=(xz+wy)*sz;te[9]=(yz-wx)*sz;te[10]=(1-(xx+yy))*sz;te[11]=0;te[12]=position.x;te[13]=position.y;te[14]=position.z;te[15]=1;return this;}decompose(position,quaternion,scale){var te=this.elements;var sx=_v1$1.set(te[0],te[1],te[2]).length();var sy=_v1$1.set(te[4],te[5],te[6]).length();var sz=_v1$1.set(te[8],te[9],te[10]).length();// if determine is negative, we need to invert one scale
  2768. var det=this.determinant();if(det<0)sx=-sx;position.x=te[12];position.y=te[13];position.z=te[14];// scale the rotation part
  2769. _m1.copy(this);var invSX=1/sx;var invSY=1/sy;var invSZ=1/sz;_m1.elements[0]*=invSX;_m1.elements[1]*=invSX;_m1.elements[2]*=invSX;_m1.elements[4]*=invSY;_m1.elements[5]*=invSY;_m1.elements[6]*=invSY;_m1.elements[8]*=invSZ;_m1.elements[9]*=invSZ;_m1.elements[10]*=invSZ;quaternion.setFromRotationMatrix(_m1);scale.x=sx;scale.y=sy;scale.z=sz;return this;}makePerspective(left,right,top,bottom,near,far){if(far===undefined){console.warn('THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.');}var te=this.elements;var x=2*near/(right-left);var y=2*near/(top-bottom);var a=(right+left)/(right-left);var b=(top+bottom)/(top-bottom);var c=-(far+near)/(far-near);var d=-2*far*near/(far-near);te[0]=x;te[4]=0;te[8]=a;te[12]=0;te[1]=0;te[5]=y;te[9]=b;te[13]=0;te[2]=0;te[6]=0;te[10]=c;te[14]=d;te[3]=0;te[7]=0;te[11]=-1;te[15]=0;return this;}makeOrthographic(left,right,top,bottom,near,far){var te=this.elements;var w=1.0/(right-left);var h=1.0/(top-bottom);var p=1.0/(far-near);var x=(right+left)*w;var y=(top+bottom)*h;var z=(far+near)*p;te[0]=2*w;te[4]=0;te[8]=0;te[12]=-x;te[1]=0;te[5]=2*h;te[9]=0;te[13]=-y;te[2]=0;te[6]=0;te[10]=-2*p;te[14]=-z;te[3]=0;te[7]=0;te[11]=0;te[15]=1;return this;}equals(matrix){var te=this.elements;var me=matrix.elements;for(var _i10=0;_i10<16;_i10++){if(te[_i10]!==me[_i10])return false;}return true;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i11=0;_i11<16;_i11++){this.elements[_i11]=array[_i11+offset];}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var te=this.elements;array[offset]=te[0];array[offset+1]=te[1];array[offset+2]=te[2];array[offset+3]=te[3];array[offset+4]=te[4];array[offset+5]=te[5];array[offset+6]=te[6];array[offset+7]=te[7];array[offset+8]=te[8];array[offset+9]=te[9];array[offset+10]=te[10];array[offset+11]=te[11];array[offset+12]=te[12];array[offset+13]=te[13];array[offset+14]=te[14];array[offset+15]=te[15];return array;}}var _v1$1=/*@__PURE__*/new Vector3();var _m1=/*@__PURE__*/new Matrix4();var _zero=/*@__PURE__*/new Vector3(0,0,0);var _one=/*@__PURE__*/new Vector3(1,1,1);var _x=/*@__PURE__*/new Vector3();var _y=/*@__PURE__*/new Vector3();var _z=/*@__PURE__*/new Vector3();class Euler{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var order=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Euler.DefaultOrder;Object.defineProperty(this,'isEuler',{value:true});this._x=x;this._y=y;this._z=z;this._order=order;}get x(){return this._x;}set x(value){this._x=value;this._onChangeCallback();}get y(){return this._y;}set y(value){this._y=value;this._onChangeCallback();}get z(){return this._z;}set z(value){this._z=value;this._onChangeCallback();}get order(){return this._order;}set order(value){this._order=value;this._onChangeCallback();}set(x,y,z,order){this._x=x;this._y=y;this._z=z;this._order=order||this._order;this._onChangeCallback();return this;}clone(){return new this.constructor(this._x,this._y,this._z,this._order);}copy(euler){this._x=euler._x;this._y=euler._y;this._z=euler._z;this._order=euler._order;this._onChangeCallback();return this;}setFromRotationMatrix(m,order,update){var clamp=MathUtils.clamp;// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2770. var te=m.elements;var m11=te[0],m12=te[4],m13=te[8];var m21=te[1],m22=te[5],m23=te[9];var m31=te[2],m32=te[6],m33=te[10];order=order||this._order;switch(order){case'XYZ':this._y=Math.asin(clamp(m13,-1,1));if(Math.abs(m13)<0.9999999){this._x=Math.atan2(-m23,m33);this._z=Math.atan2(-m12,m11);}else {this._x=Math.atan2(m32,m22);this._z=0;}break;case'YXZ':this._x=Math.asin(-clamp(m23,-1,1));if(Math.abs(m23)<0.9999999){this._y=Math.atan2(m13,m33);this._z=Math.atan2(m21,m22);}else {this._y=Math.atan2(-m31,m11);this._z=0;}break;case'ZXY':this._x=Math.asin(clamp(m32,-1,1));if(Math.abs(m32)<0.9999999){this._y=Math.atan2(-m31,m33);this._z=Math.atan2(-m12,m22);}else {this._y=0;this._z=Math.atan2(m21,m11);}break;case'ZYX':this._y=Math.asin(-clamp(m31,-1,1));if(Math.abs(m31)<0.9999999){this._x=Math.atan2(m32,m33);this._z=Math.atan2(m21,m11);}else {this._x=0;this._z=Math.atan2(-m12,m22);}break;case'YZX':this._z=Math.asin(clamp(m21,-1,1));if(Math.abs(m21)<0.9999999){this._x=Math.atan2(-m23,m22);this._y=Math.atan2(-m31,m11);}else {this._x=0;this._y=Math.atan2(m13,m33);}break;case'XZY':this._z=Math.asin(-clamp(m12,-1,1));if(Math.abs(m12)<0.9999999){this._x=Math.atan2(m32,m22);this._y=Math.atan2(m13,m11);}else {this._x=Math.atan2(-m23,m33);this._y=0;}break;default:console.warn('THREE.Euler: .setFromRotationMatrix() encountered an unknown order: '+order);}this._order=order;if(update!==false)this._onChangeCallback();return this;}setFromQuaternion(q,order,update){_matrix.makeRotationFromQuaternion(q);return this.setFromRotationMatrix(_matrix,order,update);}setFromVector3(v,order){return this.set(v.x,v.y,v.z,order||this._order);}reorder(newOrder){// WARNING: this discards revolution information -bhouston
  2771. _quaternion$1.setFromEuler(this);return this.setFromQuaternion(_quaternion$1,newOrder);}equals(euler){return euler._x===this._x&&euler._y===this._y&&euler._z===this._z&&euler._order===this._order;}fromArray(array){this._x=array[0];this._y=array[1];this._z=array[2];if(array[3]!==undefined)this._order=array[3];this._onChangeCallback();return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this._x;array[offset+1]=this._y;array[offset+2]=this._z;array[offset+3]=this._order;return array;}toVector3(optionalResult){if(optionalResult){return optionalResult.set(this._x,this._y,this._z);}else {return new Vector3(this._x,this._y,this._z);}}_onChange(callback){this._onChangeCallback=callback;return this;}_onChangeCallback(){}}Euler.DefaultOrder='XYZ';Euler.RotationOrders=['XYZ','YZX','ZXY','XZY','YXZ','ZYX'];var _matrix=/*@__PURE__*/new Matrix4();var _quaternion$1=/*@__PURE__*/new Quaternion();class Layers{constructor(){this.mask=1|0;}set(channel){this.mask=1<<channel|0;}enable(channel){this.mask|=1<<channel|0;}enableAll(){this.mask=0xffffffff|0;}toggle(channel){this.mask^=1<<channel|0;}disable(channel){this.mask&=~(1<<channel|0);}disableAll(){this.mask=0;}test(layers){return (this.mask&layers.mask)!==0;}}var _object3DId=0;var _v1$2=new Vector3();var _q1=new Quaternion();var _m1$1=new Matrix4();var _target=new Vector3();var _position=new Vector3();var _scale=new Vector3();var _quaternion$2=new Quaternion();var _xAxis=new Vector3(1,0,0);var _yAxis=new Vector3(0,1,0);var _zAxis=new Vector3(0,0,1);var _addedEvent={type:'added'};var _removedEvent={type:'removed'};function Object3D(){Object.defineProperty(this,'id',{value:_object3DId++});this.uuid=MathUtils.generateUUID();this.name='';this.type='Object3D';this.parent=null;this.children=[];this.up=Object3D.DefaultUp.clone();var position=new Vector3();var rotation=new Euler();var quaternion=new Quaternion();var scale=new Vector3(1,1,1);function onRotationChange(){quaternion.setFromEuler(rotation,false);}function onQuaternionChange(){rotation.setFromQuaternion(quaternion,undefined,false);}rotation._onChange(onRotationChange);quaternion._onChange(onQuaternionChange);Object.defineProperties(this,{position:{configurable:true,enumerable:true,value:position},rotation:{configurable:true,enumerable:true,value:rotation},quaternion:{configurable:true,enumerable:true,value:quaternion},scale:{configurable:true,enumerable:true,value:scale},modelViewMatrix:{value:new Matrix4()},normalMatrix:{value:new Matrix3()}});this.matrix=new Matrix4();this.matrixWorld=new Matrix4();this.matrixAutoUpdate=Object3D.DefaultMatrixAutoUpdate;this.matrixWorldNeedsUpdate=false;this.layers=new Layers();this.visible=true;this.castShadow=false;this.receiveShadow=false;this.frustumCulled=true;this.renderOrder=0;this.animations=[];this.userData={};}Object3D.DefaultUp=new Vector3(0,1,0);Object3D.DefaultMatrixAutoUpdate=true;Object3D.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Object3D,isObject3D:true,onBeforeRender:function onBeforeRender(){},onAfterRender:function onAfterRender(){},applyMatrix4:function applyMatrix4(matrix){if(this.matrixAutoUpdate)this.updateMatrix();this.matrix.premultiply(matrix);this.matrix.decompose(this.position,this.quaternion,this.scale);},applyQuaternion:function applyQuaternion(q){this.quaternion.premultiply(q);return this;},setRotationFromAxisAngle:function setRotationFromAxisAngle(axis,angle){// assumes axis is normalized
  2772. this.quaternion.setFromAxisAngle(axis,angle);},setRotationFromEuler:function setRotationFromEuler(euler){this.quaternion.setFromEuler(euler,true);},setRotationFromMatrix:function setRotationFromMatrix(m){// assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2773. this.quaternion.setFromRotationMatrix(m);},setRotationFromQuaternion:function setRotationFromQuaternion(q){// assumes q is normalized
  2774. this.quaternion.copy(q);},rotateOnAxis:function rotateOnAxis(axis,angle){// rotate object on axis in object space
  2775. // axis is assumed to be normalized
  2776. _q1.setFromAxisAngle(axis,angle);this.quaternion.multiply(_q1);return this;},rotateOnWorldAxis:function rotateOnWorldAxis(axis,angle){// rotate object on axis in world space
  2777. // axis is assumed to be normalized
  2778. // method assumes no rotated parent
  2779. _q1.setFromAxisAngle(axis,angle);this.quaternion.premultiply(_q1);return this;},rotateX:function rotateX(angle){return this.rotateOnAxis(_xAxis,angle);},rotateY:function rotateY(angle){return this.rotateOnAxis(_yAxis,angle);},rotateZ:function rotateZ(angle){return this.rotateOnAxis(_zAxis,angle);},translateOnAxis:function translateOnAxis(axis,distance){// translate object by distance along axis in object space
  2780. // axis is assumed to be normalized
  2781. _v1$2.copy(axis).applyQuaternion(this.quaternion);this.position.add(_v1$2.multiplyScalar(distance));return this;},translateX:function translateX(distance){return this.translateOnAxis(_xAxis,distance);},translateY:function translateY(distance){return this.translateOnAxis(_yAxis,distance);},translateZ:function translateZ(distance){return this.translateOnAxis(_zAxis,distance);},localToWorld:function localToWorld(vector){return vector.applyMatrix4(this.matrixWorld);},worldToLocal:function worldToLocal(vector){return vector.applyMatrix4(_m1$1.copy(this.matrixWorld).invert());},lookAt:function lookAt(x,y,z){// This method does not support objects having non-uniformly-scaled parent(s)
  2782. if(x.isVector3){_target.copy(x);}else {_target.set(x,y,z);}var parent=this.parent;this.updateWorldMatrix(true,false);_position.setFromMatrixPosition(this.matrixWorld);if(this.isCamera||this.isLight){_m1$1.lookAt(_position,_target,this.up);}else {_m1$1.lookAt(_target,_position,this.up);}this.quaternion.setFromRotationMatrix(_m1$1);if(parent){_m1$1.extractRotation(parent.matrixWorld);_q1.setFromRotationMatrix(_m1$1);this.quaternion.premultiply(_q1.invert());}},add:function add(object){if(arguments.length>1){for(var _i12=0;_i12<arguments.length;_i12++){this.add(arguments[_i12]);}return this;}if(object===this){console.error('THREE.Object3D.add: object can\'t be added as a child of itself.',object);return this;}if(object&&object.isObject3D){if(object.parent!==null){object.parent.remove(object);}object.parent=this;this.children.push(object);object.dispatchEvent(_addedEvent);}else {console.error('THREE.Object3D.add: object not an instance of THREE.Object3D.',object);}return this;},remove:function remove(object){if(arguments.length>1){for(var _i13=0;_i13<arguments.length;_i13++){this.remove(arguments[_i13]);}return this;}var index=this.children.indexOf(object);if(index!==-1){object.parent=null;this.children.splice(index,1);object.dispatchEvent(_removedEvent);}return this;},clear:function clear(){for(var _i14=0;_i14<this.children.length;_i14++){var object=this.children[_i14];object.parent=null;object.dispatchEvent(_removedEvent);}this.children.length=0;return this;},attach:function attach(object){// adds object as a child of this, while maintaining the object's world transform
  2783. this.updateWorldMatrix(true,false);_m1$1.copy(this.matrixWorld).invert();if(object.parent!==null){object.parent.updateWorldMatrix(true,false);_m1$1.multiply(object.parent.matrixWorld);}object.applyMatrix4(_m1$1);object.updateWorldMatrix(false,false);this.add(object);return this;},getObjectById:function getObjectById(id){return this.getObjectByProperty('id',id);},getObjectByName:function getObjectByName(name){return this.getObjectByProperty('name',name);},getObjectByProperty:function getObjectByProperty(name,value){if(this[name]===value)return this;for(var _i15=0,l=this.children.length;_i15<l;_i15++){var child=this.children[_i15];var object=child.getObjectByProperty(name,value);if(object!==undefined){return object;}}return undefined;},getWorldPosition:function getWorldPosition(target){if(target===undefined){console.warn('THREE.Object3D: .getWorldPosition() target is now required');target=new Vector3();}this.updateWorldMatrix(true,false);return target.setFromMatrixPosition(this.matrixWorld);},getWorldQuaternion:function getWorldQuaternion(target){if(target===undefined){console.warn('THREE.Object3D: .getWorldQuaternion() target is now required');target=new Quaternion();}this.updateWorldMatrix(true,false);this.matrixWorld.decompose(_position,target,_scale);return target;},getWorldScale:function getWorldScale(target){if(target===undefined){console.warn('THREE.Object3D: .getWorldScale() target is now required');target=new Vector3();}this.updateWorldMatrix(true,false);this.matrixWorld.decompose(_position,_quaternion$2,target);return target;},getWorldDirection:function getWorldDirection(target){if(target===undefined){console.warn('THREE.Object3D: .getWorldDirection() target is now required');target=new Vector3();}this.updateWorldMatrix(true,false);var e=this.matrixWorld.elements;return target.set(e[8],e[9],e[10]).normalize();},raycast:function raycast(){},traverse:function traverse(callback){callback(this);var children=this.children;for(var _i16=0,l=children.length;_i16<l;_i16++){children[_i16].traverse(callback);}},traverseVisible:function traverseVisible(callback){if(this.visible===false)return;callback(this);var children=this.children;for(var _i17=0,l=children.length;_i17<l;_i17++){children[_i17].traverseVisible(callback);}},traverseAncestors:function traverseAncestors(callback){var parent=this.parent;if(parent!==null){callback(parent);parent.traverseAncestors(callback);}},updateMatrix:function updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);this.matrixWorldNeedsUpdate=true;},updateMatrixWorld:function updateMatrixWorld(force){if(this.matrixAutoUpdate)this.updateMatrix();if(this.matrixWorldNeedsUpdate||force){if(this.parent===null){this.matrixWorld.copy(this.matrix);}else {this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);}this.matrixWorldNeedsUpdate=false;force=true;}// update children
  2784. var children=this.children;for(var _i18=0,l=children.length;_i18<l;_i18++){children[_i18].updateMatrixWorld(force);}},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){var parent=this.parent;if(updateParents===true&&parent!==null){parent.updateWorldMatrix(true,false);}if(this.matrixAutoUpdate)this.updateMatrix();if(this.parent===null){this.matrixWorld.copy(this.matrix);}else {this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix);}// update children
  2785. if(updateChildren===true){var children=this.children;for(var _i19=0,l=children.length;_i19<l;_i19++){children[_i19].updateWorldMatrix(false,true);}}},toJSON:function toJSON(meta){// meta is a string when called from JSON.stringify
  2786. var isRootObject=meta===undefined||typeof meta==='string';var output={};// meta is a hash used to collect geometries, materials.
  2787. // not providing it implies that this is the root object
  2788. // being serialized.
  2789. if(isRootObject){// initialize meta obj
  2790. meta={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{}};output.metadata={version:4.5,type:'Object',generator:'Object3D.toJSON'};}// standard Object3D serialization
  2791. var object={};object.uuid=this.uuid;object.type=this.type;if(this.name!=='')object.name=this.name;if(this.castShadow===true)object.castShadow=true;if(this.receiveShadow===true)object.receiveShadow=true;if(this.visible===false)object.visible=false;if(this.frustumCulled===false)object.frustumCulled=false;if(this.renderOrder!==0)object.renderOrder=this.renderOrder;if(JSON.stringify(this.userData)!=='{}')object.userData=this.userData;object.layers=this.layers.mask;object.matrix=this.matrix.toArray();if(this.matrixAutoUpdate===false)object.matrixAutoUpdate=false;// object specific properties
  2792. if(this.isInstancedMesh){object.type='InstancedMesh';object.count=this.count;object.instanceMatrix=this.instanceMatrix.toJSON();}//
  2793. function serialize(library,element){if(library[element.uuid]===undefined){library[element.uuid]=element.toJSON(meta);}return element.uuid;}if(this.isMesh||this.isLine||this.isPoints){object.geometry=serialize(meta.geometries,this.geometry);var parameters=this.geometry.parameters;if(parameters!==undefined&&parameters.shapes!==undefined){var shapes=parameters.shapes;if(Array.isArray(shapes)){for(var _i20=0,l=shapes.length;_i20<l;_i20++){var shape=shapes[_i20];serialize(meta.shapes,shape);}}else {serialize(meta.shapes,shapes);}}}if(this.isSkinnedMesh){object.bindMode=this.bindMode;object.bindMatrix=this.bindMatrix.toArray();if(this.skeleton!==undefined){serialize(meta.skeletons,this.skeleton);object.skeleton=this.skeleton.uuid;}}if(this.material!==undefined){if(Array.isArray(this.material)){var uuids=[];for(var _i21=0,_l=this.material.length;_i21<_l;_i21++){uuids.push(serialize(meta.materials,this.material[_i21]));}object.material=uuids;}else {object.material=serialize(meta.materials,this.material);}}//
  2794. if(this.children.length>0){object.children=[];for(var _i22=0;_i22<this.children.length;_i22++){object.children.push(this.children[_i22].toJSON(meta).object);}}//
  2795. if(this.animations.length>0){object.animations=[];for(var _i23=0;_i23<this.animations.length;_i23++){var animation=this.animations[_i23];object.animations.push(serialize(meta.animations,animation));}}if(isRootObject){var geometries=extractFromCache(meta.geometries);var materials=extractFromCache(meta.materials);var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);var _shapes=extractFromCache(meta.shapes);var skeletons=extractFromCache(meta.skeletons);var animations=extractFromCache(meta.animations);if(geometries.length>0)output.geometries=geometries;if(materials.length>0)output.materials=materials;if(textures.length>0)output.textures=textures;if(images.length>0)output.images=images;if(_shapes.length>0)output.shapes=_shapes;if(skeletons.length>0)output.skeletons=skeletons;if(animations.length>0)output.animations=animations;}output.object=object;return output;// extract data from the cache hash
  2796. // remove metadata on each item
  2797. // and return as array
  2798. function extractFromCache(cache){var values=[];for(var key in cache){var data=cache[key];delete data.metadata;values.push(data);}return values;}},clone:function clone(recursive){return new this.constructor().copy(this,recursive);},copy:function copy(source){var recursive=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;this.name=source.name;this.up.copy(source.up);this.position.copy(source.position);this.rotation.order=source.rotation.order;this.quaternion.copy(source.quaternion);this.scale.copy(source.scale);this.matrix.copy(source.matrix);this.matrixWorld.copy(source.matrixWorld);this.matrixAutoUpdate=source.matrixAutoUpdate;this.matrixWorldNeedsUpdate=source.matrixWorldNeedsUpdate;this.layers.mask=source.layers.mask;this.visible=source.visible;this.castShadow=source.castShadow;this.receiveShadow=source.receiveShadow;this.frustumCulled=source.frustumCulled;this.renderOrder=source.renderOrder;this.userData=JSON.parse(JSON.stringify(source.userData));if(recursive===true){for(var _i24=0;_i24<source.children.length;_i24++){var child=source.children[_i24];this.add(child.clone());}}return this;}});var _vector1=/*@__PURE__*/new Vector3();var _vector2=/*@__PURE__*/new Vector3();var _normalMatrix=/*@__PURE__*/new Matrix3();class Plane{constructor(normal,constant){Object.defineProperty(this,'isPlane',{value:true});// normal is assumed to be normalized
  2799. this.normal=normal!==undefined?normal:new Vector3(1,0,0);this.constant=constant!==undefined?constant:0;}set(normal,constant){this.normal.copy(normal);this.constant=constant;return this;}setComponents(x,y,z,w){this.normal.set(x,y,z);this.constant=w;return this;}setFromNormalAndCoplanarPoint(normal,point){this.normal.copy(normal);this.constant=-point.dot(this.normal);return this;}setFromCoplanarPoints(a,b,c){var normal=_vector1.subVectors(c,b).cross(_vector2.subVectors(a,b)).normalize();// Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2800. this.setFromNormalAndCoplanarPoint(normal,a);return this;}clone(){return new this.constructor().copy(this);}copy(plane){this.normal.copy(plane.normal);this.constant=plane.constant;return this;}normalize(){// Note: will lead to a divide by zero if the plane is invalid.
  2801. var inverseNormalLength=1.0/this.normal.length();this.normal.multiplyScalar(inverseNormalLength);this.constant*=inverseNormalLength;return this;}negate(){this.constant*=-1;this.normal.negate();return this;}distanceToPoint(point){return this.normal.dot(point)+this.constant;}distanceToSphere(sphere){return this.distanceToPoint(sphere.center)-sphere.radius;}projectPoint(point,target){if(target===undefined){console.warn('THREE.Plane: .projectPoint() target is now required');target=new Vector3();}return target.copy(this.normal).multiplyScalar(-this.distanceToPoint(point)).add(point);}intersectLine(line,target){if(target===undefined){console.warn('THREE.Plane: .intersectLine() target is now required');target=new Vector3();}var direction=line.delta(_vector1);var denominator=this.normal.dot(direction);if(denominator===0){// line is coplanar, return origin
  2802. if(this.distanceToPoint(line.start)===0){return target.copy(line.start);}// Unsure if this is the correct method to handle this case.
  2803. return undefined;}var t=-(line.start.dot(this.normal)+this.constant)/denominator;if(t<0||t>1){return undefined;}return target.copy(direction).multiplyScalar(t).add(line.start);}intersectsLine(line){// Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2804. var startSign=this.distanceToPoint(line.start);var endSign=this.distanceToPoint(line.end);return startSign<0&&endSign>0||endSign<0&&startSign>0;}intersectsBox(box){return box.intersectsPlane(this);}intersectsSphere(sphere){return sphere.intersectsPlane(this);}coplanarPoint(target){if(target===undefined){console.warn('THREE.Plane: .coplanarPoint() target is now required');target=new Vector3();}return target.copy(this.normal).multiplyScalar(-this.constant);}applyMatrix4(matrix,optionalNormalMatrix){var normalMatrix=optionalNormalMatrix||_normalMatrix.getNormalMatrix(matrix);var referencePoint=this.coplanarPoint(_vector1).applyMatrix4(matrix);var normal=this.normal.applyMatrix3(normalMatrix).normalize();this.constant=-referencePoint.dot(normal);return this;}translate(offset){this.constant-=offset.dot(this.normal);return this;}equals(plane){return plane.normal.equals(this.normal)&&plane.constant===this.constant;}}var _v0$1=/*@__PURE__*/new Vector3();var _v1$3=/*@__PURE__*/new Vector3();var _v2$1=/*@__PURE__*/new Vector3();var _v3=/*@__PURE__*/new Vector3();var _vab=/*@__PURE__*/new Vector3();var _vac=/*@__PURE__*/new Vector3();var _vbc=/*@__PURE__*/new Vector3();var _vap=/*@__PURE__*/new Vector3();var _vbp=/*@__PURE__*/new Vector3();var _vcp=/*@__PURE__*/new Vector3();class Triangle{constructor(a,b,c){this.a=a!==undefined?a:new Vector3();this.b=b!==undefined?b:new Vector3();this.c=c!==undefined?c:new Vector3();}static getNormal(a,b,c,target){if(target===undefined){console.warn('THREE.Triangle: .getNormal() target is now required');target=new Vector3();}target.subVectors(c,b);_v0$1.subVectors(a,b);target.cross(_v0$1);var targetLengthSq=target.lengthSq();if(targetLengthSq>0){return target.multiplyScalar(1/Math.sqrt(targetLengthSq));}return target.set(0,0,0);}// static/instance method to calculate barycentric coordinates
  2805. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  2806. static getBarycoord(point,a,b,c,target){_v0$1.subVectors(c,a);_v1$3.subVectors(b,a);_v2$1.subVectors(point,a);var dot00=_v0$1.dot(_v0$1);var dot01=_v0$1.dot(_v1$3);var dot02=_v0$1.dot(_v2$1);var dot11=_v1$3.dot(_v1$3);var dot12=_v1$3.dot(_v2$1);var denom=dot00*dot11-dot01*dot01;if(target===undefined){console.warn('THREE.Triangle: .getBarycoord() target is now required');target=new Vector3();}// collinear or singular triangle
  2807. if(denom===0){// arbitrary location outside of triangle?
  2808. // not sure if this is the best idea, maybe should be returning undefined
  2809. return target.set(-2,-1,-1);}var invDenom=1/denom;var u=(dot11*dot02-dot01*dot12)*invDenom;var v=(dot00*dot12-dot01*dot02)*invDenom;// barycentric coordinates must always sum to 1
  2810. return target.set(1-u-v,v,u);}static containsPoint(point,a,b,c){this.getBarycoord(point,a,b,c,_v3);return _v3.x>=0&&_v3.y>=0&&_v3.x+_v3.y<=1;}static getUV(point,p1,p2,p3,uv1,uv2,uv3,target){this.getBarycoord(point,p1,p2,p3,_v3);target.set(0,0);target.addScaledVector(uv1,_v3.x);target.addScaledVector(uv2,_v3.y);target.addScaledVector(uv3,_v3.z);return target;}static isFrontFacing(a,b,c,direction){_v0$1.subVectors(c,b);_v1$3.subVectors(a,b);// strictly front facing
  2811. return _v0$1.cross(_v1$3).dot(direction)<0?true:false;}set(a,b,c){this.a.copy(a);this.b.copy(b);this.c.copy(c);return this;}setFromPointsAndIndices(points,i0,i1,i2){this.a.copy(points[i0]);this.b.copy(points[i1]);this.c.copy(points[i2]);return this;}clone(){return new this.constructor().copy(this);}copy(triangle){this.a.copy(triangle.a);this.b.copy(triangle.b);this.c.copy(triangle.c);return this;}getArea(){_v0$1.subVectors(this.c,this.b);_v1$3.subVectors(this.a,this.b);return _v0$1.cross(_v1$3).length()*0.5;}getMidpoint(target){if(target===undefined){console.warn('THREE.Triangle: .getMidpoint() target is now required');target=new Vector3();}return target.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3);}getNormal(target){return Triangle.getNormal(this.a,this.b,this.c,target);}getPlane(target){if(target===undefined){console.warn('THREE.Triangle: .getPlane() target is now required');target=new Plane();}return target.setFromCoplanarPoints(this.a,this.b,this.c);}getBarycoord(point,target){return Triangle.getBarycoord(point,this.a,this.b,this.c,target);}getUV(point,uv1,uv2,uv3,target){return Triangle.getUV(point,this.a,this.b,this.c,uv1,uv2,uv3,target);}containsPoint(point){return Triangle.containsPoint(point,this.a,this.b,this.c);}isFrontFacing(direction){return Triangle.isFrontFacing(this.a,this.b,this.c,direction);}intersectsBox(box){return box.intersectsTriangle(this);}closestPointToPoint(p,target){if(target===undefined){console.warn('THREE.Triangle: .closestPointToPoint() target is now required');target=new Vector3();}var a=this.a,b=this.b,c=this.c;var v,w;// algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  2812. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  2813. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  2814. // basically, we're distinguishing which of the voronoi regions of the triangle
  2815. // the point lies in with the minimum amount of redundant computation.
  2816. _vab.subVectors(b,a);_vac.subVectors(c,a);_vap.subVectors(p,a);var d1=_vab.dot(_vap);var d2=_vac.dot(_vap);if(d1<=0&&d2<=0){// vertex region of A; barycentric coords (1, 0, 0)
  2817. return target.copy(a);}_vbp.subVectors(p,b);var d3=_vab.dot(_vbp);var d4=_vac.dot(_vbp);if(d3>=0&&d4<=d3){// vertex region of B; barycentric coords (0, 1, 0)
  2818. return target.copy(b);}var vc=d1*d4-d3*d2;if(vc<=0&&d1>=0&&d3<=0){v=d1/(d1-d3);// edge region of AB; barycentric coords (1-v, v, 0)
  2819. return target.copy(a).addScaledVector(_vab,v);}_vcp.subVectors(p,c);var d5=_vab.dot(_vcp);var d6=_vac.dot(_vcp);if(d6>=0&&d5<=d6){// vertex region of C; barycentric coords (0, 0, 1)
  2820. return target.copy(c);}var vb=d5*d2-d1*d6;if(vb<=0&&d2>=0&&d6<=0){w=d2/(d2-d6);// edge region of AC; barycentric coords (1-w, 0, w)
  2821. return target.copy(a).addScaledVector(_vac,w);}var va=d3*d6-d5*d4;if(va<=0&&d4-d3>=0&&d5-d6>=0){_vbc.subVectors(c,b);w=(d4-d3)/(d4-d3+(d5-d6));// edge region of BC; barycentric coords (0, 1-w, w)
  2822. return target.copy(b).addScaledVector(_vbc,w);// edge region of BC
  2823. }// face region
  2824. var denom=1/(va+vb+vc);// u = va * denom
  2825. v=vb*denom;w=vc*denom;return target.copy(a).addScaledVector(_vab,v).addScaledVector(_vac,w);}equals(triangle){return triangle.a.equals(this.a)&&triangle.b.equals(this.b)&&triangle.c.equals(this.c);}}var _colorKeywords={'aliceblue':0xF0F8FF,'antiquewhite':0xFAEBD7,'aqua':0x00FFFF,'aquamarine':0x7FFFD4,'azure':0xF0FFFF,'beige':0xF5F5DC,'bisque':0xFFE4C4,'black':0x000000,'blanchedalmond':0xFFEBCD,'blue':0x0000FF,'blueviolet':0x8A2BE2,'brown':0xA52A2A,'burlywood':0xDEB887,'cadetblue':0x5F9EA0,'chartreuse':0x7FFF00,'chocolate':0xD2691E,'coral':0xFF7F50,'cornflowerblue':0x6495ED,'cornsilk':0xFFF8DC,'crimson':0xDC143C,'cyan':0x00FFFF,'darkblue':0x00008B,'darkcyan':0x008B8B,'darkgoldenrod':0xB8860B,'darkgray':0xA9A9A9,'darkgreen':0x006400,'darkgrey':0xA9A9A9,'darkkhaki':0xBDB76B,'darkmagenta':0x8B008B,'darkolivegreen':0x556B2F,'darkorange':0xFF8C00,'darkorchid':0x9932CC,'darkred':0x8B0000,'darksalmon':0xE9967A,'darkseagreen':0x8FBC8F,'darkslateblue':0x483D8B,'darkslategray':0x2F4F4F,'darkslategrey':0x2F4F4F,'darkturquoise':0x00CED1,'darkviolet':0x9400D3,'deeppink':0xFF1493,'deepskyblue':0x00BFFF,'dimgray':0x696969,'dimgrey':0x696969,'dodgerblue':0x1E90FF,'firebrick':0xB22222,'floralwhite':0xFFFAF0,'forestgreen':0x228B22,'fuchsia':0xFF00FF,'gainsboro':0xDCDCDC,'ghostwhite':0xF8F8FF,'gold':0xFFD700,'goldenrod':0xDAA520,'gray':0x808080,'green':0x008000,'greenyellow':0xADFF2F,'grey':0x808080,'honeydew':0xF0FFF0,'hotpink':0xFF69B4,'indianred':0xCD5C5C,'indigo':0x4B0082,'ivory':0xFFFFF0,'khaki':0xF0E68C,'lavender':0xE6E6FA,'lavenderblush':0xFFF0F5,'lawngreen':0x7CFC00,'lemonchiffon':0xFFFACD,'lightblue':0xADD8E6,'lightcoral':0xF08080,'lightcyan':0xE0FFFF,'lightgoldenrodyellow':0xFAFAD2,'lightgray':0xD3D3D3,'lightgreen':0x90EE90,'lightgrey':0xD3D3D3,'lightpink':0xFFB6C1,'lightsalmon':0xFFA07A,'lightseagreen':0x20B2AA,'lightskyblue':0x87CEFA,'lightslategray':0x778899,'lightslategrey':0x778899,'lightsteelblue':0xB0C4DE,'lightyellow':0xFFFFE0,'lime':0x00FF00,'limegreen':0x32CD32,'linen':0xFAF0E6,'magenta':0xFF00FF,'maroon':0x800000,'mediumaquamarine':0x66CDAA,'mediumblue':0x0000CD,'mediumorchid':0xBA55D3,'mediumpurple':0x9370DB,'mediumseagreen':0x3CB371,'mediumslateblue':0x7B68EE,'mediumspringgreen':0x00FA9A,'mediumturquoise':0x48D1CC,'mediumvioletred':0xC71585,'midnightblue':0x191970,'mintcream':0xF5FFFA,'mistyrose':0xFFE4E1,'moccasin':0xFFE4B5,'navajowhite':0xFFDEAD,'navy':0x000080,'oldlace':0xFDF5E6,'olive':0x808000,'olivedrab':0x6B8E23,'orange':0xFFA500,'orangered':0xFF4500,'orchid':0xDA70D6,'palegoldenrod':0xEEE8AA,'palegreen':0x98FB98,'paleturquoise':0xAFEEEE,'palevioletred':0xDB7093,'papayawhip':0xFFEFD5,'peachpuff':0xFFDAB9,'peru':0xCD853F,'pink':0xFFC0CB,'plum':0xDDA0DD,'powderblue':0xB0E0E6,'purple':0x800080,'rebeccapurple':0x663399,'red':0xFF0000,'rosybrown':0xBC8F8F,'royalblue':0x4169E1,'saddlebrown':0x8B4513,'salmon':0xFA8072,'sandybrown':0xF4A460,'seagreen':0x2E8B57,'seashell':0xFFF5EE,'sienna':0xA0522D,'silver':0xC0C0C0,'skyblue':0x87CEEB,'slateblue':0x6A5ACD,'slategray':0x708090,'slategrey':0x708090,'snow':0xFFFAFA,'springgreen':0x00FF7F,'steelblue':0x4682B4,'tan':0xD2B48C,'teal':0x008080,'thistle':0xD8BFD8,'tomato':0xFF6347,'turquoise':0x40E0D0,'violet':0xEE82EE,'wheat':0xF5DEB3,'white':0xFFFFFF,'whitesmoke':0xF5F5F5,'yellow':0xFFFF00,'yellowgreen':0x9ACD32};var _hslA={h:0,s:0,l:0};var _hslB={h:0,s:0,l:0};function hue2rgb(p,q,t){if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*6*(2/3-t);return p;}function SRGBToLinear(c){return c<0.04045?c*0.0773993808:Math.pow(c*0.9478672986+0.0521327014,2.4);}function LinearToSRGB(c){return c<0.0031308?c*12.92:1.055*Math.pow(c,0.41666)-0.055;}class Color{constructor(r,g,b){Object.defineProperty(this,'isColor',{value:true});if(g===undefined&&b===undefined){// r is THREE.Color, hex or string
  2826. return this.set(r);}return this.setRGB(r,g,b);}set(value){if(value&&value.isColor){this.copy(value);}else if(typeof value==='number'){this.setHex(value);}else if(typeof value==='string'){this.setStyle(value);}return this;}setScalar(scalar){this.r=scalar;this.g=scalar;this.b=scalar;return this;}setHex(hex){hex=Math.floor(hex);this.r=(hex>>16&255)/255;this.g=(hex>>8&255)/255;this.b=(hex&255)/255;return this;}setRGB(r,g,b){this.r=r;this.g=g;this.b=b;return this;}setHSL(h,s,l){// h,s,l ranges are in 0.0 - 1.0
  2827. h=MathUtils.euclideanModulo(h,1);s=MathUtils.clamp(s,0,1);l=MathUtils.clamp(l,0,1);if(s===0){this.r=this.g=this.b=l;}else {var p=l<=0.5?l*(1+s):l+s-l*s;var q=2*l-p;this.r=hue2rgb(q,p,h+1/3);this.g=hue2rgb(q,p,h);this.b=hue2rgb(q,p,h-1/3);}return this;}setStyle(style){function handleAlpha(string){if(string===undefined)return;if(parseFloat(string)<1){console.warn('THREE.Color: Alpha component of '+style+' will be ignored.');}}var m;if(m=/^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec(style)){// rgb / hsl
  2828. var color;var name=m[1];var components=m[2];switch(name){case'rgb':case'rgba':if(color=/^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){// rgb(255,0,0) rgba(255,0,0,0.5)
  2829. this.r=Math.min(255,parseInt(color[1],10))/255;this.g=Math.min(255,parseInt(color[2],10))/255;this.b=Math.min(255,parseInt(color[3],10))/255;handleAlpha(color[4]);return this;}if(color=/^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){// rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  2830. this.r=Math.min(100,parseInt(color[1],10))/100;this.g=Math.min(100,parseInt(color[2],10))/100;this.b=Math.min(100,parseInt(color[3],10))/100;handleAlpha(color[4]);return this;}break;case'hsl':case'hsla':if(color=/^(\d*\.?\d+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(components)){// hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  2831. var h=parseFloat(color[1])/360;var s=parseInt(color[2],10)/100;var l=parseInt(color[3],10)/100;handleAlpha(color[4]);return this.setHSL(h,s,l);}break;}}else if(m=/^\#([A-Fa-f\d]+)$/.exec(style)){// hex color
  2832. var hex=m[1];var size=hex.length;if(size===3){// #ff0
  2833. this.r=parseInt(hex.charAt(0)+hex.charAt(0),16)/255;this.g=parseInt(hex.charAt(1)+hex.charAt(1),16)/255;this.b=parseInt(hex.charAt(2)+hex.charAt(2),16)/255;return this;}else if(size===6){// #ff0000
  2834. this.r=parseInt(hex.charAt(0)+hex.charAt(1),16)/255;this.g=parseInt(hex.charAt(2)+hex.charAt(3),16)/255;this.b=parseInt(hex.charAt(4)+hex.charAt(5),16)/255;return this;}}if(style&&style.length>0){return this.setColorName(style);}return this;}setColorName(style){// color keywords
  2835. var hex=_colorKeywords[style];if(hex!==undefined){// red
  2836. this.setHex(hex);}else {// unknown color
  2837. console.warn('THREE.Color: Unknown color '+style);}return this;}clone(){return new this.constructor(this.r,this.g,this.b);}copy(color){this.r=color.r;this.g=color.g;this.b=color.b;return this;}copyGammaToLinear(color){var gammaFactor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2.0;this.r=Math.pow(color.r,gammaFactor);this.g=Math.pow(color.g,gammaFactor);this.b=Math.pow(color.b,gammaFactor);return this;}copyLinearToGamma(color){var gammaFactor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2.0;var safeInverse=gammaFactor>0?1.0/gammaFactor:1.0;this.r=Math.pow(color.r,safeInverse);this.g=Math.pow(color.g,safeInverse);this.b=Math.pow(color.b,safeInverse);return this;}convertGammaToLinear(gammaFactor){this.copyGammaToLinear(this,gammaFactor);return this;}convertLinearToGamma(gammaFactor){this.copyLinearToGamma(this,gammaFactor);return this;}copySRGBToLinear(color){this.r=SRGBToLinear(color.r);this.g=SRGBToLinear(color.g);this.b=SRGBToLinear(color.b);return this;}copyLinearToSRGB(color){this.r=LinearToSRGB(color.r);this.g=LinearToSRGB(color.g);this.b=LinearToSRGB(color.b);return this;}convertSRGBToLinear(){this.copySRGBToLinear(this);return this;}convertLinearToSRGB(){this.copyLinearToSRGB(this);return this;}getHex(){return this.r*255<<16^this.g*255<<8^this.b*255<<0;}getHexString(){return ('000000'+this.getHex().toString(16)).slice(-6);}getHSL(target){// h,s,l ranges are in 0.0 - 1.0
  2838. if(target===undefined){console.warn('THREE.Color: .getHSL() target is now required');target={h:0,s:0,l:0};}var r=this.r,g=this.g,b=this.b;var max=Math.max(r,g,b);var min=Math.min(r,g,b);var hue,saturation;var lightness=(min+max)/2.0;if(min===max){hue=0;saturation=0;}else {var delta=max-min;saturation=lightness<=0.5?delta/(max+min):delta/(2-max-min);switch(max){case r:hue=(g-b)/delta+(g<b?6:0);break;case g:hue=(b-r)/delta+2;break;case b:hue=(r-g)/delta+4;break;}hue/=6;}target.h=hue;target.s=saturation;target.l=lightness;return target;}getStyle(){return 'rgb('+(this.r*255|0)+','+(this.g*255|0)+','+(this.b*255|0)+')';}offsetHSL(h,s,l){this.getHSL(_hslA);_hslA.h+=h;_hslA.s+=s;_hslA.l+=l;this.setHSL(_hslA.h,_hslA.s,_hslA.l);return this;}add(color){this.r+=color.r;this.g+=color.g;this.b+=color.b;return this;}addColors(color1,color2){this.r=color1.r+color2.r;this.g=color1.g+color2.g;this.b=color1.b+color2.b;return this;}addScalar(s){this.r+=s;this.g+=s;this.b+=s;return this;}sub(color){this.r=Math.max(0,this.r-color.r);this.g=Math.max(0,this.g-color.g);this.b=Math.max(0,this.b-color.b);return this;}multiply(color){this.r*=color.r;this.g*=color.g;this.b*=color.b;return this;}multiplyScalar(s){this.r*=s;this.g*=s;this.b*=s;return this;}lerp(color,alpha){this.r+=(color.r-this.r)*alpha;this.g+=(color.g-this.g)*alpha;this.b+=(color.b-this.b)*alpha;return this;}lerpHSL(color,alpha){this.getHSL(_hslA);color.getHSL(_hslB);var h=MathUtils.lerp(_hslA.h,_hslB.h,alpha);var s=MathUtils.lerp(_hslA.s,_hslB.s,alpha);var l=MathUtils.lerp(_hslA.l,_hslB.l,alpha);this.setHSL(h,s,l);return this;}equals(c){return c.r===this.r&&c.g===this.g&&c.b===this.b;}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.r=array[offset];this.g=array[offset+1];this.b=array[offset+2];return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;array[offset]=this.r;array[offset+1]=this.g;array[offset+2]=this.b;return array;}fromBufferAttribute(attribute,index){this.r=attribute.getX(index);this.g=attribute.getY(index);this.b=attribute.getZ(index);if(attribute.normalized===true){// assuming Uint8Array
  2839. this.r/=255;this.g/=255;this.b/=255;}return this;}toJSON(){return this.getHex();}}Color.NAMES=_colorKeywords;Color.prototype.r=1;Color.prototype.g=1;Color.prototype.b=1;class Face3{constructor(a,b,c,normal,color){var materialIndex=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;this.a=a;this.b=b;this.c=c;this.normal=normal&&normal.isVector3?normal:new Vector3();this.vertexNormals=Array.isArray(normal)?normal:[];this.color=color&&color.isColor?color:new Color();this.vertexColors=Array.isArray(color)?color:[];this.materialIndex=materialIndex;}clone(){return new this.constructor().copy(this);}copy(source){this.a=source.a;this.b=source.b;this.c=source.c;this.normal.copy(source.normal);this.color.copy(source.color);this.materialIndex=source.materialIndex;for(var _i25=0,il=source.vertexNormals.length;_i25<il;_i25++){this.vertexNormals[_i25]=source.vertexNormals[_i25].clone();}for(var _i26=0,_il=source.vertexColors.length;_i26<_il;_i26++){this.vertexColors[_i26]=source.vertexColors[_i26].clone();}return this;}}var materialId=0;function Material(){Object.defineProperty(this,'id',{value:materialId++});this.uuid=MathUtils.generateUUID();this.name='';this.type='Material';this.fog=true;this.blending=NormalBlending;this.side=FrontSide;this.flatShading=false;this.vertexColors=false;this.opacity=1;this.transparent=false;this.blendSrc=SrcAlphaFactor;this.blendDst=OneMinusSrcAlphaFactor;this.blendEquation=AddEquation;this.blendSrcAlpha=null;this.blendDstAlpha=null;this.blendEquationAlpha=null;this.depthFunc=LessEqualDepth;this.depthTest=true;this.depthWrite=true;this.stencilWriteMask=0xff;this.stencilFunc=AlwaysStencilFunc;this.stencilRef=0;this.stencilFuncMask=0xff;this.stencilFail=KeepStencilOp;this.stencilZFail=KeepStencilOp;this.stencilZPass=KeepStencilOp;this.stencilWrite=false;this.clippingPlanes=null;this.clipIntersection=false;this.clipShadows=false;this.shadowSide=null;this.colorWrite=true;this.precision=null;// override the renderer's default precision for this material
  2840. this.polygonOffset=false;this.polygonOffsetFactor=0;this.polygonOffsetUnits=0;this.dithering=false;this.alphaTest=0;this.premultipliedAlpha=false;this.visible=true;this.toneMapped=true;this.userData={};this.version=0;}Material.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Material,isMaterial:true,onBeforeCompile:function onBeforeCompile(/* shaderobject, renderer */){},customProgramCacheKey:function customProgramCacheKey(){return this.onBeforeCompile.toString();},setValues:function setValues(values){if(values===undefined)return;for(var key in values){var newValue=values[key];if(newValue===undefined){console.warn('THREE.Material: \''+key+'\' parameter is undefined.');continue;}// for backward compatability if shading is set in the constructor
  2841. if(key==='shading'){console.warn('THREE.'+this.type+': .shading has been removed. Use the boolean .flatShading instead.');this.flatShading=newValue===FlatShading$1?true:false;continue;}var currentValue=this[key];if(currentValue===undefined){//console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  2842. continue;}if(currentValue&&currentValue.isColor){currentValue.set(newValue);}else if(currentValue&&currentValue.isVector3&&newValue&&newValue.isVector3){currentValue.copy(newValue);}else {this[key]=newValue;}}},toJSON:function toJSON(meta){var isRoot=meta===undefined||typeof meta==='string';if(isRoot){meta={textures:{},images:{}};}var data={metadata:{version:4.5,type:'Material',generator:'Material.toJSON'}};// standard Material serialization
  2843. data.uuid=this.uuid;data.type=this.type;if(this.name!=='')data.name=this.name;if(this.color&&this.color.isColor)data.color=this.color.getHex();if(this.roughness!==undefined)data.roughness=this.roughness;if(this.metalness!==undefined)data.metalness=this.metalness;if(this.sheen&&this.sheen.isColor)data.sheen=this.sheen.getHex();if(this.emissive&&this.emissive.isColor)data.emissive=this.emissive.getHex();if(this.emissiveIntensity&&this.emissiveIntensity!==1)data.emissiveIntensity=this.emissiveIntensity;if(this.specular&&this.specular.isColor)data.specular=this.specular.getHex();if(this.shininess!==undefined)data.shininess=this.shininess;if(this.clearcoat!==undefined)data.clearcoat=this.clearcoat;if(this.clearcoatRoughness!==undefined)data.clearcoatRoughness=this.clearcoatRoughness;if(this.clearcoatMap&&this.clearcoatMap.isTexture){data.clearcoatMap=this.clearcoatMap.toJSON(meta).uuid;}if(this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture){data.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(meta).uuid;}if(this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture){data.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(meta).uuid;data.clearcoatNormalScale=this.clearcoatNormalScale.toArray();}if(this.map&&this.map.isTexture)data.map=this.map.toJSON(meta).uuid;if(this.matcap&&this.matcap.isTexture)data.matcap=this.matcap.toJSON(meta).uuid;if(this.alphaMap&&this.alphaMap.isTexture)data.alphaMap=this.alphaMap.toJSON(meta).uuid;if(this.lightMap&&this.lightMap.isTexture)data.lightMap=this.lightMap.toJSON(meta).uuid;if(this.aoMap&&this.aoMap.isTexture){data.aoMap=this.aoMap.toJSON(meta).uuid;data.aoMapIntensity=this.aoMapIntensity;}if(this.bumpMap&&this.bumpMap.isTexture){data.bumpMap=this.bumpMap.toJSON(meta).uuid;data.bumpScale=this.bumpScale;}if(this.normalMap&&this.normalMap.isTexture){data.normalMap=this.normalMap.toJSON(meta).uuid;data.normalMapType=this.normalMapType;data.normalScale=this.normalScale.toArray();}if(this.displacementMap&&this.displacementMap.isTexture){data.displacementMap=this.displacementMap.toJSON(meta).uuid;data.displacementScale=this.displacementScale;data.displacementBias=this.displacementBias;}if(this.roughnessMap&&this.roughnessMap.isTexture)data.roughnessMap=this.roughnessMap.toJSON(meta).uuid;if(this.metalnessMap&&this.metalnessMap.isTexture)data.metalnessMap=this.metalnessMap.toJSON(meta).uuid;if(this.emissiveMap&&this.emissiveMap.isTexture)data.emissiveMap=this.emissiveMap.toJSON(meta).uuid;if(this.specularMap&&this.specularMap.isTexture)data.specularMap=this.specularMap.toJSON(meta).uuid;if(this.envMap&&this.envMap.isTexture){data.envMap=this.envMap.toJSON(meta).uuid;data.reflectivity=this.reflectivity;// Scale behind envMap
  2844. data.refractionRatio=this.refractionRatio;if(this.combine!==undefined)data.combine=this.combine;if(this.envMapIntensity!==undefined)data.envMapIntensity=this.envMapIntensity;}if(this.gradientMap&&this.gradientMap.isTexture){data.gradientMap=this.gradientMap.toJSON(meta).uuid;}if(this.size!==undefined)data.size=this.size;if(this.sizeAttenuation!==undefined)data.sizeAttenuation=this.sizeAttenuation;if(this.blending!==NormalBlending)data.blending=this.blending;if(this.flatShading===true)data.flatShading=this.flatShading;if(this.side!==FrontSide)data.side=this.side;if(this.vertexColors)data.vertexColors=true;if(this.opacity<1)data.opacity=this.opacity;if(this.transparent===true)data.transparent=this.transparent;data.depthFunc=this.depthFunc;data.depthTest=this.depthTest;data.depthWrite=this.depthWrite;data.stencilWrite=this.stencilWrite;data.stencilWriteMask=this.stencilWriteMask;data.stencilFunc=this.stencilFunc;data.stencilRef=this.stencilRef;data.stencilFuncMask=this.stencilFuncMask;data.stencilFail=this.stencilFail;data.stencilZFail=this.stencilZFail;data.stencilZPass=this.stencilZPass;// rotation (SpriteMaterial)
  2845. if(this.rotation&&this.rotation!==0)data.rotation=this.rotation;if(this.polygonOffset===true)data.polygonOffset=true;if(this.polygonOffsetFactor!==0)data.polygonOffsetFactor=this.polygonOffsetFactor;if(this.polygonOffsetUnits!==0)data.polygonOffsetUnits=this.polygonOffsetUnits;if(this.linewidth&&this.linewidth!==1)data.linewidth=this.linewidth;if(this.dashSize!==undefined)data.dashSize=this.dashSize;if(this.gapSize!==undefined)data.gapSize=this.gapSize;if(this.scale!==undefined)data.scale=this.scale;if(this.dithering===true)data.dithering=true;if(this.alphaTest>0)data.alphaTest=this.alphaTest;if(this.premultipliedAlpha===true)data.premultipliedAlpha=this.premultipliedAlpha;if(this.wireframe===true)data.wireframe=this.wireframe;if(this.wireframeLinewidth>1)data.wireframeLinewidth=this.wireframeLinewidth;if(this.wireframeLinecap!=='round')data.wireframeLinecap=this.wireframeLinecap;if(this.wireframeLinejoin!=='round')data.wireframeLinejoin=this.wireframeLinejoin;if(this.morphTargets===true)data.morphTargets=true;if(this.morphNormals===true)data.morphNormals=true;if(this.skinning===true)data.skinning=true;if(this.visible===false)data.visible=false;if(this.toneMapped===false)data.toneMapped=false;if(JSON.stringify(this.userData)!=='{}')data.userData=this.userData;// TODO: Copied from Object3D.toJSON
  2846. function extractFromCache(cache){var values=[];for(var key in cache){var _data=cache[key];delete _data.metadata;values.push(_data);}return values;}if(isRoot){var textures=extractFromCache(meta.textures);var images=extractFromCache(meta.images);if(textures.length>0)data.textures=textures;if(images.length>0)data.images=images;}return data;},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.name=source.name;this.fog=source.fog;this.blending=source.blending;this.side=source.side;this.flatShading=source.flatShading;this.vertexColors=source.vertexColors;this.opacity=source.opacity;this.transparent=source.transparent;this.blendSrc=source.blendSrc;this.blendDst=source.blendDst;this.blendEquation=source.blendEquation;this.blendSrcAlpha=source.blendSrcAlpha;this.blendDstAlpha=source.blendDstAlpha;this.blendEquationAlpha=source.blendEquationAlpha;this.depthFunc=source.depthFunc;this.depthTest=source.depthTest;this.depthWrite=source.depthWrite;this.stencilWriteMask=source.stencilWriteMask;this.stencilFunc=source.stencilFunc;this.stencilRef=source.stencilRef;this.stencilFuncMask=source.stencilFuncMask;this.stencilFail=source.stencilFail;this.stencilZFail=source.stencilZFail;this.stencilZPass=source.stencilZPass;this.stencilWrite=source.stencilWrite;var srcPlanes=source.clippingPlanes;var dstPlanes=null;if(srcPlanes!==null){var n=srcPlanes.length;dstPlanes=new Array(n);for(var _i27=0;_i27!==n;++_i27){dstPlanes[_i27]=srcPlanes[_i27].clone();}}this.clippingPlanes=dstPlanes;this.clipIntersection=source.clipIntersection;this.clipShadows=source.clipShadows;this.shadowSide=source.shadowSide;this.colorWrite=source.colorWrite;this.precision=source.precision;this.polygonOffset=source.polygonOffset;this.polygonOffsetFactor=source.polygonOffsetFactor;this.polygonOffsetUnits=source.polygonOffsetUnits;this.dithering=source.dithering;this.alphaTest=source.alphaTest;this.premultipliedAlpha=source.premultipliedAlpha;this.visible=source.visible;this.toneMapped=source.toneMapped;this.userData=JSON.parse(JSON.stringify(source.userData));return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});Object.defineProperty(Material.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});/**
  2847. * parameters = {
  2848. * color: <hex>,
  2849. * opacity: <float>,
  2850. * map: new THREE.Texture( <Image> ),
  2851. *
  2852. * lightMap: new THREE.Texture( <Image> ),
  2853. * lightMapIntensity: <float>
  2854. *
  2855. * aoMap: new THREE.Texture( <Image> ),
  2856. * aoMapIntensity: <float>
  2857. *
  2858. * specularMap: new THREE.Texture( <Image> ),
  2859. *
  2860. * alphaMap: new THREE.Texture( <Image> ),
  2861. *
  2862. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  2863. * combine: THREE.Multiply,
  2864. * reflectivity: <float>,
  2865. * refractionRatio: <float>,
  2866. *
  2867. * depthTest: <bool>,
  2868. * depthWrite: <bool>,
  2869. *
  2870. * wireframe: <boolean>,
  2871. * wireframeLinewidth: <float>,
  2872. *
  2873. * skinning: <bool>,
  2874. * morphTargets: <bool>
  2875. * }
  2876. */function MeshBasicMaterial(parameters){Material.call(this);this.type='MeshBasicMaterial';this.color=new Color(0xffffff);// emissive
  2877. this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.setValues(parameters);}MeshBasicMaterial.prototype=Object.create(Material.prototype);MeshBasicMaterial.prototype.constructor=MeshBasicMaterial;MeshBasicMaterial.prototype.isMeshBasicMaterial=true;MeshBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;return this;};var _vector$3=new Vector3();var _vector2$1=new Vector2();function BufferAttribute(array,itemSize,normalized){if(Array.isArray(array)){throw new TypeError('THREE.BufferAttribute: array should be a Typed Array.');}this.name='';this.array=array;this.itemSize=itemSize;this.count=array!==undefined?array.length/itemSize:0;this.normalized=normalized===true;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;}Object.defineProperty(BufferAttribute.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(BufferAttribute.prototype,{isBufferAttribute:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.name=source.name;this.array=new source.array.constructor(source.array);this.itemSize=source.itemSize;this.count=source.count;this.normalized=source.normalized;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.itemSize;index2*=attribute.itemSize;for(var _i28=0,l=this.itemSize;_i28<l;_i28++){this.array[index1+_i28]=attribute.array[index2+_i28];}return this;},copyArray:function copyArray(array){this.array.set(array);return this;},copyColorsArray:function copyColorsArray(colors){var array=this.array;var offset=0;for(var _i29=0,l=colors.length;_i29<l;_i29++){var color=colors[_i29];if(color===undefined){console.warn('THREE.BufferAttribute.copyColorsArray(): color is undefined',_i29);color=new Color();}array[offset++]=color.r;array[offset++]=color.g;array[offset++]=color.b;}return this;},copyVector2sArray:function copyVector2sArray(vectors){var array=this.array;var offset=0;for(var _i30=0,l=vectors.length;_i30<l;_i30++){var vector=vectors[_i30];if(vector===undefined){console.warn('THREE.BufferAttribute.copyVector2sArray(): vector is undefined',_i30);vector=new Vector2();}array[offset++]=vector.x;array[offset++]=vector.y;}return this;},copyVector3sArray:function copyVector3sArray(vectors){var array=this.array;var offset=0;for(var _i31=0,l=vectors.length;_i31<l;_i31++){var vector=vectors[_i31];if(vector===undefined){console.warn('THREE.BufferAttribute.copyVector3sArray(): vector is undefined',_i31);vector=new Vector3();}array[offset++]=vector.x;array[offset++]=vector.y;array[offset++]=vector.z;}return this;},copyVector4sArray:function copyVector4sArray(vectors){var array=this.array;var offset=0;for(var _i32=0,l=vectors.length;_i32<l;_i32++){var vector=vectors[_i32];if(vector===undefined){console.warn('THREE.BufferAttribute.copyVector4sArray(): vector is undefined',_i32);vector=new Vector4();}array[offset++]=vector.x;array[offset++]=vector.y;array[offset++]=vector.z;array[offset++]=vector.w;}return this;},applyMatrix3:function applyMatrix3(m){if(this.itemSize===2){for(var _i33=0,l=this.count;_i33<l;_i33++){_vector2$1.fromBufferAttribute(this,_i33);_vector2$1.applyMatrix3(m);this.setXY(_i33,_vector2$1.x,_vector2$1.y);}}else if(this.itemSize===3){for(var _i34=0,_l2=this.count;_i34<_l2;_i34++){_vector$3.fromBufferAttribute(this,_i34);_vector$3.applyMatrix3(m);this.setXYZ(_i34,_vector$3.x,_vector$3.y,_vector$3.z);}}return this;},applyMatrix4:function applyMatrix4(m){for(var _i35=0,l=this.count;_i35<l;_i35++){_vector$3.x=this.getX(_i35);_vector$3.y=this.getY(_i35);_vector$3.z=this.getZ(_i35);_vector$3.applyMatrix4(m);this.setXYZ(_i35,_vector$3.x,_vector$3.y,_vector$3.z);}return this;},applyNormalMatrix:function applyNormalMatrix(m){for(var _i36=0,l=this.count;_i36<l;_i36++){_vector$3.x=this.getX(_i36);_vector$3.y=this.getY(_i36);_vector$3.z=this.getZ(_i36);_vector$3.applyNormalMatrix(m);this.setXYZ(_i36,_vector$3.x,_vector$3.y,_vector$3.z);}return this;},transformDirection:function transformDirection(m){for(var _i37=0,l=this.count;_i37<l;_i37++){_vector$3.x=this.getX(_i37);_vector$3.y=this.getY(_i37);_vector$3.z=this.getZ(_i37);_vector$3.transformDirection(m);this.setXYZ(_i37,_vector$3.x,_vector$3.y,_vector$3.z);}return this;},set:function set(value){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.array.set(value,offset);return this;},getX:function getX(index){return this.array[index*this.itemSize];},setX:function setX(index,x){this.array[index*this.itemSize]=x;return this;},getY:function getY(index){return this.array[index*this.itemSize+1];},setY:function setY(index,y){this.array[index*this.itemSize+1]=y;return this;},getZ:function getZ(index){return this.array[index*this.itemSize+2];},setZ:function setZ(index,z){this.array[index*this.itemSize+2]=z;return this;},getW:function getW(index){return this.array[index*this.itemSize+3];},setW:function setW(index,w){this.array[index*this.itemSize+3]=w;return this;},setXY:function setXY(index,x,y){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;return this;},setXYZ:function setXYZ(index,x,y,z){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;this.array[index+2]=z;return this;},setXYZW:function setXYZW(index,x,y,z,w){index*=this.itemSize;this.array[index+0]=x;this.array[index+1]=y;this.array[index+2]=z;this.array[index+3]=w;return this;},onUpload:function onUpload(callback){this.onUploadCallback=callback;return this;},clone:function clone(){return new this.constructor(this.array,this.itemSize).copy(this);},toJSON:function toJSON(){return {itemSize:this.itemSize,type:this.array.constructor.name,array:Array.prototype.slice.call(this.array),normalized:this.normalized};}});//
  2878. function Int8BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int8Array(array),itemSize,normalized);}Int8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int8BufferAttribute.prototype.constructor=Int8BufferAttribute;function Uint8BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint8Array(array),itemSize,normalized);}Uint8BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8BufferAttribute.prototype.constructor=Uint8BufferAttribute;function Uint8ClampedBufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint8ClampedArray(array),itemSize,normalized);}Uint8ClampedBufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint8ClampedBufferAttribute.prototype.constructor=Uint8ClampedBufferAttribute;function Int16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int16Array(array),itemSize,normalized);}Int16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int16BufferAttribute.prototype.constructor=Int16BufferAttribute;function Uint16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint16Array(array),itemSize,normalized);}Uint16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint16BufferAttribute.prototype.constructor=Uint16BufferAttribute;function Int32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Int32Array(array),itemSize,normalized);}Int32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Int32BufferAttribute.prototype.constructor=Int32BufferAttribute;function Uint32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint32Array(array),itemSize,normalized);}Uint32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Uint32BufferAttribute.prototype.constructor=Uint32BufferAttribute;function Float16BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Uint16Array(array),itemSize,normalized);}Float16BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float16BufferAttribute.prototype.constructor=Float16BufferAttribute;Float16BufferAttribute.prototype.isFloat16BufferAttribute=true;function Float32BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Float32Array(array),itemSize,normalized);}Float32BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float32BufferAttribute.prototype.constructor=Float32BufferAttribute;function Float64BufferAttribute(array,itemSize,normalized){BufferAttribute.call(this,new Float64Array(array),itemSize,normalized);}Float64BufferAttribute.prototype=Object.create(BufferAttribute.prototype);Float64BufferAttribute.prototype.constructor=Float64BufferAttribute;class DirectGeometry{constructor(){this.vertices=[];this.normals=[];this.colors=[];this.uvs=[];this.uvs2=[];this.groups=[];this.morphTargets={};this.skinWeights=[];this.skinIndices=[];// this.lineDistances = [];
  2879. this.boundingBox=null;this.boundingSphere=null;// update flags
  2880. this.verticesNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.uvsNeedUpdate=false;this.groupsNeedUpdate=false;}computeGroups(geometry){var groups=[];var group,i;var materialIndex=undefined;var faces=geometry.faces;for(i=0;i<faces.length;i++){var face=faces[i];// materials
  2881. if(face.materialIndex!==materialIndex){materialIndex=face.materialIndex;if(group!==undefined){group.count=i*3-group.start;groups.push(group);}group={start:i*3,materialIndex:materialIndex};}}if(group!==undefined){group.count=i*3-group.start;groups.push(group);}this.groups=groups;}fromGeometry(geometry){var faces=geometry.faces;var vertices=geometry.vertices;var faceVertexUvs=geometry.faceVertexUvs;var hasFaceVertexUv=faceVertexUvs[0]&&faceVertexUvs[0].length>0;var hasFaceVertexUv2=faceVertexUvs[1]&&faceVertexUvs[1].length>0;// morphs
  2882. var morphTargets=geometry.morphTargets;var morphTargetsLength=morphTargets.length;var morphTargetsPosition;if(morphTargetsLength>0){morphTargetsPosition=[];for(var _i38=0;_i38<morphTargetsLength;_i38++){morphTargetsPosition[_i38]={name:morphTargets[_i38].name,data:[]};}this.morphTargets.position=morphTargetsPosition;}var morphNormals=geometry.morphNormals;var morphNormalsLength=morphNormals.length;var morphTargetsNormal;if(morphNormalsLength>0){morphTargetsNormal=[];for(var _i39=0;_i39<morphNormalsLength;_i39++){morphTargetsNormal[_i39]={name:morphNormals[_i39].name,data:[]};}this.morphTargets.normal=morphTargetsNormal;}// skins
  2883. var skinIndices=geometry.skinIndices;var skinWeights=geometry.skinWeights;var hasSkinIndices=skinIndices.length===vertices.length;var hasSkinWeights=skinWeights.length===vertices.length;//
  2884. if(vertices.length>0&&faces.length===0){console.error('THREE.DirectGeometry: Faceless geometries are not supported.');}for(var _i40=0;_i40<faces.length;_i40++){var face=faces[_i40];this.vertices.push(vertices[face.a],vertices[face.b],vertices[face.c]);var vertexNormals=face.vertexNormals;if(vertexNormals.length===3){this.normals.push(vertexNormals[0],vertexNormals[1],vertexNormals[2]);}else {var normal=face.normal;this.normals.push(normal,normal,normal);}var vertexColors=face.vertexColors;if(vertexColors.length===3){this.colors.push(vertexColors[0],vertexColors[1],vertexColors[2]);}else {var color=face.color;this.colors.push(color,color,color);}if(hasFaceVertexUv===true){var vertexUvs=faceVertexUvs[0][_i40];if(vertexUvs!==undefined){this.uvs.push(vertexUvs[0],vertexUvs[1],vertexUvs[2]);}else {console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ',_i40);this.uvs.push(new Vector2(),new Vector2(),new Vector2());}}if(hasFaceVertexUv2===true){var _vertexUvs=faceVertexUvs[1][_i40];if(_vertexUvs!==undefined){this.uvs2.push(_vertexUvs[0],_vertexUvs[1],_vertexUvs[2]);}else {console.warn('THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ',_i40);this.uvs2.push(new Vector2(),new Vector2(),new Vector2());}}// morphs
  2885. for(var j=0;j<morphTargetsLength;j++){var morphTarget=morphTargets[j].vertices;morphTargetsPosition[j].data.push(morphTarget[face.a],morphTarget[face.b],morphTarget[face.c]);}for(var _j=0;_j<morphNormalsLength;_j++){var morphNormal=morphNormals[_j].vertexNormals[_i40];morphTargetsNormal[_j].data.push(morphNormal.a,morphNormal.b,morphNormal.c);}// skins
  2886. if(hasSkinIndices){this.skinIndices.push(skinIndices[face.a],skinIndices[face.b],skinIndices[face.c]);}if(hasSkinWeights){this.skinWeights.push(skinWeights[face.a],skinWeights[face.b],skinWeights[face.c]);}}this.computeGroups(geometry);this.verticesNeedUpdate=geometry.verticesNeedUpdate;this.normalsNeedUpdate=geometry.normalsNeedUpdate;this.colorsNeedUpdate=geometry.colorsNeedUpdate;this.uvsNeedUpdate=geometry.uvsNeedUpdate;this.groupsNeedUpdate=geometry.groupsNeedUpdate;if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}return this;}}function arrayMax(array){if(array.length===0)return -Infinity;var max=array[0];for(var _i41=1,l=array.length;_i41<l;++_i41){if(array[_i41]>max)max=array[_i41];}return max;}var TYPED_ARRAYS={Int8Array:Int8Array,Uint8Array:Uint8Array,// Workaround for IE11 pre KB2929437. See #11440
  2887. Uint8ClampedArray:typeof Uint8ClampedArray!=='undefined'?Uint8ClampedArray:Uint8Array,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float32Array:Float32Array,Float64Array:Float64Array};function getTypedArray(type,buffer){return new TYPED_ARRAYS[type](buffer);}var _bufferGeometryId=1;// BufferGeometry uses odd numbers as Id
  2888. var _m1$2=new Matrix4();var _obj=new Object3D();var _offset=new Vector3();var _box$2=new Box3();var _boxMorphTargets=new Box3();var _vector$4=new Vector3();function BufferGeometry(){Object.defineProperty(this,'id',{value:_bufferGeometryId+=2});this.uuid=MathUtils.generateUUID();this.name='';this.type='BufferGeometry';this.index=null;this.attributes={};this.morphAttributes={};this.morphTargetsRelative=false;this.groups=[];this.boundingBox=null;this.boundingSphere=null;this.drawRange={start:0,count:Infinity};this.userData={};}BufferGeometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:BufferGeometry,isBufferGeometry:true,getIndex:function getIndex(){return this.index;},setIndex:function setIndex(index){if(Array.isArray(index)){this.index=new(arrayMax(index)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(index,1);}else {this.index=index;}return this;},getAttribute:function getAttribute(name){return this.attributes[name];},setAttribute:function setAttribute(name,attribute){this.attributes[name]=attribute;return this;},deleteAttribute:function deleteAttribute(name){delete this.attributes[name];return this;},hasAttribute:function hasAttribute(name){return this.attributes[name]!==undefined;},addGroup:function addGroup(start,count){var materialIndex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;this.groups.push({start:start,count:count,materialIndex:materialIndex});},clearGroups:function clearGroups(){this.groups=[];},setDrawRange:function setDrawRange(start,count){this.drawRange.start=start;this.drawRange.count=count;},applyMatrix4:function applyMatrix4(matrix){var position=this.attributes.position;if(position!==undefined){position.applyMatrix4(matrix);position.needsUpdate=true;}var normal=this.attributes.normal;if(normal!==undefined){var normalMatrix=new Matrix3().getNormalMatrix(matrix);normal.applyNormalMatrix(normalMatrix);normal.needsUpdate=true;}var tangent=this.attributes.tangent;if(tangent!==undefined){tangent.transformDirection(matrix);tangent.needsUpdate=true;}if(this.boundingBox!==null){this.computeBoundingBox();}if(this.boundingSphere!==null){this.computeBoundingSphere();}return this;},rotateX:function rotateX(angle){// rotate geometry around world x-axis
  2889. _m1$2.makeRotationX(angle);this.applyMatrix4(_m1$2);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis
  2890. _m1$2.makeRotationY(angle);this.applyMatrix4(_m1$2);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis
  2891. _m1$2.makeRotationZ(angle);this.applyMatrix4(_m1$2);return this;},translate:function translate(x,y,z){// translate geometry
  2892. _m1$2.makeTranslation(x,y,z);this.applyMatrix4(_m1$2);return this;},scale:function scale(x,y,z){// scale geometry
  2893. _m1$2.makeScale(x,y,z);this.applyMatrix4(_m1$2);return this;},lookAt:function lookAt(vector){_obj.lookAt(vector);_obj.updateMatrix();this.applyMatrix4(_obj.matrix);return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset).negate();this.translate(_offset.x,_offset.y,_offset.z);return this;},setFromObject:function setFromObject(object){// console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  2894. var geometry=object.geometry;if(object.isPoints||object.isLine){var positions=new Float32BufferAttribute(geometry.vertices.length*3,3);var colors=new Float32BufferAttribute(geometry.colors.length*3,3);this.setAttribute('position',positions.copyVector3sArray(geometry.vertices));this.setAttribute('color',colors.copyColorsArray(geometry.colors));if(geometry.lineDistances&&geometry.lineDistances.length===geometry.vertices.length){var lineDistances=new Float32BufferAttribute(geometry.lineDistances.length,1);this.setAttribute('lineDistance',lineDistances.copyArray(geometry.lineDistances));}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}}else if(object.isMesh){if(geometry&&geometry.isGeometry){this.fromGeometry(geometry);}}return this;},setFromPoints:function setFromPoints(points){var position=[];for(var _i42=0,l=points.length;_i42<l;_i42++){var point=points[_i42];position.push(point.x,point.y,point.z||0);}this.setAttribute('position',new Float32BufferAttribute(position,3));return this;},updateFromObject:function updateFromObject(object){var geometry=object.geometry;if(object.isMesh){var direct=geometry.__directGeometry;if(geometry.elementsNeedUpdate===true){direct=undefined;geometry.elementsNeedUpdate=false;}if(direct===undefined){return this.fromGeometry(geometry);}direct.verticesNeedUpdate=geometry.verticesNeedUpdate;direct.normalsNeedUpdate=geometry.normalsNeedUpdate;direct.colorsNeedUpdate=geometry.colorsNeedUpdate;direct.uvsNeedUpdate=geometry.uvsNeedUpdate;direct.groupsNeedUpdate=geometry.groupsNeedUpdate;geometry.verticesNeedUpdate=false;geometry.normalsNeedUpdate=false;geometry.colorsNeedUpdate=false;geometry.uvsNeedUpdate=false;geometry.groupsNeedUpdate=false;geometry=direct;}if(geometry.verticesNeedUpdate===true){var attribute=this.attributes.position;if(attribute!==undefined){attribute.copyVector3sArray(geometry.vertices);attribute.needsUpdate=true;}geometry.verticesNeedUpdate=false;}if(geometry.normalsNeedUpdate===true){var _attribute=this.attributes.normal;if(_attribute!==undefined){_attribute.copyVector3sArray(geometry.normals);_attribute.needsUpdate=true;}geometry.normalsNeedUpdate=false;}if(geometry.colorsNeedUpdate===true){var _attribute2=this.attributes.color;if(_attribute2!==undefined){_attribute2.copyColorsArray(geometry.colors);_attribute2.needsUpdate=true;}geometry.colorsNeedUpdate=false;}if(geometry.uvsNeedUpdate){var _attribute3=this.attributes.uv;if(_attribute3!==undefined){_attribute3.copyVector2sArray(geometry.uvs);_attribute3.needsUpdate=true;}geometry.uvsNeedUpdate=false;}if(geometry.lineDistancesNeedUpdate){var _attribute4=this.attributes.lineDistance;if(_attribute4!==undefined){_attribute4.copyArray(geometry.lineDistances);_attribute4.needsUpdate=true;}geometry.lineDistancesNeedUpdate=false;}if(geometry.groupsNeedUpdate){geometry.computeGroups(object.geometry);this.groups=geometry.groups;geometry.groupsNeedUpdate=false;}return this;},fromGeometry:function fromGeometry(geometry){geometry.__directGeometry=new DirectGeometry().fromGeometry(geometry);return this.fromDirectGeometry(geometry.__directGeometry);},fromDirectGeometry:function fromDirectGeometry(geometry){var positions=new Float32Array(geometry.vertices.length*3);this.setAttribute('position',new BufferAttribute(positions,3).copyVector3sArray(geometry.vertices));if(geometry.normals.length>0){var normals=new Float32Array(geometry.normals.length*3);this.setAttribute('normal',new BufferAttribute(normals,3).copyVector3sArray(geometry.normals));}if(geometry.colors.length>0){var colors=new Float32Array(geometry.colors.length*3);this.setAttribute('color',new BufferAttribute(colors,3).copyColorsArray(geometry.colors));}if(geometry.uvs.length>0){var uvs=new Float32Array(geometry.uvs.length*2);this.setAttribute('uv',new BufferAttribute(uvs,2).copyVector2sArray(geometry.uvs));}if(geometry.uvs2.length>0){var uvs2=new Float32Array(geometry.uvs2.length*2);this.setAttribute('uv2',new BufferAttribute(uvs2,2).copyVector2sArray(geometry.uvs2));}// groups
  2895. this.groups=geometry.groups;// morphs
  2896. for(var name in geometry.morphTargets){var array=[];var morphTargets=geometry.morphTargets[name];for(var _i43=0,l=morphTargets.length;_i43<l;_i43++){var morphTarget=morphTargets[_i43];var attribute=new Float32BufferAttribute(morphTarget.data.length*3,3);attribute.name=morphTarget.name;array.push(attribute.copyVector3sArray(morphTarget.data));}this.morphAttributes[name]=array;}// skinning
  2897. if(geometry.skinIndices.length>0){var skinIndices=new Float32BufferAttribute(geometry.skinIndices.length*4,4);this.setAttribute('skinIndex',skinIndices.copyVector4sArray(geometry.skinIndices));}if(geometry.skinWeights.length>0){var skinWeights=new Float32BufferAttribute(geometry.skinWeights.length*4,4);this.setAttribute('skinWeight',skinWeights.copyVector4sArray(geometry.skinWeights));}//
  2898. if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}return this;},computeBoundingBox:function computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position&&position.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".',this);this.boundingBox.set(new Vector3(-Infinity,-Infinity,-Infinity),new Vector3(+Infinity,+Infinity,+Infinity));return;}if(position!==undefined){this.boundingBox.setFromBufferAttribute(position);// process morph attributes if present
  2899. if(morphAttributesPosition){for(var _i44=0,il=morphAttributesPosition.length;_i44<il;_i44++){var morphAttribute=morphAttributesPosition[_i44];_box$2.setFromBufferAttribute(morphAttribute);if(this.morphTargetsRelative){_vector$4.addVectors(this.boundingBox.min,_box$2.min);this.boundingBox.expandByPoint(_vector$4);_vector$4.addVectors(this.boundingBox.max,_box$2.max);this.boundingBox.expandByPoint(_vector$4);}else {this.boundingBox.expandByPoint(_box$2.min);this.boundingBox.expandByPoint(_box$2.max);}}}}else {this.boundingBox.makeEmpty();}if(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z)){console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this);}},computeBoundingSphere:function computeBoundingSphere(){if(this.boundingSphere===null){this.boundingSphere=new Sphere();}var position=this.attributes.position;var morphAttributesPosition=this.morphAttributes.position;if(position&&position.isGLBufferAttribute){console.error('THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".',this);this.boundingSphere.set(new Vector3(),Infinity);return;}if(position){// first, find the center of the bounding sphere
  2900. var center=this.boundingSphere.center;_box$2.setFromBufferAttribute(position);// process morph attributes if present
  2901. if(morphAttributesPosition){for(var _i45=0,il=morphAttributesPosition.length;_i45<il;_i45++){var morphAttribute=morphAttributesPosition[_i45];_boxMorphTargets.setFromBufferAttribute(morphAttribute);if(this.morphTargetsRelative){_vector$4.addVectors(_box$2.min,_boxMorphTargets.min);_box$2.expandByPoint(_vector$4);_vector$4.addVectors(_box$2.max,_boxMorphTargets.max);_box$2.expandByPoint(_vector$4);}else {_box$2.expandByPoint(_boxMorphTargets.min);_box$2.expandByPoint(_boxMorphTargets.max);}}}_box$2.getCenter(center);// second, try to find a boundingSphere with a radius smaller than the
  2902. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  2903. var maxRadiusSq=0;for(var _i46=0,_il2=position.count;_i46<_il2;_i46++){_vector$4.fromBufferAttribute(position,_i46);maxRadiusSq=Math.max(maxRadiusSq,center.distanceToSquared(_vector$4));}// process morph attributes if present
  2904. if(morphAttributesPosition){for(var _i47=0,_il3=morphAttributesPosition.length;_i47<_il3;_i47++){var _morphAttribute=morphAttributesPosition[_i47];var morphTargetsRelative=this.morphTargetsRelative;for(var j=0,jl=_morphAttribute.count;j<jl;j++){_vector$4.fromBufferAttribute(_morphAttribute,j);if(morphTargetsRelative){_offset.fromBufferAttribute(position,j);_vector$4.add(_offset);}maxRadiusSq=Math.max(maxRadiusSq,center.distanceToSquared(_vector$4));}}}this.boundingSphere.radius=Math.sqrt(maxRadiusSq);if(isNaN(this.boundingSphere.radius)){console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this);}}},computeFaceNormals:function computeFaceNormals(){// backwards compatibility
  2905. },computeVertexNormals:function computeVertexNormals(){var index=this.index;var positionAttribute=this.getAttribute('position');if(positionAttribute!==undefined){var normalAttribute=this.getAttribute('normal');if(normalAttribute===undefined){normalAttribute=new BufferAttribute(new Float32Array(positionAttribute.count*3),3);this.setAttribute('normal',normalAttribute);}else {// reset existing normals to zero
  2906. for(var _i48=0,il=normalAttribute.count;_i48<il;_i48++){normalAttribute.setXYZ(_i48,0,0,0);}}var pA=new Vector3(),pB=new Vector3(),pC=new Vector3();var nA=new Vector3(),nB=new Vector3(),nC=new Vector3();var cb=new Vector3(),ab=new Vector3();// indexed elements
  2907. if(index){for(var _i49=0,_il4=index.count;_i49<_il4;_i49+=3){var vA=index.getX(_i49+0);var vB=index.getX(_i49+1);var vC=index.getX(_i49+2);pA.fromBufferAttribute(positionAttribute,vA);pB.fromBufferAttribute(positionAttribute,vB);pC.fromBufferAttribute(positionAttribute,vC);cb.subVectors(pC,pB);ab.subVectors(pA,pB);cb.cross(ab);nA.fromBufferAttribute(normalAttribute,vA);nB.fromBufferAttribute(normalAttribute,vB);nC.fromBufferAttribute(normalAttribute,vC);nA.add(cb);nB.add(cb);nC.add(cb);normalAttribute.setXYZ(vA,nA.x,nA.y,nA.z);normalAttribute.setXYZ(vB,nB.x,nB.y,nB.z);normalAttribute.setXYZ(vC,nC.x,nC.y,nC.z);}}else {// non-indexed elements (unconnected triangle soup)
  2908. for(var _i50=0,_il5=positionAttribute.count;_i50<_il5;_i50+=3){pA.fromBufferAttribute(positionAttribute,_i50+0);pB.fromBufferAttribute(positionAttribute,_i50+1);pC.fromBufferAttribute(positionAttribute,_i50+2);cb.subVectors(pC,pB);ab.subVectors(pA,pB);cb.cross(ab);normalAttribute.setXYZ(_i50+0,cb.x,cb.y,cb.z);normalAttribute.setXYZ(_i50+1,cb.x,cb.y,cb.z);normalAttribute.setXYZ(_i50+2,cb.x,cb.y,cb.z);}}this.normalizeNormals();normalAttribute.needsUpdate=true;}},merge:function merge(geometry,offset){if(!(geometry&&geometry.isBufferGeometry)){console.error('THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.',geometry);return;}if(offset===undefined){offset=0;console.warn('THREE.BufferGeometry.merge(): Overwriting original geometry, starting at offset=0. '+'Use BufferGeometryUtils.mergeBufferGeometries() for lossless merge.');}var attributes=this.attributes;for(var key in attributes){if(geometry.attributes[key]===undefined)continue;var attribute1=attributes[key];var attributeArray1=attribute1.array;var attribute2=geometry.attributes[key];var attributeArray2=attribute2.array;var attributeOffset=attribute2.itemSize*offset;var length=Math.min(attributeArray2.length,attributeArray1.length-attributeOffset);for(var _i51=0,j=attributeOffset;_i51<length;_i51++,j++){attributeArray1[j]=attributeArray2[_i51];}}return this;},normalizeNormals:function normalizeNormals(){var normals=this.attributes.normal;for(var _i52=0,il=normals.count;_i52<il;_i52++){_vector$4.fromBufferAttribute(normals,_i52);_vector$4.normalize();normals.setXYZ(_i52,_vector$4.x,_vector$4.y,_vector$4.z);}},toNonIndexed:function toNonIndexed(){function convertBufferAttribute(attribute,indices){var array=attribute.array;var itemSize=attribute.itemSize;var normalized=attribute.normalized;var array2=new array.constructor(indices.length*itemSize);var index=0,index2=0;for(var _i53=0,l=indices.length;_i53<l;_i53++){index=indices[_i53]*itemSize;for(var j=0;j<itemSize;j++){array2[index2++]=array[index++];}}return new BufferAttribute(array2,itemSize,normalized);}//
  2909. if(this.index===null){console.warn('THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.');return this;}var geometry2=new BufferGeometry();var indices=this.index.array;var attributes=this.attributes;// attributes
  2910. for(var name in attributes){var attribute=attributes[name];var newAttribute=convertBufferAttribute(attribute,indices);geometry2.setAttribute(name,newAttribute);}// morph attributes
  2911. var morphAttributes=this.morphAttributes;for(var _name in morphAttributes){var morphArray=[];var morphAttribute=morphAttributes[_name];// morphAttribute: array of Float32BufferAttributes
  2912. for(var _i54=0,il=morphAttribute.length;_i54<il;_i54++){var _attribute5=morphAttribute[_i54];var _newAttribute=convertBufferAttribute(_attribute5,indices);morphArray.push(_newAttribute);}geometry2.morphAttributes[_name]=morphArray;}geometry2.morphTargetsRelative=this.morphTargetsRelative;// groups
  2913. var groups=this.groups;for(var _i55=0,l=groups.length;_i55<l;_i55++){var group=groups[_i55];geometry2.addGroup(group.start,group.count,group.materialIndex);}return geometry2;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'BufferGeometry',generator:'BufferGeometry.toJSON'}};// standard BufferGeometry serialization
  2914. data.uuid=this.uuid;data.type=this.type;if(this.name!=='')data.name=this.name;if(Object.keys(this.userData).length>0)data.userData=this.userData;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key];}return data;}data.data={attributes:{}};var index=this.index;if(index!==null){data.data.index={type:index.array.constructor.name,array:Array.prototype.slice.call(index.array)};}var attributes=this.attributes;for(var _key in attributes){var attribute=attributes[_key];var attributeData=attribute.toJSON(data.data);if(attribute.name!=='')attributeData.name=attribute.name;data.data.attributes[_key]=attributeData;}var morphAttributes={};var hasMorphAttributes=false;for(var _key2 in this.morphAttributes){var attributeArray=this.morphAttributes[_key2];var array=[];for(var _i56=0,il=attributeArray.length;_i56<il;_i56++){var _attribute6=attributeArray[_i56];var _attributeData=_attribute6.toJSON(data.data);if(_attribute6.name!=='')_attributeData.name=_attribute6.name;array.push(_attributeData);}if(array.length>0){morphAttributes[_key2]=array;hasMorphAttributes=true;}}if(hasMorphAttributes){data.data.morphAttributes=morphAttributes;data.data.morphTargetsRelative=this.morphTargetsRelative;}var groups=this.groups;if(groups.length>0){data.data.groups=JSON.parse(JSON.stringify(groups));}var boundingSphere=this.boundingSphere;if(boundingSphere!==null){data.data.boundingSphere={center:boundingSphere.center.toArray(),radius:boundingSphere.radius};}return data;},clone:function clone(){/*
  2915. // Handle primitives
  2916. const parameters = this.parameters;
  2917. if ( parameters !== undefined ) {
  2918. const values = [];
  2919. for ( const key in parameters ) {
  2920. values.push( parameters[ key ] );
  2921. }
  2922. const geometry = Object.create( this.constructor.prototype );
  2923. this.constructor.apply( geometry, values );
  2924. return geometry;
  2925. }
  2926. return new this.constructor().copy( this );
  2927. */return new BufferGeometry().copy(this);},copy:function copy(source){// reset
  2928. this.index=null;this.attributes={};this.morphAttributes={};this.groups=[];this.boundingBox=null;this.boundingSphere=null;// used for storing cloned, shared data
  2929. var data={};// name
  2930. this.name=source.name;// index
  2931. var index=source.index;if(index!==null){this.setIndex(index.clone(data));}// attributes
  2932. var attributes=source.attributes;for(var name in attributes){var attribute=attributes[name];this.setAttribute(name,attribute.clone(data));}// morph attributes
  2933. var morphAttributes=source.morphAttributes;for(var _name2 in morphAttributes){var array=[];var morphAttribute=morphAttributes[_name2];// morphAttribute: array of Float32BufferAttributes
  2934. for(var _i57=0,l=morphAttribute.length;_i57<l;_i57++){array.push(morphAttribute[_i57].clone(data));}this.morphAttributes[_name2]=array;}this.morphTargetsRelative=source.morphTargetsRelative;// groups
  2935. var groups=source.groups;for(var _i58=0,_l3=groups.length;_i58<_l3;_i58++){var group=groups[_i58];this.addGroup(group.start,group.count,group.materialIndex);}// bounding box
  2936. var boundingBox=source.boundingBox;if(boundingBox!==null){this.boundingBox=boundingBox.clone();}// bounding sphere
  2937. var boundingSphere=source.boundingSphere;if(boundingSphere!==null){this.boundingSphere=boundingSphere.clone();}// draw range
  2938. this.drawRange.start=source.drawRange.start;this.drawRange.count=source.drawRange.count;// user data
  2939. this.userData=source.userData;return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});var _inverseMatrix=new Matrix4();var _ray=new Ray();var _sphere=new Sphere();var _vA=new Vector3();var _vB=new Vector3();var _vC=new Vector3();var _tempA=new Vector3();var _tempB=new Vector3();var _tempC=new Vector3();var _morphA=new Vector3();var _morphB=new Vector3();var _morphC=new Vector3();var _uvA=new Vector2();var _uvB=new Vector2();var _uvC=new Vector2();var _intersectionPoint=new Vector3();var _intersectionPointWorld=new Vector3();function Mesh(){var geometry=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new MeshBasicMaterial();Object3D.call(this);this.type='Mesh';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Mesh.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Mesh,isMesh:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.morphTargetInfluences!==undefined){this.morphTargetInfluences=source.morphTargetInfluences.slice();}if(source.morphTargetDictionary!==undefined){this.morphTargetDictionary=Object.assign({},source.morphTargetDictionary);}this.material=source.material;this.geometry=source.geometry;return this;},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m<ml;m++){var name=morphAttribute[m].name||String(m);this.morphTargetInfluences.push(0);this.morphTargetDictionary[name]=m;}}}}else {var morphTargets=geometry.morphTargets;if(morphTargets!==undefined&&morphTargets.length>0){console.error('THREE.Mesh.updateMorphTargets() no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}}},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var material=this.material;var matrixWorld=this.matrixWorld;if(material===undefined)return;// Checking boundingSphere distance to ray
  2940. if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere.copy(geometry.boundingSphere);_sphere.applyMatrix4(matrixWorld);if(raycaster.ray.intersectsSphere(_sphere)===false)return;//
  2941. _inverseMatrix.copy(matrixWorld).invert();_ray.copy(raycaster.ray).applyMatrix4(_inverseMatrix);// Check boundingBox before continuing
  2942. if(geometry.boundingBox!==null){if(_ray.intersectsBox(geometry.boundingBox)===false)return;}var intersection;if(geometry.isBufferGeometry){var index=geometry.index;var position=geometry.attributes.position;var morphPosition=geometry.morphAttributes.position;var morphTargetsRelative=geometry.morphTargetsRelative;var uv=geometry.attributes.uv;var uv2=geometry.attributes.uv2;var groups=geometry.groups;var drawRange=geometry.drawRange;if(index!==null){// indexed buffer geometry
  2943. if(Array.isArray(material)){for(var _i59=0,il=groups.length;_i59<il;_i59++){var group=groups[_i59];var groupMaterial=material[group.materialIndex];var start=Math.max(group.start,drawRange.start);var end=Math.min(group.start+group.count,drawRange.start+drawRange.count);for(var j=start,jl=end;j<jl;j+=3){var a=index.getX(j);var b=index.getX(j+1);var c=index.getX(j+2);intersection=checkBufferGeometryIntersection(this,groupMaterial,raycaster,_ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c);if(intersection){intersection.faceIndex=Math.floor(j/3);// triangle number in indexed buffer semantics
  2944. intersection.face.materialIndex=group.materialIndex;intersects.push(intersection);}}}}else {var _start2=Math.max(0,drawRange.start);var _end2=Math.min(index.count,drawRange.start+drawRange.count);for(var _i60=_start2,_il6=_end2;_i60<_il6;_i60+=3){var _a=index.getX(_i60);var _b=index.getX(_i60+1);var _c=index.getX(_i60+2);intersection=checkBufferGeometryIntersection(this,material,raycaster,_ray,position,morphPosition,morphTargetsRelative,uv,uv2,_a,_b,_c);if(intersection){intersection.faceIndex=Math.floor(_i60/3);// triangle number in indexed buffer semantics
  2945. intersects.push(intersection);}}}}else if(position!==undefined){// non-indexed buffer geometry
  2946. if(Array.isArray(material)){for(var _i61=0,_il7=groups.length;_i61<_il7;_i61++){var _group=groups[_i61];var _groupMaterial=material[_group.materialIndex];var _start3=Math.max(_group.start,drawRange.start);var _end3=Math.min(_group.start+_group.count,drawRange.start+drawRange.count);for(var _j2=_start3,_jl=_end3;_j2<_jl;_j2+=3){var _a2=_j2;var _b2=_j2+1;var _c2=_j2+2;intersection=checkBufferGeometryIntersection(this,_groupMaterial,raycaster,_ray,position,morphPosition,morphTargetsRelative,uv,uv2,_a2,_b2,_c2);if(intersection){intersection.faceIndex=Math.floor(_j2/3);// triangle number in non-indexed buffer semantics
  2947. intersection.face.materialIndex=_group.materialIndex;intersects.push(intersection);}}}}else {var _start4=Math.max(0,drawRange.start);var _end4=Math.min(position.count,drawRange.start+drawRange.count);for(var _i62=_start4,_il8=_end4;_i62<_il8;_i62+=3){var _a3=_i62;var _b3=_i62+1;var _c3=_i62+2;intersection=checkBufferGeometryIntersection(this,material,raycaster,_ray,position,morphPosition,morphTargetsRelative,uv,uv2,_a3,_b3,_c3);if(intersection){intersection.faceIndex=Math.floor(_i62/3);// triangle number in non-indexed buffer semantics
  2948. intersects.push(intersection);}}}}}else if(geometry.isGeometry){var isMultiMaterial=Array.isArray(material);var vertices=geometry.vertices;var faces=geometry.faces;var uvs;var faceVertexUvs=geometry.faceVertexUvs[0];if(faceVertexUvs.length>0)uvs=faceVertexUvs;for(var f=0,fl=faces.length;f<fl;f++){var face=faces[f];var faceMaterial=isMultiMaterial?material[face.materialIndex]:material;if(faceMaterial===undefined)continue;var fvA=vertices[face.a];var fvB=vertices[face.b];var fvC=vertices[face.c];intersection=checkIntersection(this,faceMaterial,raycaster,_ray,fvA,fvB,fvC,_intersectionPoint);if(intersection){if(uvs&&uvs[f]){var uvs_f=uvs[f];_uvA.copy(uvs_f[0]);_uvB.copy(uvs_f[1]);_uvC.copy(uvs_f[2]);intersection.uv=Triangle.getUV(_intersectionPoint,fvA,fvB,fvC,_uvA,_uvB,_uvC,new Vector2());}intersection.face=face;intersection.faceIndex=f;intersects.push(intersection);}}}}});function checkIntersection(object,material,raycaster,ray,pA,pB,pC,point){var intersect;if(material.side===BackSide){intersect=ray.intersectTriangle(pC,pB,pA,true,point);}else {intersect=ray.intersectTriangle(pA,pB,pC,material.side!==DoubleSide,point);}if(intersect===null)return null;_intersectionPointWorld.copy(point);_intersectionPointWorld.applyMatrix4(object.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_intersectionPointWorld);if(distance<raycaster.near||distance>raycaster.far)return null;return {distance:distance,point:_intersectionPointWorld.clone(),object:object};}function checkBufferGeometryIntersection(object,material,raycaster,ray,position,morphPosition,morphTargetsRelative,uv,uv2,a,b,c){_vA.fromBufferAttribute(position,a);_vB.fromBufferAttribute(position,b);_vC.fromBufferAttribute(position,c);var morphInfluences=object.morphTargetInfluences;if(material.morphTargets&&morphPosition&&morphInfluences){_morphA.set(0,0,0);_morphB.set(0,0,0);_morphC.set(0,0,0);for(var _i63=0,il=morphPosition.length;_i63<il;_i63++){var influence=morphInfluences[_i63];var morphAttribute=morphPosition[_i63];if(influence===0)continue;_tempA.fromBufferAttribute(morphAttribute,a);_tempB.fromBufferAttribute(morphAttribute,b);_tempC.fromBufferAttribute(morphAttribute,c);if(morphTargetsRelative){_morphA.addScaledVector(_tempA,influence);_morphB.addScaledVector(_tempB,influence);_morphC.addScaledVector(_tempC,influence);}else {_morphA.addScaledVector(_tempA.sub(_vA),influence);_morphB.addScaledVector(_tempB.sub(_vB),influence);_morphC.addScaledVector(_tempC.sub(_vC),influence);}}_vA.add(_morphA);_vB.add(_morphB);_vC.add(_morphC);}if(object.isSkinnedMesh){object.boneTransform(a,_vA);object.boneTransform(b,_vB);object.boneTransform(c,_vC);}var intersection=checkIntersection(object,material,raycaster,ray,_vA,_vB,_vC,_intersectionPoint);if(intersection){if(uv){_uvA.fromBufferAttribute(uv,a);_uvB.fromBufferAttribute(uv,b);_uvC.fromBufferAttribute(uv,c);intersection.uv=Triangle.getUV(_intersectionPoint,_vA,_vB,_vC,_uvA,_uvB,_uvC,new Vector2());}if(uv2){_uvA.fromBufferAttribute(uv2,a);_uvB.fromBufferAttribute(uv2,b);_uvC.fromBufferAttribute(uv2,c);intersection.uv2=Triangle.getUV(_intersectionPoint,_vA,_vB,_vC,_uvA,_uvB,_uvC,new Vector2());}var face=new Face3(a,b,c);Triangle.getNormal(_vA,_vB,_vC,face.normal);intersection.face=face;}return intersection;}class BoxBufferGeometry extends BufferGeometry{constructor(){var width=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var depth=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var widthSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var heightSegments=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var depthSegments=arguments.length>5&&arguments[5]!==undefined?arguments[5]:1;super();this.type='BoxBufferGeometry';this.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};var scope=this;// segments
  2949. widthSegments=Math.floor(widthSegments);heightSegments=Math.floor(heightSegments);depthSegments=Math.floor(depthSegments);// buffers
  2950. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  2951. var numberOfVertices=0;var groupStart=0;// build each side of the box geometry
  2952. buildPlane('z','y','x',-1,-1,depth,height,width,depthSegments,heightSegments,0);// px
  2953. buildPlane('z','y','x',1,-1,depth,height,-width,depthSegments,heightSegments,1);// nx
  2954. buildPlane('x','z','y',1,1,width,depth,height,widthSegments,depthSegments,2);// py
  2955. buildPlane('x','z','y',1,-1,width,depth,-height,widthSegments,depthSegments,3);// ny
  2956. buildPlane('x','y','z',1,-1,width,height,depth,widthSegments,heightSegments,4);// pz
  2957. buildPlane('x','y','z',-1,-1,width,height,-depth,widthSegments,heightSegments,5);// nz
  2958. // build geometry
  2959. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));function buildPlane(u,v,w,udir,vdir,width,height,depth,gridX,gridY,materialIndex){var segmentWidth=width/gridX;var segmentHeight=height/gridY;var widthHalf=width/2;var heightHalf=height/2;var depthHalf=depth/2;var gridX1=gridX+1;var gridY1=gridY+1;var vertexCounter=0;var groupCount=0;var vector=new Vector3();// generate vertices, normals and uvs
  2960. for(var iy=0;iy<gridY1;iy++){var y=iy*segmentHeight-heightHalf;for(var ix=0;ix<gridX1;ix++){var x=ix*segmentWidth-widthHalf;// set values to correct vector component
  2961. vector[u]=x*udir;vector[v]=y*vdir;vector[w]=depthHalf;// now apply vector to vertex buffer
  2962. vertices.push(vector.x,vector.y,vector.z);// set values to correct vector component
  2963. vector[u]=0;vector[v]=0;vector[w]=depth>0?1:-1;// now apply vector to normal buffer
  2964. normals.push(vector.x,vector.y,vector.z);// uvs
  2965. uvs.push(ix/gridX);uvs.push(1-iy/gridY);// counters
  2966. vertexCounter+=1;}}// indices
  2967. // 1. you need three indices to draw a single face
  2968. // 2. a single segment consists of two faces
  2969. // 3. so we need to generate six (2*3) indices per segment
  2970. for(var _iy=0;_iy<gridY;_iy++){for(var _ix=0;_ix<gridX;_ix++){var a=numberOfVertices+_ix+gridX1*_iy;var b=numberOfVertices+_ix+gridX1*(_iy+1);var c=numberOfVertices+(_ix+1)+gridX1*(_iy+1);var d=numberOfVertices+(_ix+1)+gridX1*_iy;// faces
  2971. indices.push(a,b,d);indices.push(b,c,d);// increase counter
  2972. groupCount+=6;}}// add a group to the geometry. this will ensure multi material support
  2973. scope.addGroup(groupStart,groupCount,materialIndex);// calculate new start value for groups
  2974. groupStart+=groupCount;// update total number of vertices
  2975. numberOfVertices+=vertexCounter;}}}/**
  2976. * Uniform Utilities
  2977. */function cloneUniforms(src){var dst={};for(var u in src){dst[u]={};for(var p in src[u]){var property=src[u][p];if(property&&(property.isColor||property.isMatrix3||property.isMatrix4||property.isVector2||property.isVector3||property.isVector4||property.isTexture)){dst[u][p]=property.clone();}else if(Array.isArray(property)){dst[u][p]=property.slice();}else {dst[u][p]=property;}}}return dst;}function mergeUniforms(uniforms){var merged={};for(var u=0;u<uniforms.length;u++){var _tmp=cloneUniforms(uniforms[u]);for(var p in _tmp){merged[p]=_tmp[p];}}return merged;}// Legacy
  2978. var UniformsUtils={clone:cloneUniforms,merge:mergeUniforms};var default_vertex="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";var default_fragment="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";/**
  2979. * parameters = {
  2980. * defines: { "label" : "value" },
  2981. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  2982. *
  2983. * fragmentShader: <string>,
  2984. * vertexShader: <string>,
  2985. *
  2986. * wireframe: <boolean>,
  2987. * wireframeLinewidth: <float>,
  2988. *
  2989. * lights: <bool>,
  2990. *
  2991. * skinning: <bool>,
  2992. * morphTargets: <bool>,
  2993. * morphNormals: <bool>
  2994. * }
  2995. */function ShaderMaterial(parameters){Material.call(this);this.type='ShaderMaterial';this.defines={};this.uniforms={};this.vertexShader=default_vertex;this.fragmentShader=default_fragment;this.linewidth=1;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;// set to use scene fog
  2996. this.lights=false;// set to use scene lights
  2997. this.clipping=false;// set to use user-defined clipping planes
  2998. this.skinning=false;// set to use skinning attribute streams
  2999. this.morphTargets=false;// set to use morph targets
  3000. this.morphNormals=false;// set to use morph normals
  3001. this.extensions={derivatives:false,// set to use derivatives
  3002. fragDepth:false,// set to use fragment depth values
  3003. drawBuffers:false,// set to use draw buffers
  3004. shaderTextureLOD:false// set to use shader texture LOD
  3005. };// When rendered geometry doesn't include these attributes but the material does,
  3006. // use these default values in WebGL. This avoids errors when buffer data is missing.
  3007. this.defaultAttributeValues={'color':[1,1,1],'uv':[0,0],'uv2':[0,0]};this.index0AttributeName=undefined;this.uniformsNeedUpdate=false;this.glslVersion=null;if(parameters!==undefined){if(parameters.attributes!==undefined){console.error('THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.');}this.setValues(parameters);}}ShaderMaterial.prototype=Object.create(Material.prototype);ShaderMaterial.prototype.constructor=ShaderMaterial;ShaderMaterial.prototype.isShaderMaterial=true;ShaderMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.fragmentShader=source.fragmentShader;this.vertexShader=source.vertexShader;this.uniforms=cloneUniforms(source.uniforms);this.defines=Object.assign({},source.defines);this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.lights=source.lights;this.clipping=source.clipping;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;this.extensions=Object.assign({},source.extensions);this.glslVersion=source.glslVersion;return this;};ShaderMaterial.prototype.toJSON=function(meta){var data=Material.prototype.toJSON.call(this,meta);data.glslVersion=this.glslVersion;data.uniforms={};for(var name in this.uniforms){var uniform=this.uniforms[name];var value=uniform.value;if(value&&value.isTexture){data.uniforms[name]={type:'t',value:value.toJSON(meta).uuid};}else if(value&&value.isColor){data.uniforms[name]={type:'c',value:value.getHex()};}else if(value&&value.isVector2){data.uniforms[name]={type:'v2',value:value.toArray()};}else if(value&&value.isVector3){data.uniforms[name]={type:'v3',value:value.toArray()};}else if(value&&value.isVector4){data.uniforms[name]={type:'v4',value:value.toArray()};}else if(value&&value.isMatrix3){data.uniforms[name]={type:'m3',value:value.toArray()};}else if(value&&value.isMatrix4){data.uniforms[name]={type:'m4',value:value.toArray()};}else {data.uniforms[name]={value:value};// note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  3008. }}if(Object.keys(this.defines).length>0)data.defines=this.defines;data.vertexShader=this.vertexShader;data.fragmentShader=this.fragmentShader;var extensions={};for(var key in this.extensions){if(this.extensions[key]===true)extensions[key]=true;}if(Object.keys(extensions).length>0)data.extensions=extensions;return data;};function Camera(){Object3D.call(this);this.type='Camera';this.matrixWorldInverse=new Matrix4();this.projectionMatrix=new Matrix4();this.projectionMatrixInverse=new Matrix4();}Camera.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Camera,isCamera:true,copy:function copy(source,recursive){Object3D.prototype.copy.call(this,source,recursive);this.matrixWorldInverse.copy(source.matrixWorldInverse);this.projectionMatrix.copy(source.projectionMatrix);this.projectionMatrixInverse.copy(source.projectionMatrixInverse);return this;},getWorldDirection:function getWorldDirection(target){if(target===undefined){console.warn('THREE.Camera: .getWorldDirection() target is now required');target=new Vector3();}this.updateWorldMatrix(true,false);var e=this.matrixWorld.elements;return target.set(-e[8],-e[9],-e[10]).normalize();},updateMatrixWorld:function updateMatrixWorld(force){Object3D.prototype.updateMatrixWorld.call(this,force);this.matrixWorldInverse.copy(this.matrixWorld).invert();},updateWorldMatrix:function updateWorldMatrix(updateParents,updateChildren){Object3D.prototype.updateWorldMatrix.call(this,updateParents,updateChildren);this.matrixWorldInverse.copy(this.matrixWorld).invert();},clone:function clone(){return new this.constructor().copy(this);}});function PerspectiveCamera(){var fov=arguments.length>0&&arguments[0]!==undefined?arguments[0]:50;var aspect=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:2000;Camera.call(this);this.type='PerspectiveCamera';this.fov=fov;this.zoom=1;this.near=near;this.far=far;this.focus=10;this.aspect=aspect;this.view=null;this.filmGauge=35;// width of the film (default in millimeters)
  3009. this.filmOffset=0;// horizontal film offset (same unit as gauge)
  3010. this.updateProjectionMatrix();}PerspectiveCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:PerspectiveCamera,isPerspectiveCamera:true,copy:function copy(source,recursive){Camera.prototype.copy.call(this,source,recursive);this.fov=source.fov;this.zoom=source.zoom;this.near=source.near;this.far=source.far;this.focus=source.focus;this.aspect=source.aspect;this.view=source.view===null?null:Object.assign({},source.view);this.filmGauge=source.filmGauge;this.filmOffset=source.filmOffset;return this;},/**
  3011. * Sets the FOV by focal length in respect to the current .filmGauge.
  3012. *
  3013. * The default film gauge is 35, so that the focal length can be specified for
  3014. * a 35mm (full frame) camera.
  3015. *
  3016. * Values for focal length and film gauge must have the same unit.
  3017. */setFocalLength:function setFocalLength(focalLength){// see http://www.bobatkins.com/photography/technical/field_of_view.html
  3018. var vExtentSlope=0.5*this.getFilmHeight()/focalLength;this.fov=MathUtils.RAD2DEG*2*Math.atan(vExtentSlope);this.updateProjectionMatrix();},/**
  3019. * Calculates the focal length from the current .fov and .filmGauge.
  3020. */getFocalLength:function getFocalLength(){var vExtentSlope=Math.tan(MathUtils.DEG2RAD*0.5*this.fov);return 0.5*this.getFilmHeight()/vExtentSlope;},getEffectiveFOV:function getEffectiveFOV(){return MathUtils.RAD2DEG*2*Math.atan(Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom);},getFilmWidth:function getFilmWidth(){// film not completely covered in portrait format (aspect < 1)
  3021. return this.filmGauge*Math.min(this.aspect,1);},getFilmHeight:function getFilmHeight(){// film not completely covered in landscape format (aspect > 1)
  3022. return this.filmGauge/Math.max(this.aspect,1);},/**
  3023. * Sets an offset in a larger frustum. This is useful for multi-window or
  3024. * multi-monitor/multi-machine setups.
  3025. *
  3026. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3027. * the monitors are in grid like this
  3028. *
  3029. * +---+---+---+
  3030. * | A | B | C |
  3031. * +---+---+---+
  3032. * | D | E | F |
  3033. * +---+---+---+
  3034. *
  3035. * then for each monitor you would call it like this
  3036. *
  3037. * const w = 1920;
  3038. * const h = 1080;
  3039. * const fullWidth = w * 3;
  3040. * const fullHeight = h * 2;
  3041. *
  3042. * --A--
  3043. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3044. * --B--
  3045. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3046. * --C--
  3047. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3048. * --D--
  3049. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3050. * --E--
  3051. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3052. * --F--
  3053. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3054. *
  3055. * Note there is no reason monitors have to be the same size or in a grid.
  3056. */setViewOffset:function setViewOffset(fullWidth,fullHeight,x,y,width,height){this.aspect=fullWidth/fullHeight;if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();},clearViewOffset:function clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var near=this.near;var top=near*Math.tan(MathUtils.DEG2RAD*0.5*this.fov)/this.zoom;var height=2*top;var width=this.aspect*height;var left=-0.5*width;var view=this.view;if(this.view!==null&&this.view.enabled){var fullWidth=view.fullWidth,fullHeight=view.fullHeight;left+=view.offsetX*width/fullWidth;top-=view.offsetY*height/fullHeight;width*=view.width/fullWidth;height*=view.height/fullHeight;}var skew=this.filmOffset;if(skew!==0)left+=near*skew/this.getFilmWidth();this.projectionMatrix.makePerspective(left,left+width,top,top-height,near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert();},toJSON:function toJSON(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.fov=this.fov;data.object.zoom=this.zoom;data.object.near=this.near;data.object.far=this.far;data.object.focus=this.focus;data.object.aspect=this.aspect;if(this.view!==null)data.object.view=Object.assign({},this.view);data.object.filmGauge=this.filmGauge;data.object.filmOffset=this.filmOffset;return data;}});var fov=90,aspect=1;function CubeCamera(near,far,renderTarget){Object3D.call(this);this.type='CubeCamera';if(renderTarget.isWebGLCubeRenderTarget!==true){console.error('THREE.CubeCamera: The constructor now expects an instance of WebGLCubeRenderTarget as third parameter.');return;}this.renderTarget=renderTarget;var cameraPX=new PerspectiveCamera(fov,aspect,near,far);cameraPX.layers=this.layers;cameraPX.up.set(0,-1,0);cameraPX.lookAt(new Vector3(1,0,0));this.add(cameraPX);var cameraNX=new PerspectiveCamera(fov,aspect,near,far);cameraNX.layers=this.layers;cameraNX.up.set(0,-1,0);cameraNX.lookAt(new Vector3(-1,0,0));this.add(cameraNX);var cameraPY=new PerspectiveCamera(fov,aspect,near,far);cameraPY.layers=this.layers;cameraPY.up.set(0,0,1);cameraPY.lookAt(new Vector3(0,1,0));this.add(cameraPY);var cameraNY=new PerspectiveCamera(fov,aspect,near,far);cameraNY.layers=this.layers;cameraNY.up.set(0,0,-1);cameraNY.lookAt(new Vector3(0,-1,0));this.add(cameraNY);var cameraPZ=new PerspectiveCamera(fov,aspect,near,far);cameraPZ.layers=this.layers;cameraPZ.up.set(0,-1,0);cameraPZ.lookAt(new Vector3(0,0,1));this.add(cameraPZ);var cameraNZ=new PerspectiveCamera(fov,aspect,near,far);cameraNZ.layers=this.layers;cameraNZ.up.set(0,-1,0);cameraNZ.lookAt(new Vector3(0,0,-1));this.add(cameraNZ);this.update=function(renderer,scene){if(this.parent===null)this.updateMatrixWorld();var currentXrEnabled=renderer.xr.enabled;var currentRenderTarget=renderer.getRenderTarget();renderer.xr.enabled=false;var generateMipmaps=renderTarget.texture.generateMipmaps;renderTarget.texture.generateMipmaps=false;renderer.setRenderTarget(renderTarget,0);renderer.render(scene,cameraPX);renderer.setRenderTarget(renderTarget,1);renderer.render(scene,cameraNX);renderer.setRenderTarget(renderTarget,2);renderer.render(scene,cameraPY);renderer.setRenderTarget(renderTarget,3);renderer.render(scene,cameraNY);renderer.setRenderTarget(renderTarget,4);renderer.render(scene,cameraPZ);renderTarget.texture.generateMipmaps=generateMipmaps;renderer.setRenderTarget(renderTarget,5);renderer.render(scene,cameraNZ);renderer.setRenderTarget(currentRenderTarget);renderer.xr.enabled=currentXrEnabled;};}CubeCamera.prototype=Object.create(Object3D.prototype);CubeCamera.prototype.constructor=CubeCamera;function CubeTexture(images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding){images=images!==undefined?images:[];mapping=mapping!==undefined?mapping:CubeReflectionMapping;format=format!==undefined?format:RGBFormat;Texture.call(this,images,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.flipY=false;// Why CubeTexture._needsFlipEnvMap is necessary:
  3057. //
  3058. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  3059. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  3060. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  3061. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  3062. // and the flag _needsFlipEnvMap controls this conversion. The flip is not required (and thus _needsFlipEnvMap is set to false)
  3063. // when using WebGLCubeRenderTarget.texture as a cube texture.
  3064. this._needsFlipEnvMap=true;}CubeTexture.prototype=Object.create(Texture.prototype);CubeTexture.prototype.constructor=CubeTexture;CubeTexture.prototype.isCubeTexture=true;Object.defineProperty(CubeTexture.prototype,'images',{get:function get(){return this.image;},set:function set(value){this.image=value;}});function WebGLCubeRenderTarget(size,options,dummy){if(Number.isInteger(options)){console.warn('THREE.WebGLCubeRenderTarget: constructor signature is now WebGLCubeRenderTarget( size, options )');options=dummy;}WebGLRenderTarget.call(this,size,size,options);options=options||{};this.texture=new CubeTexture(undefined,options.mapping,options.wrapS,options.wrapT,options.magFilter,options.minFilter,options.format,options.type,options.anisotropy,options.encoding);this.texture._needsFlipEnvMap=false;}WebGLCubeRenderTarget.prototype=Object.create(WebGLRenderTarget.prototype);WebGLCubeRenderTarget.prototype.constructor=WebGLCubeRenderTarget;WebGLCubeRenderTarget.prototype.isWebGLCubeRenderTarget=true;WebGLCubeRenderTarget.prototype.fromEquirectangularTexture=function(renderer,texture){this.texture.type=texture.type;this.texture.format=RGBAFormat;// see #18859
  3065. this.texture.encoding=texture.encoding;this.texture.generateMipmaps=texture.generateMipmaps;this.texture.minFilter=texture.minFilter;this.texture.magFilter=texture.magFilter;var shader={uniforms:{tEquirect:{value:null}},vertexShader:/* glsl */"\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t#include <begin_vertex>\n\t\t\t\t#include <project_vertex>\n\n\t\t\t}\n\t\t",fragmentShader:/* glsl */"\n\n\t\t\tuniform sampler2D tEquirect;\n\n\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t}\n\t\t"};var geometry=new BoxBufferGeometry(5,5,5);var material=new ShaderMaterial({name:'CubemapFromEquirect',uniforms:cloneUniforms(shader.uniforms),vertexShader:shader.vertexShader,fragmentShader:shader.fragmentShader,side:BackSide,blending:NoBlending});material.uniforms.tEquirect.value=texture;var mesh=new Mesh(geometry,material);var currentMinFilter=texture.minFilter;// Avoid blurred poles
  3066. if(texture.minFilter===LinearMipmapLinearFilter)texture.minFilter=LinearFilter;var camera=new CubeCamera(1,10,this);camera.update(renderer,mesh);texture.minFilter=currentMinFilter;mesh.geometry.dispose();mesh.material.dispose();return this;};WebGLCubeRenderTarget.prototype.clear=function(renderer,color,depth,stencil){var currentRenderTarget=renderer.getRenderTarget();for(var _i64=0;_i64<6;_i64++){renderer.setRenderTarget(this,_i64);renderer.clear(color,depth,stencil);}renderer.setRenderTarget(currentRenderTarget);};function DataTexture(data,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={data:data||null,width:width||1,height:height||1};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.generateMipmaps=false;this.flipY=false;this.unpackAlignment=1;this.needsUpdate=true;}DataTexture.prototype=Object.create(Texture.prototype);DataTexture.prototype.constructor=DataTexture;DataTexture.prototype.isDataTexture=true;var _sphere$1=/*@__PURE__*/new Sphere();var _vector$5=/*@__PURE__*/new Vector3();class Frustum{constructor(p0,p1,p2,p3,p4,p5){this.planes=[p0!==undefined?p0:new Plane(),p1!==undefined?p1:new Plane(),p2!==undefined?p2:new Plane(),p3!==undefined?p3:new Plane(),p4!==undefined?p4:new Plane(),p5!==undefined?p5:new Plane()];}set(p0,p1,p2,p3,p4,p5){var planes=this.planes;planes[0].copy(p0);planes[1].copy(p1);planes[2].copy(p2);planes[3].copy(p3);planes[4].copy(p4);planes[5].copy(p5);return this;}clone(){return new this.constructor().copy(this);}copy(frustum){var planes=this.planes;for(var _i65=0;_i65<6;_i65++){planes[_i65].copy(frustum.planes[_i65]);}return this;}setFromProjectionMatrix(m){var planes=this.planes;var me=m.elements;var me0=me[0],me1=me[1],me2=me[2],me3=me[3];var me4=me[4],me5=me[5],me6=me[6],me7=me[7];var me8=me[8],me9=me[9],me10=me[10],me11=me[11];var me12=me[12],me13=me[13],me14=me[14],me15=me[15];planes[0].setComponents(me3-me0,me7-me4,me11-me8,me15-me12).normalize();planes[1].setComponents(me3+me0,me7+me4,me11+me8,me15+me12).normalize();planes[2].setComponents(me3+me1,me7+me5,me11+me9,me15+me13).normalize();planes[3].setComponents(me3-me1,me7-me5,me11-me9,me15-me13).normalize();planes[4].setComponents(me3-me2,me7-me6,me11-me10,me15-me14).normalize();planes[5].setComponents(me3+me2,me7+me6,me11+me10,me15+me14).normalize();return this;}intersectsObject(object){var geometry=object.geometry;if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$1.copy(geometry.boundingSphere).applyMatrix4(object.matrixWorld);return this.intersectsSphere(_sphere$1);}intersectsSprite(sprite){_sphere$1.center.set(0,0,0);_sphere$1.radius=0.7071067811865476;_sphere$1.applyMatrix4(sprite.matrixWorld);return this.intersectsSphere(_sphere$1);}intersectsSphere(sphere){var planes=this.planes;var center=sphere.center;var negRadius=-sphere.radius;for(var _i66=0;_i66<6;_i66++){var distance=planes[_i66].distanceToPoint(center);if(distance<negRadius){return false;}}return true;}intersectsBox(box){var planes=this.planes;for(var _i67=0;_i67<6;_i67++){var plane=planes[_i67];// corner at max distance
  3067. _vector$5.x=plane.normal.x>0?box.max.x:box.min.x;_vector$5.y=plane.normal.y>0?box.max.y:box.min.y;_vector$5.z=plane.normal.z>0?box.max.z:box.min.z;if(plane.distanceToPoint(_vector$5)<0){return false;}}return true;}containsPoint(point){var planes=this.planes;for(var _i68=0;_i68<6;_i68++){if(planes[_i68].distanceToPoint(point)<0){return false;}}return true;}}function WebGLAnimation(){var context=null;var isAnimating=false;var animationLoop=null;var requestId=null;function onAnimationFrame(time,frame){animationLoop(time,frame);requestId=context.requestAnimationFrame(onAnimationFrame);}return {start:function start(){if(isAnimating===true)return;if(animationLoop===null)return;requestId=context.requestAnimationFrame(onAnimationFrame);isAnimating=true;},stop:function stop(){context.cancelAnimationFrame(requestId);isAnimating=false;},setAnimationLoop:function setAnimationLoop(callback){animationLoop=callback;},setContext:function setContext(value){context=value;}};}function WebGLAttributes(gl,capabilities){var isWebGL2=capabilities.isWebGL2;var buffers=new WeakMap();function createBuffer(attribute,bufferType){var array=attribute.array;var usage=attribute.usage;var buffer=gl.createBuffer();gl.bindBuffer(bufferType,buffer);gl.bufferData(bufferType,array,usage);attribute.onUploadCallback();var type=5126;if(array instanceof Float32Array){type=5126;}else if(array instanceof Float64Array){console.warn('THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.');}else if(array instanceof Uint16Array){if(attribute.isFloat16BufferAttribute){if(isWebGL2){type=5131;}else {console.warn('THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.');}}else {type=5123;}}else if(array instanceof Int16Array){type=5122;}else if(array instanceof Uint32Array){type=5125;}else if(array instanceof Int32Array){type=5124;}else if(array instanceof Int8Array){type=5120;}else if(array instanceof Uint8Array){type=5121;}return {buffer:buffer,type:type,bytesPerElement:array.BYTES_PER_ELEMENT,version:attribute.version};}function updateBuffer(buffer,attribute,bufferType){var array=attribute.array;var updateRange=attribute.updateRange;gl.bindBuffer(bufferType,buffer);if(updateRange.count===-1){// Not using update ranges
  3068. gl.bufferSubData(bufferType,0,array);}else {if(isWebGL2){gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array,updateRange.offset,updateRange.count);}else {gl.bufferSubData(bufferType,updateRange.offset*array.BYTES_PER_ELEMENT,array.subarray(updateRange.offset,updateRange.offset+updateRange.count));}updateRange.count=-1;// reset range
  3069. }}//
  3070. function get(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;return buffers.get(attribute);}function remove(attribute){if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data){gl.deleteBuffer(data.buffer);buffers.delete(attribute);}}function update(attribute,bufferType){if(attribute.isGLBufferAttribute){var cached=buffers.get(attribute);if(!cached||cached.version<attribute.version){buffers.set(attribute,{buffer:attribute.buffer,type:attribute.type,bytesPerElement:attribute.elementSize,version:attribute.version});}return;}if(attribute.isInterleavedBufferAttribute)attribute=attribute.data;var data=buffers.get(attribute);if(data===undefined){buffers.set(attribute,createBuffer(attribute,bufferType));}else if(data.version<attribute.version){updateBuffer(data.buffer,attribute,bufferType);data.version=attribute.version;}}return {get:get,remove:remove,update:update};}class PlaneBufferGeometry extends BufferGeometry{constructor(){var width=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var widthSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var heightSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;super();this.type='PlaneBufferGeometry';this.parameters={width:width,height:height,widthSegments:widthSegments,heightSegments:heightSegments};var width_half=width/2;var height_half=height/2;var gridX=Math.floor(widthSegments);var gridY=Math.floor(heightSegments);var gridX1=gridX+1;var gridY1=gridY+1;var segment_width=width/gridX;var segment_height=height/gridY;//
  3071. var indices=[];var vertices=[];var normals=[];var uvs=[];for(var iy=0;iy<gridY1;iy++){var y=iy*segment_height-height_half;for(var ix=0;ix<gridX1;ix++){var x=ix*segment_width-width_half;vertices.push(x,-y,0);normals.push(0,0,1);uvs.push(ix/gridX);uvs.push(1-iy/gridY);}}for(var _iy2=0;_iy2<gridY;_iy2++){for(var _ix2=0;_ix2<gridX;_ix2++){var a=_ix2+gridX1*_iy2;var b=_ix2+gridX1*(_iy2+1);var c=_ix2+1+gridX1*(_iy2+1);var d=_ix2+1+gridX1*_iy2;indices.push(a,b,d);indices.push(b,c,d);}}this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}var alphamap_fragment="#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";var alphamap_pars_fragment="#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";var alphatest_fragment="#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif";var aomap_fragment="#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif";var aomap_pars_fragment="#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";var begin_vertex="vec3 transformed = vec3( position );";var beginnormal_vertex="vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";var bsdfs="vec2 integrateSpecularBRDF( const in float dotNV, const in float roughness ) {\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\treturn vec2( -1.04, 1.04 ) * a004 + r.zw;\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n#else\n\tif( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t}\n\treturn 1.0;\n#endif\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nvec3 F_Schlick_RoughnessDependent( const in vec3 F0, const in float dotNV, const in float roughness ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotNV - 6.98316 ) * dotNV );\n\tvec3 Fr = max( vec3( 1.0 - roughness ), F0 ) - F0;\n\treturn Fr * fresnel + F0;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + viewDir );\n\tfloat dotNL = saturate( dot( normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nvec3 BRDF_Specular_GGX_Environment( const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\treturn specularColor * brdf.x + brdf.y;\n}\nvoid BRDF_Specular_Multiscattering_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tvec3 F = F_Schlick_RoughnessDependent( specularColor, dotNV, roughness );\n\tvec2 brdf = integrateSpecularBRDF( dotNV, roughness );\n\tvec3 FssEss = F * brdf.x + brdf.y;\n\tfloat Ess = brdf.x + brdf.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = specularColor + ( 1.0 - specularColor ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie(float roughness, float NoH) {\n\tfloat invAlpha = 1.0 / roughness;\n\tfloat cos2h = NoH * NoH;\n\tfloat sin2h = max(1.0 - cos2h, 0.0078125);\treturn (2.0 + invAlpha) * pow(sin2h, invAlpha * 0.5) / (2.0 * PI);\n}\nfloat V_Neubelt(float NoV, float NoL) {\n\treturn saturate(1.0 / (4.0 * (NoL + NoV - NoL * NoV)));\n}\nvec3 BRDF_Specular_Sheen( const in float roughness, const in vec3 L, const in GeometricContext geometry, vec3 specularColor ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 H = normalize( V + L );\n\tfloat dotNH = saturate( dot( N, H ) );\n\treturn specularColor * D_Charlie( roughness, dotNH ) * V_Neubelt( dot(N, V), dot(N, L) );\n}\n#endif";var bumpmap_pars_fragment="#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tfDet *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";var clipping_planes_fragment="#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\tplane = clippingPlanes[ i ];\n\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t#pragma unroll_loop_end\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\tif ( clipped ) discard;\n\t#endif\n#endif";var clipping_planes_pars_fragment="#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";var clipping_planes_pars_vertex="#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";var clipping_planes_vertex="#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";var color_fragment="#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";var color_pars_fragment="#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";var color_pars_vertex="#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvarying vec3 vColor;\n#endif";var color_vertex="#if defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor.xyz *= color.xyz;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif";var common="#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat max3( vec3 v ) { return max( max( v.x, v.y ), v.z ); }\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat linearToRelativeLuminance( const in vec3 color ) {\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\n\treturn dot( weights, color.rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";var cube_uv_reflection_fragment="#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_maxMipLevel 8.0\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_maxTileSize 256.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\tfloat texelSize = 1.0 / ( 3.0 * cubeUV_maxTileSize );\n\t\tvec2 uv = getUV( direction, face ) * ( faceSize - 1.0 );\n\t\tvec2 f = fract( uv );\n\t\tuv += 0.5 - f;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tif ( mipInt < cubeUV_maxMipLevel ) {\n\t\t\tuv.y += 2.0 * cubeUV_maxTileSize;\n\t\t}\n\t\tuv.y += filterInt * 2.0 * cubeUV_minTileSize;\n\t\tuv.x += 3.0 * max( 0.0, cubeUV_maxTileSize - 2.0 * faceSize );\n\t\tuv *= texelSize;\n\t\tvec3 tl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x += texelSize;\n\t\tvec3 tr = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.y += texelSize;\n\t\tvec3 br = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tuv.x -= texelSize;\n\t\tvec3 bl = envMapTexelToLinear( texture2D( envMap, uv ) ).rgb;\n\t\tvec3 tm = mix( tl, tr, f.x );\n\t\tvec3 bm = mix( bl, br, f.x );\n\t\treturn mix( tm, bm, f.y );\n\t}\n\t#define r0 1.0\n\t#define v0 0.339\n\t#define m0 - 2.0\n\t#define r1 0.8\n\t#define v1 0.276\n\t#define m1 - 1.0\n\t#define r4 0.4\n\t#define v4 0.046\n\t#define m4 2.0\n\t#define r5 0.305\n\t#define v5 0.016\n\t#define m5 3.0\n\t#define r6 0.21\n\t#define v6 0.0038\n\t#define m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= r1 ) {\n\t\t\tmip = ( r0 - roughness ) * ( m1 - m0 ) / ( r0 - r1 ) + m0;\n\t\t} else if ( roughness >= r4 ) {\n\t\t\tmip = ( r1 - roughness ) * ( m4 - m1 ) / ( r1 - r4 ) + m1;\n\t\t} else if ( roughness >= r5 ) {\n\t\t\tmip = ( r4 - roughness ) * ( m5 - m4 ) / ( r4 - r5 ) + m4;\n\t\t} else if ( roughness >= r6 ) {\n\t\t\tmip = ( r5 - roughness ) * ( m6 - m5 ) / ( r5 - r6 ) + m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), m0, cubeUV_maxMipLevel );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";var defaultnormal_vertex="vec3 transformedNormal = objectNormal;\n#ifdef USE_INSTANCING\n\tmat3 m = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) );\n\ttransformedNormal = m * transformedNormal;\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = ( modelViewMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";var displacementmap_pars_vertex="#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";var displacementmap_vertex="#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";var emissivemap_fragment="#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";var emissivemap_pars_fragment="#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";var encodings_fragment="gl_FragColor = linearToOutputTexel( gl_FragColor );";var encodings_pars_fragment="\nvec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( gammaFactor ) ), value.a );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n\treturn vec4( pow( value.rgb, vec3( 1.0 / gammaFactor ) ), value.a );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * value.a * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n\tM = ceil( M * 255.0 ) / 255.0;\n\treturn vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n\tfloat maxRGB = max( value.r, max( value.g, value.b ) );\n\tfloat D = max( maxRange / maxRGB, 1.0 );\n\tD = clamp( floor( D ) / 255.0, 0.0, 1.0 );\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n\tvec3 Xp_Y_XYZp = cLogLuvM * value.rgb;\n\tXp_Y_XYZp = max( Xp_Y_XYZp, vec3( 1e-6, 1e-6, 1e-6 ) );\n\tvec4 vResult;\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n\tvResult.w = fract( Le );\n\tvResult.z = ( Le - ( floor( vResult.w * 255.0 ) ) / 255.0 ) / 255.0;\n\treturn vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n\tfloat Le = value.z * 255.0 + value.w;\n\tvec3 Xp_Y_XYZp;\n\tXp_Y_XYZp.y = exp2( ( Le - 127.0 ) / 2.0 );\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n\tvec3 vRGB = cLogLuvInverseM * Xp_Y_XYZp.rgb;\n\treturn vec4( max( vRGB, 0.0 ), 1.0 );\n}";var envmap_fragment="#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifndef ENVMAP_TYPE_CUBE_UV\n\t\tenvColor = envMapTexelToLinear( envColor );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";var envmap_common_pars_fragment="#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform int maxMipLevel;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\t\n#endif";var envmap_pars_fragment="#ifdef USE_ENVMAP\n\tuniform float reflectivity;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\tvarying vec3 vWorldPosition;\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif";var envmap_pars_vertex="#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) ||defined( PHONG )\n\t\t#define ENV_WORLDPOS\n\t#endif\n\t#ifdef ENV_WORLDPOS\n\t\t\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif";var envmap_vertex="#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif";var fog_vertex="#ifdef USE_FOG\n\tfogDepth = - mvPosition.z;\n#endif";var fog_pars_vertex="#ifdef USE_FOG\n\tvarying float fogDepth;\n#endif";var fog_fragment="#ifdef USE_FOG\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = 1.0 - exp( - fogDensity * fogDensity * fogDepth * fogDepth );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif";var fog_pars_fragment="#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\tvarying float fogDepth;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";var gradientmap_pars_fragment="#ifdef USE_GRADIENTMAP\n\tuniform sampler2D gradientMap;\n#endif\nvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\tfloat dotNL = dot( normal, lightDirection );\n\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t#ifdef USE_GRADIENTMAP\n\t\treturn texture2D( gradientMap, coord ).rgb;\n\t#else\n\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t#endif\n}";var lightmap_fragment="#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\treflectedLight.indirectDiffuse += PI * lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n#endif";var lightmap_pars_fragment="#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";var lights_lambert_vertex="vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\nvIndirectFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n\tvIndirectBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\nvIndirectFront += getAmbientLightIrradiance( ambientLightColor );\nvIndirectFront += getLightProbeIrradiance( lightProbe, geometry );\n#ifdef DOUBLE_SIDED\n\tvIndirectBack += getAmbientLightIrradiance( ambientLightColor );\n\tvIndirectBack += getLightProbeIrradiance( lightProbe, backGeometry );\n#endif\n#if NUM_POINT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_DIR_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvIndirectFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvIndirectBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n\t#pragma unroll_loop_end\n#endif";var lights_pars_begin="uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in GeometricContext geometry ) {\n\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif";var envmap_physical_pars_fragment="#if defined( USE_ENVMAP )\n\t#ifdef ENVMAP_MODE_REFRACTION\n\t\tuniform float refractionRatio;\n\t#endif\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float roughness, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat sigma = PI * roughness * roughness / ( 1.0 + roughness );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + log2( sigma );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -viewDir, normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( roughness, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif";var lights_toon_fragment="ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";var lights_toon_pars_fragment="varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in GeometricContext geometry, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon\n#define Material_LightProbeLOD( material )\t(0)";var lights_phong_fragment="BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";var lights_phong_pars_fragment="varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)";var lights_physical_fragment="PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.specularRoughness = max( roughnessFactor, 0.0525 );material.specularRoughness += geometryRoughness;\nmaterial.specularRoughness = min( material.specularRoughness, 1.0 );\n#ifdef REFLECTIVITY\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#endif\n#ifdef CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheen;\n#endif";var lights_physical_pars_fragment="struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n#ifdef CLEARCOAT\n\tfloat clearcoat;\n\tfloat clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tvec3 sheenColor;\n#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearcoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.specularRoughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNL = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = ccDotNL * directLight.color;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tccIrradiance *= PI;\n\t\t#endif\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t\treflectedLight.directSpecular += ccIrradiance * material.clearcoat * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_Sheen(\n\t\t\tmaterial.specularRoughness,\n\t\t\tdirectLight.direction,\n\t\t\tgeometry,\n\t\t\tmaterial.sheenColor\n\t\t);\n\t#else\n\t\treflectedLight.directSpecular += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry.viewDir, geometry.normal, material.specularColor, material.specularRoughness);\n\t#endif\n\treflectedLight.directDiffuse += ( 1.0 - clearcoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef CLEARCOAT\n\t\tfloat ccDotNV = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular += clearcoatRadiance * material.clearcoat * BRDF_Specular_GGX_Environment( geometry.viewDir, geometry.clearcoatNormal, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearcoatRoughness );\n\t\tfloat ccDotNL = ccDotNV;\n\t\tfloat clearcoatDHR = material.clearcoat * clearcoatDHRApprox( material.clearcoatRoughness, ccDotNL );\n\t#else\n\t\tfloat clearcoatDHR = 0.0;\n\t#endif\n\tfloat clearcoatInv = 1.0 - clearcoatDHR;\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tBRDF_Specular_Multiscattering_Environment( geometry, material.specularColor, material.specularRoughness, singleScattering, multiScattering );\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - ( singleScattering + multiScattering ) );\n\treflectedLight.indirectSpecular += clearcoatInv * radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";var lights_fragment_begin="\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\n#ifdef CLEARCOAT\n\tgeometry.clearcoatNormal = clearcoatNormal;\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\tirradiance += getLightProbeIrradiance( lightProbe, geometry );\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";var lights_fragment_maps="#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getLightProbeIndirectIrradiance( geometry, maxMipLevel );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.normal, material.specularRoughness, maxMipLevel );\n\t#ifdef CLEARCOAT\n\t\tclearcoatRadiance += getLightProbeIndirectRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness, maxMipLevel );\n\t#endif\n#endif";var lights_fragment_end="#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometry, material, reflectedLight );\n#endif";var logdepthbuf_fragment="#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tgl_FragDepthEXT = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";var logdepthbuf_pars_fragment="#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";var logdepthbuf_pars_vertex="#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t\tvarying float vIsPerspective;\n\t#else\n\t\tuniform float logDepthBufFC;\n\t#endif\n#endif";var logdepthbuf_vertex="#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n\t#else\n\t\tif ( isPerspectiveMatrix( projectionMatrix ) ) {\n\t\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\n\t\t\tgl_Position.z *= gl_Position.w;\n\t\t}\n\t#endif\n#endif";var map_fragment="#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif";var map_pars_fragment="#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";var map_particle_fragment="#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, uv );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";var map_particle_pars_fragment="#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";var metalnessmap_fragment="float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";var metalnessmap_pars_fragment="#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";var morphnormal_vertex="#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tobjectNormal += morphNormal0 * morphTargetInfluences[ 0 ];\n\tobjectNormal += morphNormal1 * morphTargetInfluences[ 1 ];\n\tobjectNormal += morphNormal2 * morphTargetInfluences[ 2 ];\n\tobjectNormal += morphNormal3 * morphTargetInfluences[ 3 ];\n#endif";var morphtarget_pars_vertex="#ifdef USE_MORPHTARGETS\n\tuniform float morphTargetBaseInfluence;\n\t#ifndef USE_MORPHNORMALS\n\t\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\t\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";var morphtarget_vertex="#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\ttransformed += morphTarget0 * morphTargetInfluences[ 0 ];\n\ttransformed += morphTarget1 * morphTargetInfluences[ 1 ];\n\ttransformed += morphTarget2 * morphTargetInfluences[ 2 ];\n\ttransformed += morphTarget3 * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\t\ttransformed += morphTarget4 * morphTargetInfluences[ 4 ];\n\t\ttransformed += morphTarget5 * morphTargetInfluences[ 5 ];\n\t\ttransformed += morphTarget6 * morphTargetInfluences[ 6 ];\n\t\ttransformed += morphTarget7 * morphTargetInfluences[ 7 ];\n\t#endif\n#endif";var normal_fragment_begin="#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t\tbitangent = bitangent * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";var normal_fragment_maps="#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( -vViewPosition, normal, mapN );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif";var normalmap_pars_fragment="#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN ) {\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tfloat scale = sign( st1.t * st0.s - st0.t * st1.s );\n\t\tvec3 S = normalize( ( q0 * st1.t - q1 * st0.t ) * scale );\n\t\tvec3 T = normalize( ( - q0 * st1.s + q1 * st0.s ) * scale );\n\t\tvec3 N = normalize( surf_norm );\n\t\tmat3 tsn = mat3( S, T, N );\n\t\tmapN.xy *= ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif";var clearcoat_normal_fragment_begin="#ifdef CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";var clearcoat_normal_fragment_maps="#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN );\n\t#endif\n#endif";var clearcoat_pars_fragment="#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";var packing="vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ));\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w);\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";var premultiplied_alpha_fragment="#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";var project_vertex="vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";var dithering_fragment="#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";var dithering_pars_fragment="#ifdef DITHERING\n\tvec3 dithering( vec3 color ) {\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\n\t\treturn color + dither_shift_RGB;\n\t}\n#endif";var roughnessmap_fragment="float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";var roughnessmap_pars_fragment="#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";var shadowmap_pars_fragment="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ), \n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";var shadowmap_pars_vertex="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";var shadowmap_vertex="#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";var shadowmask_pars_fragment="float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";var skinbase_vertex="#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";var skinning_pars_vertex="#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform highp sampler2D boneTexture;\n\t\tuniform int boneTextureSize;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif";var skinning_vertex="#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\n#endif";var skinnormal_vertex="#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n\t#ifdef USE_TANGENT\n\t\tobjectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;\n\t#endif\n#endif";var specularmap_fragment="float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";var specularmap_pars_fragment="#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";var tonemapping_fragment="#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";var tonemapping_pars_fragment="#ifndef saturate\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";var transmissionmap_fragment="#ifdef USE_TRANSMISSIONMAP\n\ttotalTransmission *= texture2D( transmissionMap, vUv ).r;\n#endif";var transmissionmap_pars_fragment="#ifdef USE_TRANSMISSIONMAP\n\tuniform sampler2D transmissionMap;\n#endif";var uv_pars_fragment="#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";var uv_pars_vertex="#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";var uv_vertex="#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";var uv2_pars_fragment="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";var uv2_pars_vertex="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";var uv2_vertex="#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";var worldpos_vertex="#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";var background_frag="uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";var background_vert="varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";var cube_frag="#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";var cube_vert="varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";var depth_frag="#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";var depth_vert="#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";var distanceRGBA_frag="#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";var distanceRGBA_vert="#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";var equirect_frag="uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tvec4 texColor = texture2D( tEquirect, sampleUV );\n\tgl_FragColor = mapTexelToLinear( texColor );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";var equirect_vert="varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}";var linedashed_frag="uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";var linedashed_vert="uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";var meshbasic_frag="uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\n\t\tvec4 lightMapTexel= texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexelToLinear( lightMapTexel ).rgb * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshbasic_vert="#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";var meshlambert_frag="uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.indirectDiffuse += ( gl_FrontFacing ) ? vIndirectFront : vIndirectBack;\n\t#else\n\t\treflectedLight.indirectDiffuse += vIndirectFront;\n\t#endif\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshlambert_vert="#define LAMBERT\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";var meshmatcap_frag="#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t\tmatcapColor = matcapTexelToLinear( matcapColor );\n\t#else\n\t\tvec4 matcapColor = vec4( 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshmatcap_vert="#define MATCAP\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#ifndef FLAT_SHADED\n\t\tvNormal = normalize( transformedNormal );\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";var meshtoon_frag="#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshtoon_vert="#define TOON\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";var meshphong_frag="#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <cube_uv_reflection_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshphong_vert="#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";var meshphysical_frag="#define STANDARD\n#ifdef PHYSICAL\n\t#define REFLECTIVITY\n\t#define CLEARCOAT\n\t#define TRANSMISSION\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef TRANSMISSION\n\tuniform float transmission;\n#endif\n#ifdef REFLECTIVITY\n\tuniform float reflectivity;\n#endif\n#ifdef CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheen;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <transmissionmap_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#ifdef TRANSMISSION\n\t\tfloat totalTransmission = transmission;\n\t#endif\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <transmissionmap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#ifdef TRANSMISSION\n\t\tdiffuseColor.a *= mix( saturate( 1. - totalTransmission + linearToRelativeLuminance( reflectedLight.directSpecular + reflectedLight.indirectSpecular ) ), 1.0, metalness );\n\t#endif\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";var meshphysical_vert="#define STANDARD\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";var normal_frag="#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n}";var normal_vert="#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n\t#ifdef USE_TANGENT\n\t\tvarying vec3 vTangent;\n\t\tvarying vec3 vBitangent;\n\t#endif\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n\t#ifdef USE_TANGENT\n\t\tvTangent = normalize( transformedTangent );\n\t\tvBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );\n\t#endif\n#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";var points_frag="uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";var points_vert="uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";var shadow_frag="uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";var shadow_vert="#include <common>\n#include <fog_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";var sprite_frag="uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";var sprite_vert="uniform float rotation;\nuniform vec2 center;\n#include <common>\n#include <uv_pars_vertex>\n#include <fog_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\tvec4 mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\n\tvec2 scale;\n\tscale.x = length( vec3( modelMatrix[ 0 ].x, modelMatrix[ 0 ].y, modelMatrix[ 0 ].z ) );\n\tscale.y = length( vec3( modelMatrix[ 1 ].x, modelMatrix[ 1 ].y, modelMatrix[ 1 ].z ) );\n\t#ifndef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) scale *= - mvPosition.z;\n\t#endif\n\tvec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;\n\tvec2 rotatedPosition;\n\trotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;\n\trotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;\n\tmvPosition.xy += rotatedPosition;\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";var ShaderChunk={alphamap_fragment:alphamap_fragment,alphamap_pars_fragment:alphamap_pars_fragment,alphatest_fragment:alphatest_fragment,aomap_fragment:aomap_fragment,aomap_pars_fragment:aomap_pars_fragment,begin_vertex:begin_vertex,beginnormal_vertex:beginnormal_vertex,bsdfs:bsdfs,bumpmap_pars_fragment:bumpmap_pars_fragment,clipping_planes_fragment:clipping_planes_fragment,clipping_planes_pars_fragment:clipping_planes_pars_fragment,clipping_planes_pars_vertex:clipping_planes_pars_vertex,clipping_planes_vertex:clipping_planes_vertex,color_fragment:color_fragment,color_pars_fragment:color_pars_fragment,color_pars_vertex:color_pars_vertex,color_vertex:color_vertex,common:common,cube_uv_reflection_fragment:cube_uv_reflection_fragment,defaultnormal_vertex:defaultnormal_vertex,displacementmap_pars_vertex:displacementmap_pars_vertex,displacementmap_vertex:displacementmap_vertex,emissivemap_fragment:emissivemap_fragment,emissivemap_pars_fragment:emissivemap_pars_fragment,encodings_fragment:encodings_fragment,encodings_pars_fragment:encodings_pars_fragment,envmap_fragment:envmap_fragment,envmap_common_pars_fragment:envmap_common_pars_fragment,envmap_pars_fragment:envmap_pars_fragment,envmap_pars_vertex:envmap_pars_vertex,envmap_physical_pars_fragment:envmap_physical_pars_fragment,envmap_vertex:envmap_vertex,fog_vertex:fog_vertex,fog_pars_vertex:fog_pars_vertex,fog_fragment:fog_fragment,fog_pars_fragment:fog_pars_fragment,gradientmap_pars_fragment:gradientmap_pars_fragment,lightmap_fragment:lightmap_fragment,lightmap_pars_fragment:lightmap_pars_fragment,lights_lambert_vertex:lights_lambert_vertex,lights_pars_begin:lights_pars_begin,lights_toon_fragment:lights_toon_fragment,lights_toon_pars_fragment:lights_toon_pars_fragment,lights_phong_fragment:lights_phong_fragment,lights_phong_pars_fragment:lights_phong_pars_fragment,lights_physical_fragment:lights_physical_fragment,lights_physical_pars_fragment:lights_physical_pars_fragment,lights_fragment_begin:lights_fragment_begin,lights_fragment_maps:lights_fragment_maps,lights_fragment_end:lights_fragment_end,logdepthbuf_fragment:logdepthbuf_fragment,logdepthbuf_pars_fragment:logdepthbuf_pars_fragment,logdepthbuf_pars_vertex:logdepthbuf_pars_vertex,logdepthbuf_vertex:logdepthbuf_vertex,map_fragment:map_fragment,map_pars_fragment:map_pars_fragment,map_particle_fragment:map_particle_fragment,map_particle_pars_fragment:map_particle_pars_fragment,metalnessmap_fragment:metalnessmap_fragment,metalnessmap_pars_fragment:metalnessmap_pars_fragment,morphnormal_vertex:morphnormal_vertex,morphtarget_pars_vertex:morphtarget_pars_vertex,morphtarget_vertex:morphtarget_vertex,normal_fragment_begin:normal_fragment_begin,normal_fragment_maps:normal_fragment_maps,normalmap_pars_fragment:normalmap_pars_fragment,clearcoat_normal_fragment_begin:clearcoat_normal_fragment_begin,clearcoat_normal_fragment_maps:clearcoat_normal_fragment_maps,clearcoat_pars_fragment:clearcoat_pars_fragment,packing:packing,premultiplied_alpha_fragment:premultiplied_alpha_fragment,project_vertex:project_vertex,dithering_fragment:dithering_fragment,dithering_pars_fragment:dithering_pars_fragment,roughnessmap_fragment:roughnessmap_fragment,roughnessmap_pars_fragment:roughnessmap_pars_fragment,shadowmap_pars_fragment:shadowmap_pars_fragment,shadowmap_pars_vertex:shadowmap_pars_vertex,shadowmap_vertex:shadowmap_vertex,shadowmask_pars_fragment:shadowmask_pars_fragment,skinbase_vertex:skinbase_vertex,skinning_pars_vertex:skinning_pars_vertex,skinning_vertex:skinning_vertex,skinnormal_vertex:skinnormal_vertex,specularmap_fragment:specularmap_fragment,specularmap_pars_fragment:specularmap_pars_fragment,tonemapping_fragment:tonemapping_fragment,tonemapping_pars_fragment:tonemapping_pars_fragment,transmissionmap_fragment:transmissionmap_fragment,transmissionmap_pars_fragment:transmissionmap_pars_fragment,uv_pars_fragment:uv_pars_fragment,uv_pars_vertex:uv_pars_vertex,uv_vertex:uv_vertex,uv2_pars_fragment:uv2_pars_fragment,uv2_pars_vertex:uv2_pars_vertex,uv2_vertex:uv2_vertex,worldpos_vertex:worldpos_vertex,background_frag:background_frag,background_vert:background_vert,cube_frag:cube_frag,cube_vert:cube_vert,depth_frag:depth_frag,depth_vert:depth_vert,distanceRGBA_frag:distanceRGBA_frag,distanceRGBA_vert:distanceRGBA_vert,equirect_frag:equirect_frag,equirect_vert:equirect_vert,linedashed_frag:linedashed_frag,linedashed_vert:linedashed_vert,meshbasic_frag:meshbasic_frag,meshbasic_vert:meshbasic_vert,meshlambert_frag:meshlambert_frag,meshlambert_vert:meshlambert_vert,meshmatcap_frag:meshmatcap_frag,meshmatcap_vert:meshmatcap_vert,meshtoon_frag:meshtoon_frag,meshtoon_vert:meshtoon_vert,meshphong_frag:meshphong_frag,meshphong_vert:meshphong_vert,meshphysical_frag:meshphysical_frag,meshphysical_vert:meshphysical_vert,normal_frag:normal_frag,normal_vert:normal_vert,points_frag:points_frag,points_vert:points_vert,shadow_frag:shadow_frag,shadow_vert:shadow_vert,sprite_frag:sprite_frag,sprite_vert:sprite_vert};/**
  3072. * Uniforms library for shared webgl shaders
  3073. */var UniformsLib={common:{diffuse:{value:new Color(0xeeeeee)},opacity:{value:1.0},map:{value:null},uvTransform:{value:new Matrix3()},uv2Transform:{value:new Matrix3()},alphaMap:{value:null}},specularmap:{specularMap:{value:null}},envmap:{envMap:{value:null},flipEnvMap:{value:-1},reflectivity:{value:1.0},refractionRatio:{value:0.98},maxMipLevel:{value:0}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1}},emissivemap:{emissiveMap:{value:null}},bumpmap:{bumpMap:{value:null},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalScale:{value:new Vector2(1,1)}},displacementmap:{displacementMap:{value:null},displacementScale:{value:1},displacementBias:{value:0}},roughnessmap:{roughnessMap:{value:null}},metalnessmap:{metalnessMap:{value:null}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:0.00025},fogNear:{value:1},fogFar:{value:2000},fogColor:{value:new Color(0xffffff)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotShadowMap:{value:[]},spotShadowMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},// TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  3074. rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new Color(0xeeeeee)},opacity:{value:1.0},size:{value:1.0},scale:{value:1.0},map:{value:null},alphaMap:{value:null},uvTransform:{value:new Matrix3()}},sprite:{diffuse:{value:new Color(0xeeeeee)},opacity:{value:1.0},center:{value:new Vector2(0.5,0.5)},rotation:{value:0.0},map:{value:null},alphaMap:{value:null},uvTransform:{value:new Matrix3()}}};var ShaderLib={basic:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.fog]),vertexShader:ShaderChunk.meshbasic_vert,fragmentShader:ShaderChunk.meshbasic_frag},lambert:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0x000000)}}]),vertexShader:ShaderChunk.meshlambert_vert,fragmentShader:ShaderChunk.meshlambert_frag},phong:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.specularmap,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0x000000)},specular:{value:new Color(0x111111)},shininess:{value:30}}]),vertexShader:ShaderChunk.meshphong_vert,fragmentShader:ShaderChunk.meshphong_frag},standard:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.envmap,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.roughnessmap,UniformsLib.metalnessmap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0x000000)},roughness:{value:1.0},metalness:{value:0.0},envMapIntensity:{value:1}// temporary
  3075. }]),vertexShader:ShaderChunk.meshphysical_vert,fragmentShader:ShaderChunk.meshphysical_frag},toon:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.aomap,UniformsLib.lightmap,UniformsLib.emissivemap,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.gradientmap,UniformsLib.fog,UniformsLib.lights,{emissive:{value:new Color(0x000000)}}]),vertexShader:ShaderChunk.meshtoon_vert,fragmentShader:ShaderChunk.meshtoon_frag},matcap:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,UniformsLib.fog,{matcap:{value:null}}]),vertexShader:ShaderChunk.meshmatcap_vert,fragmentShader:ShaderChunk.meshmatcap_frag},points:{uniforms:mergeUniforms([UniformsLib.points,UniformsLib.fog]),vertexShader:ShaderChunk.points_vert,fragmentShader:ShaderChunk.points_frag},dashed:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ShaderChunk.linedashed_vert,fragmentShader:ShaderChunk.linedashed_frag},depth:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.displacementmap]),vertexShader:ShaderChunk.depth_vert,fragmentShader:ShaderChunk.depth_frag},normal:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.bumpmap,UniformsLib.normalmap,UniformsLib.displacementmap,{opacity:{value:1.0}}]),vertexShader:ShaderChunk.normal_vert,fragmentShader:ShaderChunk.normal_frag},sprite:{uniforms:mergeUniforms([UniformsLib.sprite,UniformsLib.fog]),vertexShader:ShaderChunk.sprite_vert,fragmentShader:ShaderChunk.sprite_frag},background:{uniforms:{uvTransform:{value:new Matrix3()},t2D:{value:null}},vertexShader:ShaderChunk.background_vert,fragmentShader:ShaderChunk.background_frag},/* -------------------------------------------------------------------------
  3076. // Cube map shader
  3077. ------------------------------------------------------------------------- */cube:{uniforms:mergeUniforms([UniformsLib.envmap,{opacity:{value:1.0}}]),vertexShader:ShaderChunk.cube_vert,fragmentShader:ShaderChunk.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ShaderChunk.equirect_vert,fragmentShader:ShaderChunk.equirect_frag},distanceRGBA:{uniforms:mergeUniforms([UniformsLib.common,UniformsLib.displacementmap,{referencePosition:{value:new Vector3()},nearDistance:{value:1},farDistance:{value:1000}}]),vertexShader:ShaderChunk.distanceRGBA_vert,fragmentShader:ShaderChunk.distanceRGBA_frag},shadow:{uniforms:mergeUniforms([UniformsLib.lights,UniformsLib.fog,{color:{value:new Color(0x00000)},opacity:{value:1.0}}]),vertexShader:ShaderChunk.shadow_vert,fragmentShader:ShaderChunk.shadow_frag}};ShaderLib.physical={uniforms:mergeUniforms([ShaderLib.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatNormalScale:{value:new Vector2(1,1)},clearcoatNormalMap:{value:null},sheen:{value:new Color(0x000000)},transmission:{value:0},transmissionMap:{value:null}}]),vertexShader:ShaderChunk.meshphysical_vert,fragmentShader:ShaderChunk.meshphysical_frag};function WebGLBackground(renderer,cubemaps,state,objects,premultipliedAlpha){var clearColor=new Color(0x000000);var clearAlpha=0;var planeMesh;var boxMesh;var currentBackground=null;var currentBackgroundVersion=0;var currentTonemapping=null;function render(renderList,scene,camera,forceClear){var background=scene.isScene===true?scene.background:null;if(background&&background.isTexture){background=cubemaps.get(background);}// Ignore background in AR
  3078. // TODO: Reconsider this.
  3079. var xr=renderer.xr;var session=xr.getSession&&xr.getSession();if(session&&session.environmentBlendMode==='additive'){background=null;}if(background===null){setClear(clearColor,clearAlpha);}else if(background&&background.isColor){setClear(background,1);forceClear=true;}if(renderer.autoClear||forceClear){renderer.clear(renderer.autoClearColor,renderer.autoClearDepth,renderer.autoClearStencil);}if(background&&(background.isCubeTexture||background.isWebGLCubeRenderTarget||background.mapping===CubeUVReflectionMapping)){if(boxMesh===undefined){boxMesh=new Mesh(new BoxBufferGeometry(1,1,1),new ShaderMaterial({name:'BackgroundCubeMaterial',uniforms:cloneUniforms(ShaderLib.cube.uniforms),vertexShader:ShaderLib.cube.vertexShader,fragmentShader:ShaderLib.cube.fragmentShader,side:BackSide,depthTest:false,depthWrite:false,fog:false}));boxMesh.geometry.deleteAttribute('normal');boxMesh.geometry.deleteAttribute('uv');boxMesh.onBeforeRender=function(renderer,scene,camera){this.matrixWorld.copyPosition(camera.matrixWorld);};// enable code injection for non-built-in material
  3080. Object.defineProperty(boxMesh.material,'envMap',{get:function get(){return this.uniforms.envMap.value;}});objects.update(boxMesh);}if(background.isWebGLCubeRenderTarget){// TODO Deprecate
  3081. background=background.texture;}boxMesh.material.uniforms.envMap.value=background;boxMesh.material.uniforms.flipEnvMap.value=background.isCubeTexture&&background._needsFlipEnvMap?-1:1;if(currentBackground!==background||currentBackgroundVersion!==background.version||currentTonemapping!==renderer.toneMapping){boxMesh.material.needsUpdate=true;currentBackground=background;currentBackgroundVersion=background.version;currentTonemapping=renderer.toneMapping;}// push to the pre-sorted opaque render list
  3082. renderList.unshift(boxMesh,boxMesh.geometry,boxMesh.material,0,0,null);}else if(background&&background.isTexture){if(planeMesh===undefined){planeMesh=new Mesh(new PlaneBufferGeometry(2,2),new ShaderMaterial({name:'BackgroundMaterial',uniforms:cloneUniforms(ShaderLib.background.uniforms),vertexShader:ShaderLib.background.vertexShader,fragmentShader:ShaderLib.background.fragmentShader,side:FrontSide,depthTest:false,depthWrite:false,fog:false}));planeMesh.geometry.deleteAttribute('normal');// enable code injection for non-built-in material
  3083. Object.defineProperty(planeMesh.material,'map',{get:function get(){return this.uniforms.t2D.value;}});objects.update(planeMesh);}planeMesh.material.uniforms.t2D.value=background;if(background.matrixAutoUpdate===true){background.updateMatrix();}planeMesh.material.uniforms.uvTransform.value.copy(background.matrix);if(currentBackground!==background||currentBackgroundVersion!==background.version||currentTonemapping!==renderer.toneMapping){planeMesh.material.needsUpdate=true;currentBackground=background;currentBackgroundVersion=background.version;currentTonemapping=renderer.toneMapping;}// push to the pre-sorted opaque render list
  3084. renderList.unshift(planeMesh,planeMesh.geometry,planeMesh.material,0,0,null);}}function setClear(color,alpha){state.buffers.color.setClear(color.r,color.g,color.b,alpha,premultipliedAlpha);}return {getClearColor:function getClearColor(){return clearColor;},setClearColor:function setClearColor(color){var alpha=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;clearColor.set(color);clearAlpha=alpha;setClear(clearColor,clearAlpha);},getClearAlpha:function getClearAlpha(){return clearAlpha;},setClearAlpha:function setClearAlpha(alpha){clearAlpha=alpha;setClear(clearColor,clearAlpha);},render:render};}function WebGLBindingStates(gl,extensions,attributes,capabilities){var maxVertexAttributes=gl.getParameter(34921);var extension=capabilities.isWebGL2?null:extensions.get('OES_vertex_array_object');var vaoAvailable=capabilities.isWebGL2||extension!==null;var bindingStates={};var defaultState=createBindingState(null);var currentState=defaultState;function setup(object,material,program,geometry,index){var updateBuffers=false;if(vaoAvailable){var state=getBindingState(geometry,program,material);if(currentState!==state){currentState=state;bindVertexArrayObject(currentState.object);}updateBuffers=needsUpdate(geometry,index);if(updateBuffers)saveCache(geometry,index);}else {var wireframe=material.wireframe===true;if(currentState.geometry!==geometry.id||currentState.program!==program.id||currentState.wireframe!==wireframe){currentState.geometry=geometry.id;currentState.program=program.id;currentState.wireframe=wireframe;updateBuffers=true;}}if(object.isInstancedMesh===true){updateBuffers=true;}if(index!==null){attributes.update(index,34963);}if(updateBuffers){setupVertexAttributes(object,material,program,geometry);if(index!==null){gl.bindBuffer(34963,attributes.get(index).buffer);}}}function createVertexArrayObject(){if(capabilities.isWebGL2)return gl.createVertexArray();return extension.createVertexArrayOES();}function bindVertexArrayObject(vao){if(capabilities.isWebGL2)return gl.bindVertexArray(vao);return extension.bindVertexArrayOES(vao);}function deleteVertexArrayObject(vao){if(capabilities.isWebGL2)return gl.deleteVertexArray(vao);return extension.deleteVertexArrayOES(vao);}function getBindingState(geometry,program,material){var wireframe=material.wireframe===true;var programMap=bindingStates[geometry.id];if(programMap===undefined){programMap={};bindingStates[geometry.id]=programMap;}var stateMap=programMap[program.id];if(stateMap===undefined){stateMap={};programMap[program.id]=stateMap;}var state=stateMap[wireframe];if(state===undefined){state=createBindingState(createVertexArrayObject());stateMap[wireframe]=state;}return state;}function createBindingState(vao){var newAttributes=[];var enabledAttributes=[];var attributeDivisors=[];for(var _i69=0;_i69<maxVertexAttributes;_i69++){newAttributes[_i69]=0;enabledAttributes[_i69]=0;attributeDivisors[_i69]=0;}return {// for backward compatibility on non-VAO support browser
  3085. geometry:null,program:null,wireframe:false,newAttributes:newAttributes,enabledAttributes:enabledAttributes,attributeDivisors:attributeDivisors,object:vao,attributes:{},index:null};}function needsUpdate(geometry,index){var cachedAttributes=currentState.attributes;var geometryAttributes=geometry.attributes;var attributesNum=0;for(var key in geometryAttributes){var cachedAttribute=cachedAttributes[key];var geometryAttribute=geometryAttributes[key];if(cachedAttribute===undefined)return true;if(cachedAttribute.attribute!==geometryAttribute)return true;if(cachedAttribute.data!==geometryAttribute.data)return true;attributesNum++;}if(currentState.attributesNum!==attributesNum)return true;if(currentState.index!==index)return true;return false;}function saveCache(geometry,index){var cache={};var attributes=geometry.attributes;var attributesNum=0;for(var key in attributes){var attribute=attributes[key];var data={};data.attribute=attribute;if(attribute.data){data.data=attribute.data;}cache[key]=data;attributesNum++;}currentState.attributes=cache;currentState.attributesNum=attributesNum;currentState.index=index;}function initAttributes(){var newAttributes=currentState.newAttributes;for(var _i70=0,il=newAttributes.length;_i70<il;_i70++){newAttributes[_i70]=0;}}function enableAttribute(attribute){enableAttributeAndDivisor(attribute,0);}function enableAttributeAndDivisor(attribute,meshPerAttribute){var newAttributes=currentState.newAttributes;var enabledAttributes=currentState.enabledAttributes;var attributeDivisors=currentState.attributeDivisors;newAttributes[attribute]=1;if(enabledAttributes[attribute]===0){gl.enableVertexAttribArray(attribute);enabledAttributes[attribute]=1;}if(attributeDivisors[attribute]!==meshPerAttribute){var _extension=capabilities.isWebGL2?gl:extensions.get('ANGLE_instanced_arrays');_extension[capabilities.isWebGL2?'vertexAttribDivisor':'vertexAttribDivisorANGLE'](attribute,meshPerAttribute);attributeDivisors[attribute]=meshPerAttribute;}}function disableUnusedAttributes(){var newAttributes=currentState.newAttributes;var enabledAttributes=currentState.enabledAttributes;for(var _i71=0,il=enabledAttributes.length;_i71<il;_i71++){if(enabledAttributes[_i71]!==newAttributes[_i71]){gl.disableVertexAttribArray(_i71);enabledAttributes[_i71]=0;}}}function vertexAttribPointer(index,size,type,normalized,stride,offset){if(capabilities.isWebGL2===true&&(type===5124||type===5125)){gl.vertexAttribIPointer(index,size,type,stride,offset);}else {gl.vertexAttribPointer(index,size,type,normalized,stride,offset);}}function setupVertexAttributes(object,material,program,geometry){if(capabilities.isWebGL2===false&&(object.isInstancedMesh||geometry.isInstancedBufferGeometry)){if(extensions.get('ANGLE_instanced_arrays')===null)return;}initAttributes();var geometryAttributes=geometry.attributes;var programAttributes=program.getAttributes();var materialDefaultAttributeValues=material.defaultAttributeValues;for(var name in programAttributes){var programAttribute=programAttributes[name];if(programAttribute>=0){var geometryAttribute=geometryAttributes[name];if(geometryAttribute!==undefined){var normalized=geometryAttribute.normalized;var size=geometryAttribute.itemSize;var attribute=attributes.get(geometryAttribute);// TODO Attribute may not be available on context restore
  3086. if(attribute===undefined)continue;var buffer=attribute.buffer;var type=attribute.type;var bytesPerElement=attribute.bytesPerElement;if(geometryAttribute.isInterleavedBufferAttribute){var data=geometryAttribute.data;var stride=data.stride;var offset=geometryAttribute.offset;if(data&&data.isInstancedInterleavedBuffer){enableAttributeAndDivisor(programAttribute,data.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=data.meshPerAttribute*data.count;}}else {enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,stride*bytesPerElement,offset*bytesPerElement);}else {if(geometryAttribute.isInstancedBufferAttribute){enableAttributeAndDivisor(programAttribute,geometryAttribute.meshPerAttribute);if(geometry._maxInstanceCount===undefined){geometry._maxInstanceCount=geometryAttribute.meshPerAttribute*geometryAttribute.count;}}else {enableAttribute(programAttribute);}gl.bindBuffer(34962,buffer);vertexAttribPointer(programAttribute,size,type,normalized,0,0);}}else if(name==='instanceMatrix'){var _attribute7=attributes.get(object.instanceMatrix);// TODO Attribute may not be available on context restore
  3087. if(_attribute7===undefined)continue;var _buffer=_attribute7.buffer;var _type=_attribute7.type;enableAttributeAndDivisor(programAttribute+0,1);enableAttributeAndDivisor(programAttribute+1,1);enableAttributeAndDivisor(programAttribute+2,1);enableAttributeAndDivisor(programAttribute+3,1);gl.bindBuffer(34962,_buffer);gl.vertexAttribPointer(programAttribute+0,4,_type,false,64,0);gl.vertexAttribPointer(programAttribute+1,4,_type,false,64,16);gl.vertexAttribPointer(programAttribute+2,4,_type,false,64,32);gl.vertexAttribPointer(programAttribute+3,4,_type,false,64,48);}else if(name==='instanceColor'){var _attribute8=attributes.get(object.instanceColor);// TODO Attribute may not be available on context restore
  3088. if(_attribute8===undefined)continue;var _buffer2=_attribute8.buffer;var _type2=_attribute8.type;enableAttributeAndDivisor(programAttribute,1);gl.bindBuffer(34962,_buffer2);gl.vertexAttribPointer(programAttribute,3,_type2,false,12,0);}else if(materialDefaultAttributeValues!==undefined){var value=materialDefaultAttributeValues[name];if(value!==undefined){switch(value.length){case 2:gl.vertexAttrib2fv(programAttribute,value);break;case 3:gl.vertexAttrib3fv(programAttribute,value);break;case 4:gl.vertexAttrib4fv(programAttribute,value);break;default:gl.vertexAttrib1fv(programAttribute,value);}}}}}disableUnusedAttributes();}function dispose(){reset();for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometryId];}}function releaseStatesOfGeometry(geometry){if(bindingStates[geometry.id]===undefined)return;var programMap=bindingStates[geometry.id];for(var programId in programMap){var stateMap=programMap[programId];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[programId];}delete bindingStates[geometry.id];}function releaseStatesOfProgram(program){for(var geometryId in bindingStates){var programMap=bindingStates[geometryId];if(programMap[program.id]===undefined)continue;var stateMap=programMap[program.id];for(var wireframe in stateMap){deleteVertexArrayObject(stateMap[wireframe].object);delete stateMap[wireframe];}delete programMap[program.id];}}function reset(){resetDefaultState();if(currentState===defaultState)return;currentState=defaultState;bindVertexArrayObject(currentState.object);}// for backward-compatilibity
  3089. function resetDefaultState(){defaultState.geometry=null;defaultState.program=null;defaultState.wireframe=false;}return {setup:setup,reset:reset,resetDefaultState:resetDefaultState,dispose:dispose,releaseStatesOfGeometry:releaseStatesOfGeometry,releaseStatesOfProgram:releaseStatesOfProgram,initAttributes:initAttributes,enableAttribute:enableAttribute,disableUnusedAttributes:disableUnusedAttributes};}function WebGLBufferRenderer(gl,extensions,info,capabilities){var isWebGL2=capabilities.isWebGL2;var mode;function setMode(value){mode=value;}function render(start,count){gl.drawArrays(mode,start,count);info.update(count,mode,1);}function renderInstances(start,count,primcount){if(primcount===0)return;var extension,methodName;if(isWebGL2){extension=gl;methodName='drawArraysInstanced';}else {extension=extensions.get('ANGLE_instanced_arrays');methodName='drawArraysInstancedANGLE';if(extension===null){console.error('THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');return;}}extension[methodName](mode,start,count,primcount);info.update(count,mode,primcount);}//
  3090. this.setMode=setMode;this.render=render;this.renderInstances=renderInstances;}function WebGLCapabilities(gl,extensions,parameters){var maxAnisotropy;function getMaxAnisotropy(){if(maxAnisotropy!==undefined)return maxAnisotropy;var extension=extensions.get('EXT_texture_filter_anisotropic');if(extension!==null){maxAnisotropy=gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);}else {maxAnisotropy=0;}return maxAnisotropy;}function getMaxPrecision(precision){if(precision==='highp'){if(gl.getShaderPrecisionFormat(35633,36338).precision>0&&gl.getShaderPrecisionFormat(35632,36338).precision>0){return 'highp';}precision='mediump';}if(precision==='mediump'){if(gl.getShaderPrecisionFormat(35633,36337).precision>0&&gl.getShaderPrecisionFormat(35632,36337).precision>0){return 'mediump';}}return 'lowp';}/* eslint-disable no-undef */var isWebGL2=typeof WebGL2RenderingContext!=='undefined'&&gl instanceof WebGL2RenderingContext||typeof WebGL2ComputeRenderingContext!=='undefined'&&gl instanceof WebGL2ComputeRenderingContext;/* eslint-enable no-undef */var precision=parameters.precision!==undefined?parameters.precision:'highp';var maxPrecision=getMaxPrecision(precision);if(maxPrecision!==precision){console.warn('THREE.WebGLRenderer:',precision,'not supported, using',maxPrecision,'instead.');precision=maxPrecision;}var logarithmicDepthBuffer=parameters.logarithmicDepthBuffer===true;var maxTextures=gl.getParameter(34930);var maxVertexTextures=gl.getParameter(35660);var maxTextureSize=gl.getParameter(3379);var maxCubemapSize=gl.getParameter(34076);var maxAttributes=gl.getParameter(34921);var maxVertexUniforms=gl.getParameter(36347);var maxVaryings=gl.getParameter(36348);var maxFragmentUniforms=gl.getParameter(36349);var vertexTextures=maxVertexTextures>0;var floatFragmentTextures=isWebGL2||!!extensions.get('OES_texture_float');var floatVertexTextures=vertexTextures&&floatFragmentTextures;var maxSamples=isWebGL2?gl.getParameter(36183):0;return {isWebGL2:isWebGL2,getMaxAnisotropy:getMaxAnisotropy,getMaxPrecision:getMaxPrecision,precision:precision,logarithmicDepthBuffer:logarithmicDepthBuffer,maxTextures:maxTextures,maxVertexTextures:maxVertexTextures,maxTextureSize:maxTextureSize,maxCubemapSize:maxCubemapSize,maxAttributes:maxAttributes,maxVertexUniforms:maxVertexUniforms,maxVaryings:maxVaryings,maxFragmentUniforms:maxFragmentUniforms,vertexTextures:vertexTextures,floatFragmentTextures:floatFragmentTextures,floatVertexTextures:floatVertexTextures,maxSamples:maxSamples};}function WebGLClipping(properties){var scope=this;var globalState=null,numGlobalPlanes=0,localClippingEnabled=false,renderingShadows=false;var plane=new Plane(),viewNormalMatrix=new Matrix3(),uniform={value:null,needsUpdate:false};this.uniform=uniform;this.numPlanes=0;this.numIntersection=0;this.init=function(planes,enableLocalClipping,camera){var enabled=planes.length!==0||enableLocalClipping||// enable state of previous frame - the clipping code has to
  3091. // run another frame in order to reset the state:
  3092. numGlobalPlanes!==0||localClippingEnabled;localClippingEnabled=enableLocalClipping;globalState=projectPlanes(planes,camera,0);numGlobalPlanes=planes.length;return enabled;};this.beginShadows=function(){renderingShadows=true;projectPlanes(null);};this.endShadows=function(){renderingShadows=false;resetGlobalState();};this.setState=function(material,camera,useCache){var planes=material.clippingPlanes,clipIntersection=material.clipIntersection,clipShadows=material.clipShadows;var materialProperties=properties.get(material);if(!localClippingEnabled||planes===null||planes.length===0||renderingShadows&&!clipShadows){// there's no local clipping
  3093. if(renderingShadows){// there's no global clipping
  3094. projectPlanes(null);}else {resetGlobalState();}}else {var nGlobal=renderingShadows?0:numGlobalPlanes,lGlobal=nGlobal*4;var dstArray=materialProperties.clippingState||null;uniform.value=dstArray;// ensure unique state
  3095. dstArray=projectPlanes(planes,camera,lGlobal,useCache);for(var _i72=0;_i72!==lGlobal;++_i72){dstArray[_i72]=globalState[_i72];}materialProperties.clippingState=dstArray;this.numIntersection=clipIntersection?this.numPlanes:0;this.numPlanes+=nGlobal;}};function resetGlobalState(){if(uniform.value!==globalState){uniform.value=globalState;uniform.needsUpdate=numGlobalPlanes>0;}scope.numPlanes=numGlobalPlanes;scope.numIntersection=0;}function projectPlanes(planes,camera,dstOffset,skipTransform){var nPlanes=planes!==null?planes.length:0;var dstArray=null;if(nPlanes!==0){dstArray=uniform.value;if(skipTransform!==true||dstArray===null){var flatSize=dstOffset+nPlanes*4,viewMatrix=camera.matrixWorldInverse;viewNormalMatrix.getNormalMatrix(viewMatrix);if(dstArray===null||dstArray.length<flatSize){dstArray=new Float32Array(flatSize);}for(var _i73=0,i4=dstOffset;_i73!==nPlanes;++_i73,i4+=4){plane.copy(planes[_i73]).applyMatrix4(viewMatrix,viewNormalMatrix);plane.normal.toArray(dstArray,i4);dstArray[i4+3]=plane.constant;}}uniform.value=dstArray;uniform.needsUpdate=true;}scope.numPlanes=nPlanes;scope.numIntersection=0;return dstArray;}}function WebGLCubeMaps(renderer){var cubemaps=new WeakMap();function mapTextureMapping(texture,mapping){if(mapping===EquirectangularReflectionMapping){texture.mapping=CubeReflectionMapping;}else if(mapping===EquirectangularRefractionMapping){texture.mapping=CubeRefractionMapping;}return texture;}function get(texture){if(texture&&texture.isTexture){var mapping=texture.mapping;if(mapping===EquirectangularReflectionMapping||mapping===EquirectangularRefractionMapping){if(cubemaps.has(texture)){var cubemap=cubemaps.get(texture).texture;return mapTextureMapping(cubemap,texture.mapping);}else {var image=texture.image;if(image&&image.height>0){var currentRenderList=renderer.getRenderList();var currentRenderTarget=renderer.getRenderTarget();var renderTarget=new WebGLCubeRenderTarget(image.height/2);renderTarget.fromEquirectangularTexture(renderer,texture);cubemaps.set(texture,renderTarget);renderer.setRenderTarget(currentRenderTarget);renderer.setRenderList(currentRenderList);texture.addEventListener('dispose',onTextureDispose);return mapTextureMapping(renderTarget.texture,texture.mapping);}else {// image not yet ready. try the conversion next frame
  3096. return null;}}}}return texture;}function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);var cubemap=cubemaps.get(texture);if(cubemap!==undefined){cubemaps.delete(texture);cubemap.dispose();}}function dispose(){cubemaps=new WeakMap();}return {get:get,dispose:dispose};}function WebGLExtensions(gl){var extensions={};return {has:function has(name){if(extensions[name]!==undefined){return extensions[name]!==null;}var extension;switch(name){case'WEBGL_depth_texture':extension=gl.getExtension('WEBGL_depth_texture')||gl.getExtension('MOZ_WEBGL_depth_texture')||gl.getExtension('WEBKIT_WEBGL_depth_texture');break;case'EXT_texture_filter_anisotropic':extension=gl.getExtension('EXT_texture_filter_anisotropic')||gl.getExtension('MOZ_EXT_texture_filter_anisotropic')||gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');break;case'WEBGL_compressed_texture_s3tc':extension=gl.getExtension('WEBGL_compressed_texture_s3tc')||gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc')||gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');break;case'WEBGL_compressed_texture_pvrtc':extension=gl.getExtension('WEBGL_compressed_texture_pvrtc')||gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');break;default:extension=gl.getExtension(name);}extensions[name]=extension;return extension!==null;},get:function get(name){if(!this.has(name)){console.warn('THREE.WebGLRenderer: '+name+' extension not supported.');}return extensions[name];}};}function WebGLGeometries(gl,attributes,info,bindingStates){var geometries=new WeakMap();var wireframeAttributes=new WeakMap();function onGeometryDispose(event){var geometry=event.target;var buffergeometry=geometries.get(geometry);if(buffergeometry.index!==null){attributes.remove(buffergeometry.index);}for(var name in buffergeometry.attributes){attributes.remove(buffergeometry.attributes[name]);}geometry.removeEventListener('dispose',onGeometryDispose);geometries.delete(geometry);var attribute=wireframeAttributes.get(buffergeometry);if(attribute){attributes.remove(attribute);wireframeAttributes.delete(buffergeometry);}bindingStates.releaseStatesOfGeometry(buffergeometry);if(geometry.isInstancedBufferGeometry===true){delete geometry._maxInstanceCount;}//
  3097. info.memory.geometries--;}function get(object,geometry){var buffergeometry=geometries.get(geometry);if(buffergeometry)return buffergeometry;geometry.addEventListener('dispose',onGeometryDispose);if(geometry.isBufferGeometry){buffergeometry=geometry;}else if(geometry.isGeometry){if(geometry._bufferGeometry===undefined){geometry._bufferGeometry=new BufferGeometry().setFromObject(object);}buffergeometry=geometry._bufferGeometry;}geometries.set(geometry,buffergeometry);info.memory.geometries++;return buffergeometry;}function update(geometry){var geometryAttributes=geometry.attributes;// Updating index buffer in VAO now. See WebGLBindingStates.
  3098. for(var name in geometryAttributes){attributes.update(geometryAttributes[name],34962);}// morph targets
  3099. var morphAttributes=geometry.morphAttributes;for(var _name3 in morphAttributes){var array=morphAttributes[_name3];for(var _i74=0,l=array.length;_i74<l;_i74++){attributes.update(array[_i74],34962);}}}function updateWireframeAttribute(geometry){var indices=[];var geometryIndex=geometry.index;var geometryPosition=geometry.attributes.position;var version=0;if(geometryIndex!==null){var array=geometryIndex.array;version=geometryIndex.version;for(var _i75=0,l=array.length;_i75<l;_i75+=3){var a=array[_i75+0];var b=array[_i75+1];var c=array[_i75+2];indices.push(a,b,b,c,c,a);}}else {var _array=geometryPosition.array;version=geometryPosition.version;for(var _i76=0,_l4=_array.length/3-1;_i76<_l4;_i76+=3){var _a4=_i76+0;var _b4=_i76+1;var _c4=_i76+2;indices.push(_a4,_b4,_b4,_c4,_c4,_a4);}}var attribute=new(arrayMax(indices)>65535?Uint32BufferAttribute:Uint16BufferAttribute)(indices,1);attribute.version=version;// Updating index buffer in VAO now. See WebGLBindingStates
  3100. //
  3101. var previousAttribute=wireframeAttributes.get(geometry);if(previousAttribute)attributes.remove(previousAttribute);//
  3102. wireframeAttributes.set(geometry,attribute);}function getWireframeAttribute(geometry){var currentAttribute=wireframeAttributes.get(geometry);if(currentAttribute){var geometryIndex=geometry.index;if(geometryIndex!==null){// if the attribute is obsolete, create a new one
  3103. if(currentAttribute.version<geometryIndex.version){updateWireframeAttribute(geometry);}}}else {updateWireframeAttribute(geometry);}return wireframeAttributes.get(geometry);}return {get:get,update:update,getWireframeAttribute:getWireframeAttribute};}function WebGLIndexedBufferRenderer(gl,extensions,info,capabilities){var isWebGL2=capabilities.isWebGL2;var mode;function setMode(value){mode=value;}var type,bytesPerElement;function setIndex(value){type=value.type;bytesPerElement=value.bytesPerElement;}function render(start,count){gl.drawElements(mode,count,type,start*bytesPerElement);info.update(count,mode,1);}function renderInstances(start,count,primcount){if(primcount===0)return;var extension,methodName;if(isWebGL2){extension=gl;methodName='drawElementsInstanced';}else {extension=extensions.get('ANGLE_instanced_arrays');methodName='drawElementsInstancedANGLE';if(extension===null){console.error('THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.');return;}}extension[methodName](mode,count,type,start*bytesPerElement,primcount);info.update(count,mode,primcount);}//
  3104. this.setMode=setMode;this.setIndex=setIndex;this.render=render;this.renderInstances=renderInstances;}function WebGLInfo(gl){var memory={geometries:0,textures:0};var render={frame:0,calls:0,triangles:0,points:0,lines:0};function update(count,mode,instanceCount){render.calls++;switch(mode){case 4:render.triangles+=instanceCount*(count/3);break;case 1:render.lines+=instanceCount*(count/2);break;case 3:render.lines+=instanceCount*(count-1);break;case 2:render.lines+=instanceCount*count;break;case 0:render.points+=instanceCount*count;break;default:console.error('THREE.WebGLInfo: Unknown draw mode:',mode);break;}}function reset(){render.frame++;render.calls=0;render.triangles=0;render.points=0;render.lines=0;}return {memory:memory,render:render,programs:null,autoReset:true,reset:reset,update:update};}function numericalSort(a,b){return a[0]-b[0];}function absNumericalSort(a,b){return Math.abs(b[1])-Math.abs(a[1]);}function WebGLMorphtargets(gl){var influencesList={};var morphInfluences=new Float32Array(8);var workInfluences=[];for(var _i77=0;_i77<8;_i77++){workInfluences[_i77]=[_i77,0];}function update(object,geometry,material,program){var objectInfluences=object.morphTargetInfluences;// When object doesn't have morph target influences defined, we treat it as a 0-length array
  3105. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  3106. var length=objectInfluences===undefined?0:objectInfluences.length;var influences=influencesList[geometry.id];if(influences===undefined){// initialise list
  3107. influences=[];for(var _i78=0;_i78<length;_i78++){influences[_i78]=[_i78,0];}influencesList[geometry.id]=influences;}// Collect influences
  3108. for(var _i79=0;_i79<length;_i79++){var influence=influences[_i79];influence[0]=_i79;influence[1]=objectInfluences[_i79];}influences.sort(absNumericalSort);for(var _i80=0;_i80<8;_i80++){if(_i80<length&&influences[_i80][1]){workInfluences[_i80][0]=influences[_i80][0];workInfluences[_i80][1]=influences[_i80][1];}else {workInfluences[_i80][0]=Number.MAX_SAFE_INTEGER;workInfluences[_i80][1]=0;}}workInfluences.sort(numericalSort);var morphTargets=material.morphTargets&&geometry.morphAttributes.position;var morphNormals=material.morphNormals&&geometry.morphAttributes.normal;var morphInfluencesSum=0;for(var _i81=0;_i81<8;_i81++){var _influence=workInfluences[_i81];var index=_influence[0];var value=_influence[1];if(index!==Number.MAX_SAFE_INTEGER&&value){if(morphTargets&&geometry.getAttribute('morphTarget'+_i81)!==morphTargets[index]){geometry.setAttribute('morphTarget'+_i81,morphTargets[index]);}if(morphNormals&&geometry.getAttribute('morphNormal'+_i81)!==morphNormals[index]){geometry.setAttribute('morphNormal'+_i81,morphNormals[index]);}morphInfluences[_i81]=value;morphInfluencesSum+=value;}else {if(morphTargets&&geometry.hasAttribute('morphTarget'+_i81)===true){geometry.deleteAttribute('morphTarget'+_i81);}if(morphNormals&&geometry.hasAttribute('morphNormal'+_i81)===true){geometry.deleteAttribute('morphNormal'+_i81);}morphInfluences[_i81]=0;}}// GLSL shader uses formula baseinfluence * base + sum(target * influence)
  3109. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  3110. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  3111. var morphBaseInfluence=geometry.morphTargetsRelative?1:1-morphInfluencesSum;program.getUniforms().setValue(gl,'morphTargetBaseInfluence',morphBaseInfluence);program.getUniforms().setValue(gl,'morphTargetInfluences',morphInfluences);}return {update:update};}function WebGLObjects(gl,geometries,attributes,info){var updateMap=new WeakMap();function update(object){var frame=info.render.frame;var geometry=object.geometry;var buffergeometry=geometries.get(object,geometry);// Update once per frame
  3112. if(updateMap.get(buffergeometry)!==frame){if(geometry.isGeometry){buffergeometry.updateFromObject(object);}geometries.update(buffergeometry);updateMap.set(buffergeometry,frame);}if(object.isInstancedMesh){if(object.hasEventListener('dispose',onInstancedMeshDispose)===false){object.addEventListener('dispose',onInstancedMeshDispose);}attributes.update(object.instanceMatrix,34962);if(object.instanceColor!==null){attributes.update(object.instanceColor,34962);}}return buffergeometry;}function dispose(){updateMap=new WeakMap();}function onInstancedMeshDispose(event){var instancedMesh=event.target;instancedMesh.removeEventListener('dispose',onInstancedMeshDispose);attributes.remove(instancedMesh.instanceMatrix);if(instancedMesh.instanceColor!==null)attributes.remove(instancedMesh.instanceColor);}return {update:update,dispose:dispose};}function DataTexture2DArray(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var width=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var depth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;Texture.call(this,null);this.image={data,width,height,depth};this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.wrapR=ClampToEdgeWrapping;this.generateMipmaps=false;this.flipY=false;this.needsUpdate=true;}DataTexture2DArray.prototype=Object.create(Texture.prototype);DataTexture2DArray.prototype.constructor=DataTexture2DArray;DataTexture2DArray.prototype.isDataTexture2DArray=true;function DataTexture3D(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;var width=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var depth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;// We're going to add .setXXX() methods for setting properties later.
  3113. // Users can still set in DataTexture3D directly.
  3114. //
  3115. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  3116. // texture.anisotropy = 16;
  3117. //
  3118. // See #14839
  3119. Texture.call(this,null);this.image={data,width,height,depth};this.magFilter=NearestFilter;this.minFilter=NearestFilter;this.wrapR=ClampToEdgeWrapping;this.generateMipmaps=false;this.flipY=false;this.needsUpdate=true;}DataTexture3D.prototype=Object.create(Texture.prototype);DataTexture3D.prototype.constructor=DataTexture3D;DataTexture3D.prototype.isDataTexture3D=true;/**
  3120. * Uniforms of a program.
  3121. * Those form a tree structure with a special top-level container for the root,
  3122. * which you get by calling 'new WebGLUniforms( gl, program )'.
  3123. *
  3124. *
  3125. * Properties of inner nodes including the top-level container:
  3126. *
  3127. * .seq - array of nested uniforms
  3128. * .map - nested uniforms by name
  3129. *
  3130. *
  3131. * Methods of all nodes except the top-level container:
  3132. *
  3133. * .setValue( gl, value, [textures] )
  3134. *
  3135. * uploads a uniform value(s)
  3136. * the 'textures' parameter is needed for sampler uniforms
  3137. *
  3138. *
  3139. * Static methods of the top-level container (textures factorizations):
  3140. *
  3141. * .upload( gl, seq, values, textures )
  3142. *
  3143. * sets uniforms in 'seq' to 'values[id].value'
  3144. *
  3145. * .seqWithValue( seq, values ) : filteredSeq
  3146. *
  3147. * filters 'seq' entries with corresponding entry in values
  3148. *
  3149. *
  3150. * Methods of the top-level container (textures factorizations):
  3151. *
  3152. * .setValue( gl, name, value, textures )
  3153. *
  3154. * sets uniform with name 'name' to 'value'
  3155. *
  3156. * .setOptional( gl, obj, prop )
  3157. *
  3158. * like .set for an optional property of the object
  3159. *
  3160. */var emptyTexture=new Texture();var emptyTexture2dArray=new DataTexture2DArray();var emptyTexture3d=new DataTexture3D();var emptyCubeTexture=new CubeTexture();// --- Utilities ---
  3161. // Array Caches (provide typed arrays for temporary by size)
  3162. var arrayCacheF32=[];var arrayCacheI32=[];// Float32Array caches used for uploading Matrix uniforms
  3163. var mat4array=new Float32Array(16);var mat3array=new Float32Array(9);var mat2array=new Float32Array(4);// Flattening for arrays of vectors and matrices
  3164. function flatten(array,nBlocks,blockSize){var firstElem=array[0];if(firstElem<=0||firstElem>0)return array;// unoptimized: ! isNaN( firstElem )
  3165. // see http://jacksondunstan.com/articles/983
  3166. var n=nBlocks*blockSize;var r=arrayCacheF32[n];if(r===undefined){r=new Float32Array(n);arrayCacheF32[n]=r;}if(nBlocks!==0){firstElem.toArray(r,0);for(var _i82=1,offset=0;_i82!==nBlocks;++_i82){offset+=blockSize;array[_i82].toArray(r,offset);}}return r;}function arraysEqual(a,b){if(a.length!==b.length)return false;for(var _i83=0,l=a.length;_i83<l;_i83++){if(a[_i83]!==b[_i83])return false;}return true;}function copyArray(a,b){for(var _i84=0,l=b.length;_i84<l;_i84++){a[_i84]=b[_i84];}}// Texture unit allocation
  3167. function allocTexUnits(textures,n){var r=arrayCacheI32[n];if(r===undefined){r=new Int32Array(n);arrayCacheI32[n]=r;}for(var _i85=0;_i85!==n;++_i85){r[_i85]=textures.allocateTextureUnit();}return r;}// --- Setters ---
  3168. // Note: Defining these methods externally, because they come in a bunch
  3169. // and this way their names minify.
  3170. // Single scalar
  3171. function setValueV1f(gl,v){var cache=this.cache;if(cache[0]===v)return;gl.uniform1f(this.addr,v);cache[0]=v;}// Single float vector (from flat array or THREE.VectorN)
  3172. function setValueV2f(gl,v){var cache=this.cache;if(v.x!==undefined){if(cache[0]!==v.x||cache[1]!==v.y){gl.uniform2f(this.addr,v.x,v.y);cache[0]=v.x;cache[1]=v.y;}}else {if(arraysEqual(cache,v))return;gl.uniform2fv(this.addr,v);copyArray(cache,v);}}function setValueV3f(gl,v){var cache=this.cache;if(v.x!==undefined){if(cache[0]!==v.x||cache[1]!==v.y||cache[2]!==v.z){gl.uniform3f(this.addr,v.x,v.y,v.z);cache[0]=v.x;cache[1]=v.y;cache[2]=v.z;}}else if(v.r!==undefined){if(cache[0]!==v.r||cache[1]!==v.g||cache[2]!==v.b){gl.uniform3f(this.addr,v.r,v.g,v.b);cache[0]=v.r;cache[1]=v.g;cache[2]=v.b;}}else {if(arraysEqual(cache,v))return;gl.uniform3fv(this.addr,v);copyArray(cache,v);}}function setValueV4f(gl,v){var cache=this.cache;if(v.x!==undefined){if(cache[0]!==v.x||cache[1]!==v.y||cache[2]!==v.z||cache[3]!==v.w){gl.uniform4f(this.addr,v.x,v.y,v.z,v.w);cache[0]=v.x;cache[1]=v.y;cache[2]=v.z;cache[3]=v.w;}}else {if(arraysEqual(cache,v))return;gl.uniform4fv(this.addr,v);copyArray(cache,v);}}// Single matrix (from flat array or MatrixN)
  3173. function setValueM2(gl,v){var cache=this.cache;var elements=v.elements;if(elements===undefined){if(arraysEqual(cache,v))return;gl.uniformMatrix2fv(this.addr,false,v);copyArray(cache,v);}else {if(arraysEqual(cache,elements))return;mat2array.set(elements);gl.uniformMatrix2fv(this.addr,false,mat2array);copyArray(cache,elements);}}function setValueM3(gl,v){var cache=this.cache;var elements=v.elements;if(elements===undefined){if(arraysEqual(cache,v))return;gl.uniformMatrix3fv(this.addr,false,v);copyArray(cache,v);}else {if(arraysEqual(cache,elements))return;mat3array.set(elements);gl.uniformMatrix3fv(this.addr,false,mat3array);copyArray(cache,elements);}}function setValueM4(gl,v){var cache=this.cache;var elements=v.elements;if(elements===undefined){if(arraysEqual(cache,v))return;gl.uniformMatrix4fv(this.addr,false,v);copyArray(cache,v);}else {if(arraysEqual(cache,elements))return;mat4array.set(elements);gl.uniformMatrix4fv(this.addr,false,mat4array);copyArray(cache,elements);}}// Single texture (2D / Cube)
  3174. function setValueT1(gl,v,textures){var cache=this.cache;var unit=textures.allocateTextureUnit();if(cache[0]!==unit){gl.uniform1i(this.addr,unit);cache[0]=unit;}textures.safeSetTexture2D(v||emptyTexture,unit);}function setValueT2DArray1(gl,v,textures){var cache=this.cache;var unit=textures.allocateTextureUnit();if(cache[0]!==unit){gl.uniform1i(this.addr,unit);cache[0]=unit;}textures.setTexture2DArray(v||emptyTexture2dArray,unit);}function setValueT3D1(gl,v,textures){var cache=this.cache;var unit=textures.allocateTextureUnit();if(cache[0]!==unit){gl.uniform1i(this.addr,unit);cache[0]=unit;}textures.setTexture3D(v||emptyTexture3d,unit);}function setValueT6(gl,v,textures){var cache=this.cache;var unit=textures.allocateTextureUnit();if(cache[0]!==unit){gl.uniform1i(this.addr,unit);cache[0]=unit;}textures.safeSetTextureCube(v||emptyCubeTexture,unit);}// Integer / Boolean vectors or arrays thereof (always flat arrays)
  3175. function setValueV1i(gl,v){var cache=this.cache;if(cache[0]===v)return;gl.uniform1i(this.addr,v);cache[0]=v;}function setValueV2i(gl,v){var cache=this.cache;if(arraysEqual(cache,v))return;gl.uniform2iv(this.addr,v);copyArray(cache,v);}function setValueV3i(gl,v){var cache=this.cache;if(arraysEqual(cache,v))return;gl.uniform3iv(this.addr,v);copyArray(cache,v);}function setValueV4i(gl,v){var cache=this.cache;if(arraysEqual(cache,v))return;gl.uniform4iv(this.addr,v);copyArray(cache,v);}// uint
  3176. function setValueV1ui(gl,v){var cache=this.cache;if(cache[0]===v)return;gl.uniform1ui(this.addr,v);cache[0]=v;}// Helper to pick the right setter for the singular case
  3177. function getSingularSetter(type){switch(type){case 0x1406:return setValueV1f;// FLOAT
  3178. case 0x8b50:return setValueV2f;// _VEC2
  3179. case 0x8b51:return setValueV3f;// _VEC3
  3180. case 0x8b52:return setValueV4f;// _VEC4
  3181. case 0x8b5a:return setValueM2;// _MAT2
  3182. case 0x8b5b:return setValueM3;// _MAT3
  3183. case 0x8b5c:return setValueM4;// _MAT4
  3184. case 0x1404:case 0x8b56:return setValueV1i;// INT, BOOL
  3185. case 0x8b53:case 0x8b57:return setValueV2i;// _VEC2
  3186. case 0x8b54:case 0x8b58:return setValueV3i;// _VEC3
  3187. case 0x8b55:case 0x8b59:return setValueV4i;// _VEC4
  3188. case 0x1405:return setValueV1ui;// UINT
  3189. case 0x8b5e:// SAMPLER_2D
  3190. case 0x8d66:// SAMPLER_EXTERNAL_OES
  3191. case 0x8dca:// INT_SAMPLER_2D
  3192. case 0x8dd2:// UNSIGNED_INT_SAMPLER_2D
  3193. case 0x8b62:// SAMPLER_2D_SHADOW
  3194. return setValueT1;case 0x8b5f:// SAMPLER_3D
  3195. case 0x8dcb:// INT_SAMPLER_3D
  3196. case 0x8dd3:// UNSIGNED_INT_SAMPLER_3D
  3197. return setValueT3D1;case 0x8b60:// SAMPLER_CUBE
  3198. case 0x8dcc:// INT_SAMPLER_CUBE
  3199. case 0x8dd4:// UNSIGNED_INT_SAMPLER_CUBE
  3200. case 0x8dc5:// SAMPLER_CUBE_SHADOW
  3201. return setValueT6;case 0x8dc1:// SAMPLER_2D_ARRAY
  3202. case 0x8dcf:// INT_SAMPLER_2D_ARRAY
  3203. case 0x8dd7:// UNSIGNED_INT_SAMPLER_2D_ARRAY
  3204. case 0x8dc4:// SAMPLER_2D_ARRAY_SHADOW
  3205. return setValueT2DArray1;}}// Array of scalars
  3206. function setValueV1fArray(gl,v){gl.uniform1fv(this.addr,v);}// Integer / Boolean vectors or arrays thereof (always flat arrays)
  3207. function setValueV1iArray(gl,v){gl.uniform1iv(this.addr,v);}function setValueV2iArray(gl,v){gl.uniform2iv(this.addr,v);}function setValueV3iArray(gl,v){gl.uniform3iv(this.addr,v);}function setValueV4iArray(gl,v){gl.uniform4iv(this.addr,v);}// Array of vectors (flat or from THREE classes)
  3208. function setValueV2fArray(gl,v){var data=flatten(v,this.size,2);gl.uniform2fv(this.addr,data);}function setValueV3fArray(gl,v){var data=flatten(v,this.size,3);gl.uniform3fv(this.addr,data);}function setValueV4fArray(gl,v){var data=flatten(v,this.size,4);gl.uniform4fv(this.addr,data);}// Array of matrices (flat or from THREE clases)
  3209. function setValueM2Array(gl,v){var data=flatten(v,this.size,4);gl.uniformMatrix2fv(this.addr,false,data);}function setValueM3Array(gl,v){var data=flatten(v,this.size,9);gl.uniformMatrix3fv(this.addr,false,data);}function setValueM4Array(gl,v){var data=flatten(v,this.size,16);gl.uniformMatrix4fv(this.addr,false,data);}// Array of textures (2D / Cube)
  3210. function setValueT1Array(gl,v,textures){var n=v.length;var units=allocTexUnits(textures,n);gl.uniform1iv(this.addr,units);for(var _i86=0;_i86!==n;++_i86){textures.safeSetTexture2D(v[_i86]||emptyTexture,units[_i86]);}}function setValueT6Array(gl,v,textures){var n=v.length;var units=allocTexUnits(textures,n);gl.uniform1iv(this.addr,units);for(var _i87=0;_i87!==n;++_i87){textures.safeSetTextureCube(v[_i87]||emptyCubeTexture,units[_i87]);}}// Helper to pick the right setter for a pure (bottom-level) array
  3211. function getPureArraySetter(type){switch(type){case 0x1406:return setValueV1fArray;// FLOAT
  3212. case 0x8b50:return setValueV2fArray;// _VEC2
  3213. case 0x8b51:return setValueV3fArray;// _VEC3
  3214. case 0x8b52:return setValueV4fArray;// _VEC4
  3215. case 0x8b5a:return setValueM2Array;// _MAT2
  3216. case 0x8b5b:return setValueM3Array;// _MAT3
  3217. case 0x8b5c:return setValueM4Array;// _MAT4
  3218. case 0x1404:case 0x8b56:return setValueV1iArray;// INT, BOOL
  3219. case 0x8b53:case 0x8b57:return setValueV2iArray;// _VEC2
  3220. case 0x8b54:case 0x8b58:return setValueV3iArray;// _VEC3
  3221. case 0x8b55:case 0x8b59:return setValueV4iArray;// _VEC4
  3222. case 0x8b5e:// SAMPLER_2D
  3223. case 0x8d66:// SAMPLER_EXTERNAL_OES
  3224. case 0x8dca:// INT_SAMPLER_2D
  3225. case 0x8dd2:// UNSIGNED_INT_SAMPLER_2D
  3226. case 0x8b62:// SAMPLER_2D_SHADOW
  3227. return setValueT1Array;case 0x8b60:// SAMPLER_CUBE
  3228. case 0x8dcc:// INT_SAMPLER_CUBE
  3229. case 0x8dd4:// UNSIGNED_INT_SAMPLER_CUBE
  3230. case 0x8dc5:// SAMPLER_CUBE_SHADOW
  3231. return setValueT6Array;}}// --- Uniform Classes ---
  3232. function SingleUniform(id,activeInfo,addr){this.id=id;this.addr=addr;this.cache=[];this.setValue=getSingularSetter(activeInfo.type);// this.path = activeInfo.name; // DEBUG
  3233. }function PureArrayUniform(id,activeInfo,addr){this.id=id;this.addr=addr;this.cache=[];this.size=activeInfo.size;this.setValue=getPureArraySetter(activeInfo.type);// this.path = activeInfo.name; // DEBUG
  3234. }PureArrayUniform.prototype.updateCache=function(data){var cache=this.cache;if(data instanceof Float32Array&&cache.length!==data.length){this.cache=new Float32Array(data.length);}copyArray(cache,data);};function StructuredUniform(id){this.id=id;this.seq=[];this.map={};}StructuredUniform.prototype.setValue=function(gl,value,textures){var seq=this.seq;for(var _i88=0,n=seq.length;_i88!==n;++_i88){var u=seq[_i88];u.setValue(gl,value[u.id],textures);}};// --- Top-level ---
  3235. // Parser - builds up the property tree from the path strings
  3236. var RePathPart=/(\w+)(\])?(\[|\.)?/g;// extracts
  3237. // - the identifier (member name or array index)
  3238. // - followed by an optional right bracket (found when array index)
  3239. // - followed by an optional left bracket or dot (type of subscript)
  3240. //
  3241. // Note: These portions can be read in a non-overlapping fashion and
  3242. // allow straightforward parsing of the hierarchy that WebGL encodes
  3243. // in the uniform names.
  3244. function addUniform(container,uniformObject){container.seq.push(uniformObject);container.map[uniformObject.id]=uniformObject;}function parseUniform(activeInfo,addr,container){var path=activeInfo.name,pathLength=path.length;// reset RegExp object, because of the early exit of a previous run
  3245. RePathPart.lastIndex=0;while(true){var match=RePathPart.exec(path),matchEnd=RePathPart.lastIndex;var id=match[1];var idIsIndex=match[2]===']',subscript=match[3];if(idIsIndex)id=id|0;// convert to integer
  3246. if(subscript===undefined||subscript==='['&&matchEnd+2===pathLength){// bare name or "pure" bottom-level array "[0]" suffix
  3247. addUniform(container,subscript===undefined?new SingleUniform(id,activeInfo,addr):new PureArrayUniform(id,activeInfo,addr));break;}else {// step into inner node / create it in case it doesn't exist
  3248. var map=container.map;var next=map[id];if(next===undefined){next=new StructuredUniform(id);addUniform(container,next);}container=next;}}}// Root Container
  3249. function WebGLUniforms(gl,program){this.seq=[];this.map={};var n=gl.getProgramParameter(program,35718);for(var _i89=0;_i89<n;++_i89){var info=gl.getActiveUniform(program,_i89),addr=gl.getUniformLocation(program,info.name);parseUniform(info,addr,this);}}WebGLUniforms.prototype.setValue=function(gl,name,value,textures){var u=this.map[name];if(u!==undefined)u.setValue(gl,value,textures);};WebGLUniforms.prototype.setOptional=function(gl,object,name){var v=object[name];if(v!==undefined)this.setValue(gl,name,v);};// Static interface
  3250. WebGLUniforms.upload=function(gl,seq,values,textures){for(var _i90=0,n=seq.length;_i90!==n;++_i90){var u=seq[_i90],v=values[u.id];if(v.needsUpdate!==false){// note: always updating when .needsUpdate is undefined
  3251. u.setValue(gl,v.value,textures);}}};WebGLUniforms.seqWithValue=function(seq,values){var r=[];for(var _i91=0,n=seq.length;_i91!==n;++_i91){var u=seq[_i91];if(u.id in values)r.push(u);}return r;};function WebGLShader(gl,type,string){var shader=gl.createShader(type);gl.shaderSource(shader,string);gl.compileShader(shader);return shader;}var programIdCount=0;function addLineNumbers(string){var lines=string.split('\n');for(var _i92=0;_i92<lines.length;_i92++){lines[_i92]=_i92+1+': '+lines[_i92];}return lines.join('\n');}function getEncodingComponents(encoding){switch(encoding){case LinearEncoding:return ['Linear','( value )'];case sRGBEncoding:return ['sRGB','( value )'];case RGBEEncoding:return ['RGBE','( value )'];case RGBM7Encoding:return ['RGBM','( value, 7.0 )'];case RGBM16Encoding:return ['RGBM','( value, 16.0 )'];case RGBDEncoding:return ['RGBD','( value, 256.0 )'];case GammaEncoding:return ['Gamma','( value, float( GAMMA_FACTOR ) )'];case LogLuvEncoding:return ['LogLuv','( value )'];default:console.warn('THREE.WebGLProgram: Unsupported encoding:',encoding);return ['Linear','( value )'];}}function getShaderErrors(gl,shader,type){var status=gl.getShaderParameter(shader,35713);var log=gl.getShaderInfoLog(shader).trim();if(status&&log==='')return '';// --enable-privileged-webgl-extension
  3252. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  3253. var source=gl.getShaderSource(shader);return 'THREE.WebGLShader: gl.getShaderInfoLog() '+type+'\n'+log+addLineNumbers(source);}function getTexelDecodingFunction(functionName,encoding){var components=getEncodingComponents(encoding);return 'vec4 '+functionName+'( vec4 value ) { return '+components[0]+'ToLinear'+components[1]+'; }';}function getTexelEncodingFunction(functionName,encoding){var components=getEncodingComponents(encoding);return 'vec4 '+functionName+'( vec4 value ) { return LinearTo'+components[0]+components[1]+'; }';}function getToneMappingFunction(functionName,toneMapping){var toneMappingName;switch(toneMapping){case LinearToneMapping:toneMappingName='Linear';break;case ReinhardToneMapping:toneMappingName='Reinhard';break;case CineonToneMapping:toneMappingName='OptimizedCineon';break;case ACESFilmicToneMapping:toneMappingName='ACESFilmic';break;case CustomToneMapping:toneMappingName='Custom';break;default:console.warn('THREE.WebGLProgram: Unsupported toneMapping:',toneMapping);toneMappingName='Linear';}return 'vec3 '+functionName+'( vec3 color ) { return '+toneMappingName+'ToneMapping( color ); }';}function generateExtensions(parameters){var chunks=[parameters.extensionDerivatives||parameters.envMapCubeUV||parameters.bumpMap||parameters.tangentSpaceNormalMap||parameters.clearcoatNormalMap||parameters.flatShading||parameters.shaderID==='physical'?'#extension GL_OES_standard_derivatives : enable':'',(parameters.extensionFragDepth||parameters.logarithmicDepthBuffer)&&parameters.rendererExtensionFragDepth?'#extension GL_EXT_frag_depth : enable':'',parameters.extensionDrawBuffers&&parameters.rendererExtensionDrawBuffers?'#extension GL_EXT_draw_buffers : require':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&&parameters.rendererExtensionShaderTextureLod?'#extension GL_EXT_shader_texture_lod : enable':''];return chunks.filter(filterEmptyLine).join('\n');}function generateDefines(defines){var chunks=[];for(var name in defines){var value=defines[name];if(value===false)continue;chunks.push('#define '+name+' '+value);}return chunks.join('\n');}function fetchAttributeLocations(gl,program){var attributes={};var n=gl.getProgramParameter(program,35721);for(var _i93=0;_i93<n;_i93++){var info=gl.getActiveAttrib(program,_i93);var name=info.name;// console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  3254. attributes[name]=gl.getAttribLocation(program,name);}return attributes;}function filterEmptyLine(string){return string!=='';}function replaceLightNums(string,parameters){return string.replace(/NUM_DIR_LIGHTS/g,parameters.numDirLights).replace(/NUM_SPOT_LIGHTS/g,parameters.numSpotLights).replace(/NUM_RECT_AREA_LIGHTS/g,parameters.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,parameters.numPointLights).replace(/NUM_HEMI_LIGHTS/g,parameters.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,parameters.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS/g,parameters.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,parameters.numPointLightShadows);}function replaceClippingPlaneNums(string,parameters){return string.replace(/NUM_CLIPPING_PLANES/g,parameters.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,parameters.numClippingPlanes-parameters.numClipIntersection);}// Resolve Includes
  3255. var includePattern=/^[ \t]*#include +<([\w\d./]+)>/gm;function resolveIncludes(string){return string.replace(includePattern,includeReplacer);}function includeReplacer(match,include){var string=ShaderChunk[include];if(string===undefined){throw new Error('Can not resolve #include <'+include+'>');}return resolveIncludes(string);}// Unroll Loops
  3256. var deprecatedUnrollLoopPattern=/#pragma unroll_loop[\s]+?for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;var unrollLoopPattern=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function unrollLoops(string){return string.replace(unrollLoopPattern,loopReplacer).replace(deprecatedUnrollLoopPattern,deprecatedLoopReplacer);}function deprecatedLoopReplacer(match,start,end,snippet){console.warn('WebGLProgram: #pragma unroll_loop shader syntax is deprecated. Please use #pragma unroll_loop_start syntax instead.');return loopReplacer(match,start,end,snippet);}function loopReplacer(match,start,end,snippet){var string='';for(var _i94=parseInt(start);_i94<parseInt(end);_i94++){string+=snippet.replace(/\[\s*i\s*\]/g,'[ '+_i94+' ]').replace(/UNROLLED_LOOP_INDEX/g,_i94);}return string;}//
  3257. function generatePrecision(parameters){var precisionstring='precision '+parameters.precision+' float;\nprecision '+parameters.precision+' int;';if(parameters.precision==='highp'){precisionstring+='\n#define HIGH_PRECISION';}else if(parameters.precision==='mediump'){precisionstring+='\n#define MEDIUM_PRECISION';}else if(parameters.precision==='lowp'){precisionstring+='\n#define LOW_PRECISION';}return precisionstring;}function generateShadowMapTypeDefine(parameters){var shadowMapTypeDefine='SHADOWMAP_TYPE_BASIC';if(parameters.shadowMapType===PCFShadowMap){shadowMapTypeDefine='SHADOWMAP_TYPE_PCF';}else if(parameters.shadowMapType===PCFSoftShadowMap){shadowMapTypeDefine='SHADOWMAP_TYPE_PCF_SOFT';}else if(parameters.shadowMapType===VSMShadowMap){shadowMapTypeDefine='SHADOWMAP_TYPE_VSM';}return shadowMapTypeDefine;}function generateEnvMapTypeDefine(parameters){var envMapTypeDefine='ENVMAP_TYPE_CUBE';if(parameters.envMap){switch(parameters.envMapMode){case CubeReflectionMapping:case CubeRefractionMapping:envMapTypeDefine='ENVMAP_TYPE_CUBE';break;case CubeUVReflectionMapping:case CubeUVRefractionMapping:envMapTypeDefine='ENVMAP_TYPE_CUBE_UV';break;}}return envMapTypeDefine;}function generateEnvMapModeDefine(parameters){var envMapModeDefine='ENVMAP_MODE_REFLECTION';if(parameters.envMap){switch(parameters.envMapMode){case CubeRefractionMapping:case CubeUVRefractionMapping:envMapModeDefine='ENVMAP_MODE_REFRACTION';break;}}return envMapModeDefine;}function generateEnvMapBlendingDefine(parameters){var envMapBlendingDefine='ENVMAP_BLENDING_NONE';if(parameters.envMap){switch(parameters.combine){case MultiplyOperation:envMapBlendingDefine='ENVMAP_BLENDING_MULTIPLY';break;case MixOperation:envMapBlendingDefine='ENVMAP_BLENDING_MIX';break;case AddOperation:envMapBlendingDefine='ENVMAP_BLENDING_ADD';break;}}return envMapBlendingDefine;}function WebGLProgram(renderer,cacheKey,parameters,bindingStates){var gl=renderer.getContext();var defines=parameters.defines;var vertexShader=parameters.vertexShader;var fragmentShader=parameters.fragmentShader;var shadowMapTypeDefine=generateShadowMapTypeDefine(parameters);var envMapTypeDefine=generateEnvMapTypeDefine(parameters);var envMapModeDefine=generateEnvMapModeDefine(parameters);var envMapBlendingDefine=generateEnvMapBlendingDefine(parameters);var gammaFactorDefine=renderer.gammaFactor>0?renderer.gammaFactor:1.0;var customExtensions=parameters.isWebGL2?'':generateExtensions(parameters);var customDefines=generateDefines(defines);var program=gl.createProgram();var prefixVertex,prefixFragment;var versionString=parameters.glslVersion?'#version '+parameters.glslVersion+'\n':'';if(parameters.isRawShaderMaterial){prefixVertex=[customDefines].filter(filterEmptyLine).join('\n');if(prefixVertex.length>0){prefixVertex+='\n';}prefixFragment=[customExtensions,customDefines].filter(filterEmptyLine).join('\n');if(prefixFragment.length>0){prefixFragment+='\n';}}else {prefixVertex=[generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.instancing?'#define USE_INSTANCING':'',parameters.instancingColor?'#define USE_INSTANCING_COLOR':'',parameters.supportsVertexTextures?'#define VERTEX_TEXTURES':'','#define GAMMA_FACTOR '+gammaFactorDefine,'#define MAX_BONES '+parameters.maxBones,parameters.useFog&&parameters.fog?'#define USE_FOG':'',parameters.useFog&&parameters.fogExp2?'#define FOG_EXP2':'',parameters.map?'#define USE_MAP':'',parameters.envMap?'#define USE_ENVMAP':'',parameters.envMap?'#define '+envMapModeDefine:'',parameters.lightMap?'#define USE_LIGHTMAP':'',parameters.aoMap?'#define USE_AOMAP':'',parameters.emissiveMap?'#define USE_EMISSIVEMAP':'',parameters.bumpMap?'#define USE_BUMPMAP':'',parameters.normalMap?'#define USE_NORMALMAP':'',parameters.normalMap&&parameters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&&parameters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.displacementMap&&parameters.supportsVertexTextures?'#define USE_DISPLACEMENTMAP':'',parameters.specularMap?'#define USE_SPECULARMAP':'',parameters.roughnessMap?'#define USE_ROUGHNESSMAP':'',parameters.metalnessMap?'#define USE_METALNESSMAP':'',parameters.alphaMap?'#define USE_ALPHAMAP':'',parameters.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.skinning?'#define USE_SKINNING':'',parameters.useVertexTexture?'#define BONE_TEXTURE':'',parameters.morphTargets?'#define USE_MORPHTARGETS':'',parameters.morphNormals&&parameters.flatShading===false?'#define USE_MORPHNORMALS':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',parameters.shadowMapEnabled?'#define USE_SHADOWMAP':'',parameters.shadowMapEnabled?'#define '+shadowMapTypeDefine:'',parameters.sizeAttenuation?'#define USE_SIZEATTENUATION':'',parameters.logarithmicDepthBuffer?'#define USE_LOGDEPTHBUF':'',parameters.logarithmicDepthBuffer&&parameters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'','uniform mat4 modelMatrix;','uniform mat4 modelViewMatrix;','uniform mat4 projectionMatrix;','uniform mat4 viewMatrix;','uniform mat3 normalMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;','#ifdef USE_INSTANCING',' attribute mat4 instanceMatrix;','#endif','#ifdef USE_INSTANCING_COLOR',' attribute vec3 instanceColor;','#endif','attribute vec3 position;','attribute vec3 normal;','attribute vec2 uv;','#ifdef USE_TANGENT',' attribute vec4 tangent;','#endif','#ifdef USE_COLOR',' attribute vec3 color;','#endif','#ifdef USE_MORPHTARGETS',' attribute vec3 morphTarget0;',' attribute vec3 morphTarget1;',' attribute vec3 morphTarget2;',' attribute vec3 morphTarget3;',' #ifdef USE_MORPHNORMALS',' attribute vec3 morphNormal0;',' attribute vec3 morphNormal1;',' attribute vec3 morphNormal2;',' attribute vec3 morphNormal3;',' #else',' attribute vec3 morphTarget4;',' attribute vec3 morphTarget5;',' attribute vec3 morphTarget6;',' attribute vec3 morphTarget7;',' #endif','#endif','#ifdef USE_SKINNING',' attribute vec4 skinIndex;',' attribute vec4 skinWeight;','#endif','\n'].filter(filterEmptyLine).join('\n');prefixFragment=[customExtensions,generatePrecision(parameters),'#define SHADER_NAME '+parameters.shaderName,customDefines,parameters.alphaTest?'#define ALPHATEST '+parameters.alphaTest+(parameters.alphaTest%1?'':'.0'):'',// add '.0' if integer
  3258. '#define GAMMA_FACTOR '+gammaFactorDefine,parameters.useFog&&parameters.fog?'#define USE_FOG':'',parameters.useFog&&parameters.fogExp2?'#define FOG_EXP2':'',parameters.map?'#define USE_MAP':'',parameters.matcap?'#define USE_MATCAP':'',parameters.envMap?'#define USE_ENVMAP':'',parameters.envMap?'#define '+envMapTypeDefine:'',parameters.envMap?'#define '+envMapModeDefine:'',parameters.envMap?'#define '+envMapBlendingDefine:'',parameters.lightMap?'#define USE_LIGHTMAP':'',parameters.aoMap?'#define USE_AOMAP':'',parameters.emissiveMap?'#define USE_EMISSIVEMAP':'',parameters.bumpMap?'#define USE_BUMPMAP':'',parameters.normalMap?'#define USE_NORMALMAP':'',parameters.normalMap&&parameters.objectSpaceNormalMap?'#define OBJECTSPACE_NORMALMAP':'',parameters.normalMap&&parameters.tangentSpaceNormalMap?'#define TANGENTSPACE_NORMALMAP':'',parameters.clearcoatMap?'#define USE_CLEARCOATMAP':'',parameters.clearcoatRoughnessMap?'#define USE_CLEARCOAT_ROUGHNESSMAP':'',parameters.clearcoatNormalMap?'#define USE_CLEARCOAT_NORMALMAP':'',parameters.specularMap?'#define USE_SPECULARMAP':'',parameters.roughnessMap?'#define USE_ROUGHNESSMAP':'',parameters.metalnessMap?'#define USE_METALNESSMAP':'',parameters.alphaMap?'#define USE_ALPHAMAP':'',parameters.sheen?'#define USE_SHEEN':'',parameters.transmissionMap?'#define USE_TRANSMISSIONMAP':'',parameters.vertexTangents?'#define USE_TANGENT':'',parameters.vertexColors||parameters.instancingColor?'#define USE_COLOR':'',parameters.vertexUvs?'#define USE_UV':'',parameters.uvsVertexOnly?'#define UVS_VERTEX_ONLY':'',parameters.gradientMap?'#define USE_GRADIENTMAP':'',parameters.flatShading?'#define FLAT_SHADED':'',parameters.doubleSided?'#define DOUBLE_SIDED':'',parameters.flipSided?'#define FLIP_SIDED':'',parameters.shadowMapEnabled?'#define USE_SHADOWMAP':'',parameters.shadowMapEnabled?'#define '+shadowMapTypeDefine:'',parameters.premultipliedAlpha?'#define PREMULTIPLIED_ALPHA':'',parameters.physicallyCorrectLights?'#define PHYSICALLY_CORRECT_LIGHTS':'',parameters.logarithmicDepthBuffer?'#define USE_LOGDEPTHBUF':'',parameters.logarithmicDepthBuffer&&parameters.rendererExtensionFragDepth?'#define USE_LOGDEPTHBUF_EXT':'',(parameters.extensionShaderTextureLOD||parameters.envMap)&&parameters.rendererExtensionShaderTextureLod?'#define TEXTURE_LOD_EXT':'','uniform mat4 viewMatrix;','uniform vec3 cameraPosition;','uniform bool isOrthographic;',parameters.toneMapping!==NoToneMapping?'#define TONE_MAPPING':'',parameters.toneMapping!==NoToneMapping?ShaderChunk['tonemapping_pars_fragment']:'',// this code is required here because it is used by the toneMapping() function defined below
  3259. parameters.toneMapping!==NoToneMapping?getToneMappingFunction('toneMapping',parameters.toneMapping):'',parameters.dithering?'#define DITHERING':'',ShaderChunk['encodings_pars_fragment'],// this code is required here because it is used by the various encoding/decoding function defined below
  3260. parameters.map?getTexelDecodingFunction('mapTexelToLinear',parameters.mapEncoding):'',parameters.matcap?getTexelDecodingFunction('matcapTexelToLinear',parameters.matcapEncoding):'',parameters.envMap?getTexelDecodingFunction('envMapTexelToLinear',parameters.envMapEncoding):'',parameters.emissiveMap?getTexelDecodingFunction('emissiveMapTexelToLinear',parameters.emissiveMapEncoding):'',parameters.lightMap?getTexelDecodingFunction('lightMapTexelToLinear',parameters.lightMapEncoding):'',getTexelEncodingFunction('linearToOutputTexel',parameters.outputEncoding),parameters.depthPacking?'#define DEPTH_PACKING '+parameters.depthPacking:'','\n'].filter(filterEmptyLine).join('\n');}vertexShader=resolveIncludes(vertexShader);vertexShader=replaceLightNums(vertexShader,parameters);vertexShader=replaceClippingPlaneNums(vertexShader,parameters);fragmentShader=resolveIncludes(fragmentShader);fragmentShader=replaceLightNums(fragmentShader,parameters);fragmentShader=replaceClippingPlaneNums(fragmentShader,parameters);vertexShader=unrollLoops(vertexShader);fragmentShader=unrollLoops(fragmentShader);if(parameters.isWebGL2&&parameters.isRawShaderMaterial!==true){// GLSL 3.0 conversion for built-in materials and ShaderMaterial
  3261. versionString='#version 300 es\n';prefixVertex=['#define attribute in','#define varying out','#define texture2D texture'].join('\n')+'\n'+prefixVertex;prefixFragment=['#define varying in',parameters.glslVersion===GLSL3?'':'out highp vec4 pc_fragColor;',parameters.glslVersion===GLSL3?'':'#define gl_FragColor pc_fragColor','#define gl_FragDepthEXT gl_FragDepth','#define texture2D texture','#define textureCube texture','#define texture2DProj textureProj','#define texture2DLodEXT textureLod','#define texture2DProjLodEXT textureProjLod','#define textureCubeLodEXT textureLod','#define texture2DGradEXT textureGrad','#define texture2DProjGradEXT textureProjGrad','#define textureCubeGradEXT textureGrad'].join('\n')+'\n'+prefixFragment;}var vertexGlsl=versionString+prefixVertex+vertexShader;var fragmentGlsl=versionString+prefixFragment+fragmentShader;// console.log( '*VERTEX*', vertexGlsl );
  3262. // console.log( '*FRAGMENT*', fragmentGlsl );
  3263. var glVertexShader=WebGLShader(gl,35633,vertexGlsl);var glFragmentShader=WebGLShader(gl,35632,fragmentGlsl);gl.attachShader(program,glVertexShader);gl.attachShader(program,glFragmentShader);// Force a particular attribute to index 0.
  3264. if(parameters.index0AttributeName!==undefined){gl.bindAttribLocation(program,0,parameters.index0AttributeName);}else if(parameters.morphTargets===true){// programs with morphTargets displace position out of attribute 0
  3265. gl.bindAttribLocation(program,0,'position');}gl.linkProgram(program);// check for link errors
  3266. if(renderer.debug.checkShaderErrors){var programLog=gl.getProgramInfoLog(program).trim();var vertexLog=gl.getShaderInfoLog(glVertexShader).trim();var fragmentLog=gl.getShaderInfoLog(glFragmentShader).trim();var runnable=true;var haveDiagnostics=true;if(gl.getProgramParameter(program,35714)===false){runnable=false;var vertexErrors=getShaderErrors(gl,glVertexShader,'vertex');var fragmentErrors=getShaderErrors(gl,glFragmentShader,'fragment');console.error('THREE.WebGLProgram: shader error: ',gl.getError(),'35715',gl.getProgramParameter(program,35715),'gl.getProgramInfoLog',programLog,vertexErrors,fragmentErrors);//add:
  3267. if(fragmentErrors){console.log(fragmentGlsl.split("\n").map((a,i)=>"".concat(i+1).padEnd(5)+a).join("\n"));}else {console.log(vertexGlsl.split("\n").map((a,i)=>"".concat(i+1).padEnd(5)+a).join("\n"));}}else if(programLog!==''){console.warn('THREE.WebGLProgram: gl.getProgramInfoLog()',programLog);}else if(vertexLog===''||fragmentLog===''){haveDiagnostics=false;}if(haveDiagnostics){this.diagnostics={runnable:runnable,programLog:programLog,vertexShader:{log:vertexLog,prefix:prefixVertex},fragmentShader:{log:fragmentLog,prefix:prefixFragment}};}}// Clean up
  3268. // Crashes in iOS9 and iOS10. #18402
  3269. // gl.detachShader( program, glVertexShader );
  3270. // gl.detachShader( program, glFragmentShader );
  3271. gl.deleteShader(glVertexShader);gl.deleteShader(glFragmentShader);// set up caching for uniform locations
  3272. var cachedUniforms;this.getUniforms=function(){if(cachedUniforms===undefined){cachedUniforms=new WebGLUniforms(gl,program);}return cachedUniforms;};// set up caching for attribute locations
  3273. var cachedAttributes;this.getAttributes=function(){if(cachedAttributes===undefined){cachedAttributes=fetchAttributeLocations(gl,program);}return cachedAttributes;};// free resource
  3274. this.destroy=function(){bindingStates.releaseStatesOfProgram(this);gl.deleteProgram(program);this.program=undefined;};//
  3275. this.name=parameters.shaderName;this.id=programIdCount++;this.cacheKey=cacheKey;this.usedTimes=1;this.program=program;this.vertexShader=glVertexShader;this.fragmentShader=glFragmentShader;return this;}function WebGLPrograms(renderer,cubemaps,extensions,capabilities,bindingStates,clipping){var programs=[];var isWebGL2=capabilities.isWebGL2;var logarithmicDepthBuffer=capabilities.logarithmicDepthBuffer;var floatVertexTextures=capabilities.floatVertexTextures;var maxVertexUniforms=capabilities.maxVertexUniforms;var vertexTextures=capabilities.vertexTextures;var precision=capabilities.precision;var shaderIDs={MeshDepthMaterial:'depth',MeshDistanceMaterial:'distanceRGBA',MeshNormalMaterial:'normal',MeshBasicMaterial:'basic',MeshLambertMaterial:'lambert',MeshPhongMaterial:'phong',MeshToonMaterial:'toon',MeshStandardMaterial:'physical',MeshPhysicalMaterial:'physical',MeshMatcapMaterial:'matcap',LineBasicMaterial:'basic',LineDashedMaterial:'dashed',PointsMaterial:'points',ShadowMaterial:'shadow',SpriteMaterial:'sprite'};var parameterNames=['precision','isWebGL2','supportsVertexTextures','outputEncoding','instancing','instancingColor','map','mapEncoding','matcap','matcapEncoding','envMap','envMapMode','envMapEncoding','envMapCubeUV','lightMap','lightMapEncoding','aoMap','emissiveMap','emissiveMapEncoding','bumpMap','normalMap','objectSpaceNormalMap','tangentSpaceNormalMap','clearcoatMap','clearcoatRoughnessMap','clearcoatNormalMap','displacementMap','specularMap','roughnessMap','metalnessMap','gradientMap','alphaMap','combine','vertexColors','vertexTangents','vertexUvs','uvsVertexOnly','fog','useFog','fogExp2','flatShading','sizeAttenuation','logarithmicDepthBuffer','skinning','maxBones','useVertexTexture','morphTargets','morphNormals','maxMorphTargets','maxMorphNormals','premultipliedAlpha','numDirLights','numPointLights','numSpotLights','numHemiLights','numRectAreaLights','numDirLightShadows','numPointLightShadows','numSpotLightShadows','shadowMapEnabled','shadowMapType','toneMapping','physicallyCorrectLights','alphaTest','doubleSided','flipSided','numClippingPlanes','numClipIntersection','depthPacking','dithering','sheen','transmissionMap'];function getMaxBones(object){var skeleton=object.skeleton;var bones=skeleton.bones;if(floatVertexTextures){return 1024;}else {// default for when object is not specified
  3276. // ( for example when prebuilding shader to be used with multiple objects )
  3277. //
  3278. // - leave some extra space for other uniforms
  3279. // - limit here is ANGLE's 254 max uniform vectors
  3280. // (up to 54 should be safe)
  3281. var nVertexUniforms=maxVertexUniforms;var nVertexMatrices=Math.floor((nVertexUniforms-20)/4);var maxBones=Math.min(nVertexMatrices,bones.length);if(maxBones<bones.length){console.warn('THREE.WebGLRenderer: Skeleton has '+bones.length+' bones. This GPU supports '+maxBones+'.');return 0;}return maxBones;}}function getTextureEncodingFromMap(map){var encoding;if(map&&map.isTexture){encoding=map.encoding;}else if(map&&map.isWebGLRenderTarget){console.warn('THREE.WebGLPrograms.getTextureEncodingFromMap: don\'t use render targets as textures. Use their .texture property instead.');encoding=map.texture.encoding;}else {encoding=LinearEncoding;}return encoding;}function getParameters(material,lights,shadows,scene,object){var fog=scene.fog;var environment=material.isMeshStandardMaterial?scene.environment:null;var envMap=cubemaps.get(material.envMap||environment);var shaderID=shaderIDs[material.type];// heuristics to create shader parameters according to lights in the scene
  3282. // (not to blow over maxLights budget)
  3283. var maxBones=object.isSkinnedMesh?getMaxBones(object):0;if(material.precision!==null){precision=capabilities.getMaxPrecision(material.precision);if(precision!==material.precision){console.warn('THREE.WebGLProgram.getParameters:',material.precision,'not supported, using',precision,'instead.');}}var vertexShader,fragmentShader;if(shaderID){var shader=ShaderLib[shaderID];vertexShader=shader.vertexShader;fragmentShader=shader.fragmentShader;}else {vertexShader=material.vertexShader;fragmentShader=material.fragmentShader;}var currentRenderTarget=renderer.getRenderTarget();var parameters={isWebGL2:isWebGL2,shaderID:shaderID,shaderName:material.type,vertexShader:vertexShader,fragmentShader:fragmentShader,defines:material.defines,isRawShaderMaterial:material.isRawShaderMaterial===true,glslVersion:material.glslVersion,precision:precision,instancing:object.isInstancedMesh===true,instancingColor:object.isInstancedMesh===true&&object.instanceColor!==null,supportsVertexTextures:vertexTextures,outputEncoding:currentRenderTarget!==null?getTextureEncodingFromMap(currentRenderTarget.texture):renderer.outputEncoding,map:!!material.map,mapEncoding:getTextureEncodingFromMap(material.map),matcap:!!material.matcap,matcapEncoding:getTextureEncodingFromMap(material.matcap),envMap:!!envMap,envMapMode:envMap&&envMap.mapping,envMapEncoding:getTextureEncodingFromMap(envMap),envMapCubeUV:!!envMap&&(envMap.mapping===CubeUVReflectionMapping||envMap.mapping===CubeUVRefractionMapping),lightMap:!!material.lightMap,lightMapEncoding:getTextureEncodingFromMap(material.lightMap),aoMap:!!material.aoMap,emissiveMap:!!material.emissiveMap,emissiveMapEncoding:getTextureEncodingFromMap(material.emissiveMap),bumpMap:!!material.bumpMap,normalMap:!!material.normalMap,objectSpaceNormalMap:material.normalMapType===ObjectSpaceNormalMap,tangentSpaceNormalMap:material.normalMapType===TangentSpaceNormalMap,clearcoatMap:!!material.clearcoatMap,clearcoatRoughnessMap:!!material.clearcoatRoughnessMap,clearcoatNormalMap:!!material.clearcoatNormalMap,displacementMap:!!material.displacementMap,roughnessMap:!!material.roughnessMap,metalnessMap:!!material.metalnessMap,specularMap:!!material.specularMap,alphaMap:!!material.alphaMap,gradientMap:!!material.gradientMap,sheen:!!material.sheen,transmissionMap:!!material.transmissionMap,combine:material.combine,vertexTangents:material.normalMap&&material.vertexTangents,vertexColors:material.vertexColors,vertexUvs:!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatMap||!!material.clearcoatRoughnessMap||!!material.clearcoatNormalMap||!!material.displacementMap||!!material.transmissionMap,uvsVertexOnly:!(!!material.map||!!material.bumpMap||!!material.normalMap||!!material.specularMap||!!material.alphaMap||!!material.emissiveMap||!!material.roughnessMap||!!material.metalnessMap||!!material.clearcoatNormalMap||!!material.transmissionMap)&&!!material.displacementMap,fog:!!fog,useFog:material.fog,fogExp2:fog&&fog.isFogExp2,flatShading:material.flatShading,sizeAttenuation:material.sizeAttenuation,logarithmicDepthBuffer:logarithmicDepthBuffer,skinning:material.skinning&&maxBones>0,maxBones:maxBones,useVertexTexture:floatVertexTextures,morphTargets:material.morphTargets,morphNormals:material.morphNormals,maxMorphTargets:renderer.maxMorphTargets,maxMorphNormals:renderer.maxMorphNormals,numDirLights:lights.directional.length,numPointLights:lights.point.length,numSpotLights:lights.spot.length,numRectAreaLights:lights.rectArea.length,numHemiLights:lights.hemi.length,numDirLightShadows:lights.directionalShadowMap.length,numPointLightShadows:lights.pointShadowMap.length,numSpotLightShadows:lights.spotShadowMap.length,numClippingPlanes:clipping.numPlanes,numClipIntersection:clipping.numIntersection,dithering:material.dithering,shadowMapEnabled:renderer.shadowMap.enabled&&shadows.length>0,shadowMapType:renderer.shadowMap.type,toneMapping:material.toneMapped?renderer.toneMapping:NoToneMapping,physicallyCorrectLights:renderer.physicallyCorrectLights,premultipliedAlpha:material.premultipliedAlpha,alphaTest:material.alphaTest,doubleSided:material.side===DoubleSide,flipSided:material.side===BackSide,depthPacking:material.depthPacking!==undefined?material.depthPacking:false,index0AttributeName:material.index0AttributeName,extensionDerivatives:material.extensions&&material.extensions.derivatives,extensionFragDepth:material.extensions&&material.extensions.fragDepth,extensionDrawBuffers:material.extensions&&material.extensions.drawBuffers,extensionShaderTextureLOD:material.extensions&&material.extensions.shaderTextureLOD,rendererExtensionFragDepth:isWebGL2||extensions.has('EXT_frag_depth'),rendererExtensionDrawBuffers:isWebGL2||extensions.has('WEBGL_draw_buffers'),rendererExtensionShaderTextureLod:isWebGL2||extensions.has('EXT_shader_texture_lod'),customProgramCacheKey:material.customProgramCacheKey()};return parameters;}function getProgramCacheKey(parameters){var array=[];if(parameters.shaderID){array.push(parameters.shaderID);}else {array.push(parameters.fragmentShader);array.push(parameters.vertexShader);}if(parameters.defines!==undefined){for(var name in parameters.defines){array.push(name);array.push(parameters.defines[name]);}}if(parameters.isRawShaderMaterial===false){for(var _i95=0;_i95<parameterNames.length;_i95++){array.push(parameters[parameterNames[_i95]]);}array.push(renderer.outputEncoding);array.push(renderer.gammaFactor);}array.push(parameters.customProgramCacheKey);return array.join();}function getUniforms(material){var shaderID=shaderIDs[material.type];var uniforms;if(shaderID){var shader=ShaderLib[shaderID];uniforms=UniformsUtils.clone(shader.uniforms);}else {uniforms=material.uniforms;}return uniforms;}function acquireProgram(parameters,cacheKey){var program;// Check if code has been already compiled
  3284. for(var p=0,pl=programs.length;p<pl;p++){var preexistingProgram=programs[p];if(preexistingProgram.cacheKey===cacheKey){program=preexistingProgram;++program.usedTimes;break;}}if(program===undefined){program=new WebGLProgram(renderer,cacheKey,parameters,bindingStates);programs.push(program);}return program;}function releaseProgram(program){if(--program.usedTimes===0){// Remove from unordered set
  3285. var _i96=programs.indexOf(program);programs[_i96]=programs[programs.length-1];programs.pop();// Free WebGL resources
  3286. program.destroy();}}return {getParameters:getParameters,getProgramCacheKey:getProgramCacheKey,getUniforms:getUniforms,acquireProgram:acquireProgram,releaseProgram:releaseProgram,// Exposed for resource monitoring & error feedback via renderer.info:
  3287. programs:programs};}function WebGLProperties(){var properties=new WeakMap();function get(object){var map=properties.get(object);if(map===undefined){map={};properties.set(object,map);}return map;}function remove(object){properties.delete(object);}function update(object,key,value){properties.get(object)[key]=value;}function dispose(){properties=new WeakMap();}return {get:get,remove:remove,update:update,dispose:dispose};}function painterSortStable(a,b){if(a.groupOrder!==b.groupOrder){return a.groupOrder-b.groupOrder;}else if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder;}else if(a.program!==b.program){return a.program.id-b.program.id;}else if(a.material.id!==b.material.id){return a.material.id-b.material.id;}else if(a.z!==b.z){return a.z-b.z;}else {return a.id-b.id;}}function reversePainterSortStable(a,b){if(a.groupOrder!==b.groupOrder){return a.groupOrder-b.groupOrder;}else if(a.renderOrder!==b.renderOrder){return a.renderOrder-b.renderOrder;}else if(a.z!==b.z){return b.z-a.z;}else {return a.id-b.id;}}function WebGLRenderList(properties){var renderItems=[];var renderItemsIndex=0;var opaque=[];var transparent=[];var defaultProgram={id:-1};function init(){renderItemsIndex=0;opaque.length=0;transparent.length=0;}function getNextRenderItem(object,geometry,material,groupOrder,z,group){var renderItem=renderItems[renderItemsIndex];var materialProperties=properties.get(material);if(renderItem===undefined){renderItem={id:object.id,object:object,geometry:geometry,material:material,program:materialProperties.program||defaultProgram,groupOrder:groupOrder,renderOrder:object.renderOrder,z:z,group:group};renderItems[renderItemsIndex]=renderItem;}else {renderItem.id=object.id;renderItem.object=object;renderItem.geometry=geometry;renderItem.material=material;renderItem.program=materialProperties.program||defaultProgram;renderItem.groupOrder=groupOrder;renderItem.renderOrder=object.renderOrder;renderItem.z=z;renderItem.group=group;}renderItemsIndex++;return renderItem;}function push(object,geometry,material,groupOrder,z,group){var renderItem=getNextRenderItem(object,geometry,material,groupOrder,z,group);(material.transparent===true?transparent:opaque).push(renderItem);}function unshift(object,geometry,material,groupOrder,z,group){var renderItem=getNextRenderItem(object,geometry,material,groupOrder,z,group);(material.transparent===true?transparent:opaque).unshift(renderItem);}function sort(customOpaqueSort,customTransparentSort){if(opaque.length>1)opaque.sort(customOpaqueSort||painterSortStable);if(transparent.length>1)transparent.sort(customTransparentSort||reversePainterSortStable);}function finish(){// Clear references from inactive renderItems in the list
  3288. for(var _i97=renderItemsIndex,il=renderItems.length;_i97<il;_i97++){var renderItem=renderItems[_i97];if(renderItem.id===null)break;renderItem.id=null;renderItem.object=null;renderItem.geometry=null;renderItem.material=null;renderItem.program=null;renderItem.group=null;}}return {opaque:opaque,transparent:transparent,init:init,push:push,unshift:unshift,finish:finish,sort:sort};}function WebGLRenderLists(properties){var lists=new WeakMap();function get(scene,camera){var cameras=lists.get(scene);var list;if(cameras===undefined){list=new WebGLRenderList(properties);lists.set(scene,new WeakMap());lists.get(scene).set(camera,list);}else {list=cameras.get(camera);if(list===undefined){list=new WebGLRenderList(properties);cameras.set(camera,list);}}return list;}function dispose(){lists=new WeakMap();}return {get:get,dispose:dispose};}function UniformsCache(){var lights={};return {get:function get(light){if(lights[light.id]!==undefined){return lights[light.id];}var uniforms;switch(light.type){case'DirectionalLight':uniforms={direction:new Vector3(),color:new Color()};break;case'SpotLight':uniforms={position:new Vector3(),direction:new Vector3(),color:new Color(),distance:0,coneCos:0,penumbraCos:0,decay:0};break;case'PointLight':uniforms={position:new Vector3(),color:new Color(),distance:0,decay:0};break;case'HemisphereLight':uniforms={direction:new Vector3(),skyColor:new Color(),groundColor:new Color()};break;case'RectAreaLight':uniforms={color:new Color(),position:new Vector3(),halfWidth:new Vector3(),halfHeight:new Vector3()};break;}lights[light.id]=uniforms;return uniforms;}};}function ShadowUniformsCache(){var lights={};return {get:function get(light){if(lights[light.id]!==undefined){return lights[light.id];}var uniforms;switch(light.type){case'DirectionalLight':uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2()};break;case'SpotLight':uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2()};break;case'PointLight':uniforms={shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Vector2(),shadowCameraNear:1,shadowCameraFar:1000};break;// TODO (abelnation): set RectAreaLight shadow uniforms
  3289. }lights[light.id]=uniforms;return uniforms;}};}var nextVersion=0;function shadowCastingLightsFirst(lightA,lightB){return (lightB.castShadow?1:0)-(lightA.castShadow?1:0);}function WebGLLights(extensions,capabilities){var cache=new UniformsCache();var shadowCache=ShadowUniformsCache();var state={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotShadow:[],spotShadowMap:[],spotShadowMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[]};for(var _i98=0;_i98<9;_i98++)state.probe.push(new Vector3());var vector3=new Vector3();var matrix4=new Matrix4();var matrix42=new Matrix4();function setup(lights){var r=0,g=0,b=0;for(var _i99=0;_i99<9;_i99++)state.probe[_i99].set(0,0,0);var directionalLength=0;var pointLength=0;var spotLength=0;var rectAreaLength=0;var hemiLength=0;var numDirectionalShadows=0;var numPointShadows=0;var numSpotShadows=0;lights.sort(shadowCastingLightsFirst);for(var _i100=0,l=lights.length;_i100<l;_i100++){var light=lights[_i100];var color=light.color;var intensity=light.intensity;var distance=light.distance;var shadowMap=light.shadow&&light.shadow.map?light.shadow.map.texture:null;if(light.isAmbientLight){r+=color.r*intensity;g+=color.g*intensity;b+=color.b*intensity;}else if(light.isLightProbe){for(var j=0;j<9;j++){state.probe[j].addScaledVector(light.sh.coefficients[j],intensity);}}else if(light.isDirectionalLight){var uniforms=cache.get(light);uniforms.color.copy(light.color).multiplyScalar(light.intensity);if(light.castShadow){var shadow=light.shadow;var shadowUniforms=shadowCache.get(light);shadowUniforms.shadowBias=shadow.bias;shadowUniforms.shadowNormalBias=shadow.normalBias;shadowUniforms.shadowRadius=shadow.radius;shadowUniforms.shadowMapSize=shadow.mapSize;state.directionalShadow[directionalLength]=shadowUniforms;state.directionalShadowMap[directionalLength]=shadowMap;state.directionalShadowMatrix[directionalLength]=light.shadow.matrix;numDirectionalShadows++;}state.directional[directionalLength]=uniforms;directionalLength++;}else if(light.isSpotLight){var _uniforms=cache.get(light);_uniforms.position.setFromMatrixPosition(light.matrixWorld);_uniforms.color.copy(color).multiplyScalar(intensity);_uniforms.distance=distance;_uniforms.coneCos=Math.cos(light.angle);_uniforms.penumbraCos=Math.cos(light.angle*(1-light.penumbra));_uniforms.decay=light.decay;if(light.castShadow){var _shadow=light.shadow;var _shadowUniforms=shadowCache.get(light);_shadowUniforms.shadowBias=_shadow.bias;_shadowUniforms.shadowNormalBias=_shadow.normalBias;_shadowUniforms.shadowRadius=_shadow.radius;_shadowUniforms.shadowMapSize=_shadow.mapSize;state.spotShadow[spotLength]=_shadowUniforms;state.spotShadowMap[spotLength]=shadowMap;state.spotShadowMatrix[spotLength]=light.shadow.matrix;numSpotShadows++;}state.spot[spotLength]=_uniforms;spotLength++;}else if(light.isRectAreaLight){var _uniforms2=cache.get(light);// (a) intensity is the total visible light emitted
  3290. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  3291. // (b) intensity is the brightness of the light
  3292. _uniforms2.color.copy(color).multiplyScalar(intensity);_uniforms2.halfWidth.set(light.width*0.5,0.0,0.0);_uniforms2.halfHeight.set(0.0,light.height*0.5,0.0);state.rectArea[rectAreaLength]=_uniforms2;rectAreaLength++;}else if(light.isPointLight){var _uniforms3=cache.get(light);_uniforms3.color.copy(light.color).multiplyScalar(light.intensity);_uniforms3.distance=light.distance;_uniforms3.decay=light.decay;if(light.castShadow){var _shadow2=light.shadow;var _shadowUniforms2=shadowCache.get(light);_shadowUniforms2.shadowBias=_shadow2.bias;_shadowUniforms2.shadowNormalBias=_shadow2.normalBias;_shadowUniforms2.shadowRadius=_shadow2.radius;_shadowUniforms2.shadowMapSize=_shadow2.mapSize;_shadowUniforms2.shadowCameraNear=_shadow2.camera.near;_shadowUniforms2.shadowCameraFar=_shadow2.camera.far;state.pointShadow[pointLength]=_shadowUniforms2;state.pointShadowMap[pointLength]=shadowMap;state.pointShadowMatrix[pointLength]=light.shadow.matrix;numPointShadows++;}state.point[pointLength]=_uniforms3;pointLength++;}else if(light.isHemisphereLight){var _uniforms4=cache.get(light);_uniforms4.skyColor.copy(light.color).multiplyScalar(intensity);_uniforms4.groundColor.copy(light.groundColor).multiplyScalar(intensity);state.hemi[hemiLength]=_uniforms4;hemiLength++;}}if(rectAreaLength>0){if(capabilities.isWebGL2){// WebGL 2
  3293. state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2;}else {// WebGL 1
  3294. if(extensions.has('OES_texture_float_linear')===true){state.rectAreaLTC1=UniformsLib.LTC_FLOAT_1;state.rectAreaLTC2=UniformsLib.LTC_FLOAT_2;}else if(extensions.has('OES_texture_half_float_linear')===true){state.rectAreaLTC1=UniformsLib.LTC_HALF_1;state.rectAreaLTC2=UniformsLib.LTC_HALF_2;}else {console.error('THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.');}}}state.ambient[0]=r;state.ambient[1]=g;state.ambient[2]=b;var hash=state.hash;if(hash.directionalLength!==directionalLength||hash.pointLength!==pointLength||hash.spotLength!==spotLength||hash.rectAreaLength!==rectAreaLength||hash.hemiLength!==hemiLength||hash.numDirectionalShadows!==numDirectionalShadows||hash.numPointShadows!==numPointShadows||hash.numSpotShadows!==numSpotShadows){state.directional.length=directionalLength;state.spot.length=spotLength;state.rectArea.length=rectAreaLength;state.point.length=pointLength;state.hemi.length=hemiLength;state.directionalShadow.length=numDirectionalShadows;state.directionalShadowMap.length=numDirectionalShadows;state.pointShadow.length=numPointShadows;state.pointShadowMap.length=numPointShadows;state.spotShadow.length=numSpotShadows;state.spotShadowMap.length=numSpotShadows;state.directionalShadowMatrix.length=numDirectionalShadows;state.pointShadowMatrix.length=numPointShadows;state.spotShadowMatrix.length=numSpotShadows;hash.directionalLength=directionalLength;hash.pointLength=pointLength;hash.spotLength=spotLength;hash.rectAreaLength=rectAreaLength;hash.hemiLength=hemiLength;hash.numDirectionalShadows=numDirectionalShadows;hash.numPointShadows=numPointShadows;hash.numSpotShadows=numSpotShadows;state.version=nextVersion++;}}function setupView(lights,camera){var directionalLength=0;var pointLength=0;var spotLength=0;var rectAreaLength=0;var hemiLength=0;var viewMatrix=camera.matrixWorldInverse;for(var _i101=0,l=lights.length;_i101<l;_i101++){var light=lights[_i101];if(light.isDirectionalLight){var uniforms=state.directional[directionalLength];uniforms.direction.setFromMatrixPosition(light.matrixWorld);vector3.setFromMatrixPosition(light.target.matrixWorld);uniforms.direction.sub(vector3);uniforms.direction.transformDirection(viewMatrix);directionalLength++;}else if(light.isSpotLight){var _uniforms5=state.spot[spotLength];_uniforms5.position.setFromMatrixPosition(light.matrixWorld);_uniforms5.position.applyMatrix4(viewMatrix);_uniforms5.direction.setFromMatrixPosition(light.matrixWorld);vector3.setFromMatrixPosition(light.target.matrixWorld);_uniforms5.direction.sub(vector3);_uniforms5.direction.transformDirection(viewMatrix);spotLength++;}else if(light.isRectAreaLight){var _uniforms6=state.rectArea[rectAreaLength];_uniforms6.position.setFromMatrixPosition(light.matrixWorld);_uniforms6.position.applyMatrix4(viewMatrix);// extract local rotation of light to derive width/height half vectors
  3295. matrix42.identity();matrix4.copy(light.matrixWorld);matrix4.premultiply(viewMatrix);matrix42.extractRotation(matrix4);_uniforms6.halfWidth.set(light.width*0.5,0.0,0.0);_uniforms6.halfHeight.set(0.0,light.height*0.5,0.0);_uniforms6.halfWidth.applyMatrix4(matrix42);_uniforms6.halfHeight.applyMatrix4(matrix42);rectAreaLength++;}else if(light.isPointLight){var _uniforms7=state.point[pointLength];_uniforms7.position.setFromMatrixPosition(light.matrixWorld);_uniforms7.position.applyMatrix4(viewMatrix);pointLength++;}else if(light.isHemisphereLight){var _uniforms8=state.hemi[hemiLength];_uniforms8.direction.setFromMatrixPosition(light.matrixWorld);_uniforms8.direction.transformDirection(viewMatrix);_uniforms8.direction.normalize();hemiLength++;}}}return {setup:setup,setupView:setupView,state:state};}function WebGLRenderState(extensions,capabilities){var lights=new WebGLLights(extensions,capabilities);var lightsArray=[];var shadowsArray=[];function init(){lightsArray.length=0;shadowsArray.length=0;}function pushLight(light){lightsArray.push(light);}function pushShadow(shadowLight){shadowsArray.push(shadowLight);}function setupLights(){lights.setup(lightsArray);}function setupLightsView(camera){lights.setupView(lightsArray,camera);}var state={lightsArray:lightsArray,shadowsArray:shadowsArray,lights:lights};return {init:init,state:state,setupLights:setupLights,setupLightsView:setupLightsView,pushLight:pushLight,pushShadow:pushShadow};}function WebGLRenderStates(extensions,capabilities){var renderStates=new WeakMap();function get(scene){var renderCallDepth=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var renderState;if(renderStates.has(scene)===false){renderState=new WebGLRenderState(extensions,capabilities);renderStates.set(scene,[]);renderStates.get(scene).push(renderState);}else {if(renderCallDepth>=renderStates.get(scene).length){renderState=new WebGLRenderState(extensions,capabilities);renderStates.get(scene).push(renderState);}else {renderState=renderStates.get(scene)[renderCallDepth];}}return renderState;}function dispose(){renderStates=new WeakMap();}return {get:get,dispose:dispose};}/**
  3296. * parameters = {
  3297. *
  3298. * opacity: <float>,
  3299. *
  3300. * map: new THREE.Texture( <Image> ),
  3301. *
  3302. * alphaMap: new THREE.Texture( <Image> ),
  3303. *
  3304. * displacementMap: new THREE.Texture( <Image> ),
  3305. * displacementScale: <float>,
  3306. * displacementBias: <float>,
  3307. *
  3308. * wireframe: <boolean>,
  3309. * wireframeLinewidth: <float>
  3310. * }
  3311. */function MeshDepthMaterial(parameters){Material.call(this);this.type='MeshDepthMaterial';this.depthPacking=BasicDepthPacking;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.setValues(parameters);}MeshDepthMaterial.prototype=Object.create(Material.prototype);MeshDepthMaterial.prototype.constructor=MeshDepthMaterial;MeshDepthMaterial.prototype.isMeshDepthMaterial=true;MeshDepthMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.depthPacking=source.depthPacking;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;return this;};/**
  3312. * parameters = {
  3313. *
  3314. * referencePosition: <float>,
  3315. * nearDistance: <float>,
  3316. * farDistance: <float>,
  3317. *
  3318. * skinning: <bool>,
  3319. * morphTargets: <bool>,
  3320. *
  3321. * map: new THREE.Texture( <Image> ),
  3322. *
  3323. * alphaMap: new THREE.Texture( <Image> ),
  3324. *
  3325. * displacementMap: new THREE.Texture( <Image> ),
  3326. * displacementScale: <float>,
  3327. * displacementBias: <float>
  3328. *
  3329. * }
  3330. */function MeshDistanceMaterial(parameters){Material.call(this);this.type='MeshDistanceMaterial';this.referencePosition=new Vector3();this.nearDistance=1;this.farDistance=1000;this.skinning=false;this.morphTargets=false;this.map=null;this.alphaMap=null;this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.fog=false;this.setValues(parameters);}MeshDistanceMaterial.prototype=Object.create(Material.prototype);MeshDistanceMaterial.prototype.constructor=MeshDistanceMaterial;MeshDistanceMaterial.prototype.isMeshDistanceMaterial=true;MeshDistanceMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.referencePosition.copy(source.referencePosition);this.nearDistance=source.nearDistance;this.farDistance=source.farDistance;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.map=source.map;this.alphaMap=source.alphaMap;this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;return this;};var vsm_frag="uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\n#include <packing>\nvoid main() {\n\tfloat mean = 0.0;\n\tfloat squared_mean = 0.0;\n\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy ) / resolution ) );\n\tfor ( float i = -1.0; i < 1.0 ; i += SAMPLE_RATE) {\n\t\t#ifdef HORIZONTAL_PASS\n\t\t\tvec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( i, 0.0 ) * radius ) / resolution ) );\n\t\t\tmean += distribution.x;\n\t\t\tsquared_mean += distribution.y * distribution.y + distribution.x * distribution.x;\n\t\t#else\n\t\t\tfloat depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, i ) * radius ) / resolution ) );\n\t\t\tmean += depth;\n\t\t\tsquared_mean += depth * depth;\n\t\t#endif\n\t}\n\tmean = mean * HALF_SAMPLE_RATE;\n\tsquared_mean = squared_mean * HALF_SAMPLE_RATE;\n\tfloat std_dev = sqrt( squared_mean - mean * mean );\n\tgl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );\n}";var vsm_vert="void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";function WebGLShadowMap(_renderer,_objects,maxTextureSize){var _frustum=new Frustum();var _shadowMapSize=new Vector2(),_viewportSize=new Vector2(),_viewport=new Vector4(),_depthMaterials=[],_distanceMaterials=[],_materialCache={};var shadowSide={0:BackSide,1:FrontSide,2:DoubleSide};var shadowMaterialVertical=new ShaderMaterial({defines:{SAMPLE_RATE:2.0/8.0,HALF_SAMPLE_RATE:1.0/8.0},uniforms:{shadow_pass:{value:null},resolution:{value:new Vector2()},radius:{value:4.0}},vertexShader:vsm_vert,fragmentShader:vsm_frag});var shadowMaterialHorizontal=shadowMaterialVertical.clone();shadowMaterialHorizontal.defines.HORIZONTAL_PASS=1;var fullScreenTri=new BufferGeometry();fullScreenTri.setAttribute('position',new BufferAttribute(new Float32Array([-1,-1,0.5,3,-1,0.5,-1,3,0.5]),3));var fullScreenMesh=new Mesh(fullScreenTri,shadowMaterialVertical);var scope=this;this.enabled=false;this.autoUpdate=true;this.needsUpdate=false;this.type=PCFShadowMap;this.render=function(lights,scene,camera){if(scope.enabled===false)return;if(scope.autoUpdate===false&&scope.needsUpdate===false)return;if(lights.length===0)return;var currentRenderTarget=_renderer.getRenderTarget();var activeCubeFace=_renderer.getActiveCubeFace();var activeMipmapLevel=_renderer.getActiveMipmapLevel();var _state=_renderer.state;// Set GL state for depth map.
  3331. _state.setBlending(NoBlending);_state.buffers.color.setClear(1,1,1,1);_state.buffers.depth.setTest(true);_state.setScissorTest(false);// render depth map
  3332. for(var _i102=0,il=lights.length;_i102<il;_i102++){var light=lights[_i102];var shadow=light.shadow;if(shadow===undefined){console.warn('THREE.WebGLShadowMap:',light,'has no shadow.');continue;}if(shadow.autoUpdate===false&&shadow.needsUpdate===false)continue;_shadowMapSize.copy(shadow.mapSize);var shadowFrameExtents=shadow.getFrameExtents();_shadowMapSize.multiply(shadowFrameExtents);_viewportSize.copy(shadow.mapSize);if(_shadowMapSize.x>maxTextureSize||_shadowMapSize.y>maxTextureSize){if(_shadowMapSize.x>maxTextureSize){_viewportSize.x=Math.floor(maxTextureSize/shadowFrameExtents.x);_shadowMapSize.x=_viewportSize.x*shadowFrameExtents.x;shadow.mapSize.x=_viewportSize.x;}if(_shadowMapSize.y>maxTextureSize){_viewportSize.y=Math.floor(maxTextureSize/shadowFrameExtents.y);_shadowMapSize.y=_viewportSize.y*shadowFrameExtents.y;shadow.mapSize.y=_viewportSize.y;}}if(shadow.map===null&&!shadow.isPointLightShadow&&this.type===VSMShadowMap){var pars={minFilter:LinearFilter,magFilter:LinearFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.map.texture.name=light.name+'.shadowMap';shadow.mapPass=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,pars);shadow.camera.updateProjectionMatrix();}if(shadow.map===null){var _pars={minFilter:NearestFilter,magFilter:NearestFilter,format:RGBAFormat};shadow.map=new WebGLRenderTarget(_shadowMapSize.x,_shadowMapSize.y,_pars);shadow.map.texture.name=light.name+'.shadowMap';shadow.camera.updateProjectionMatrix();}_renderer.setRenderTarget(shadow.map);_renderer.clear();var viewportCount=shadow.getViewportCount();for(var vp=0;vp<viewportCount;vp++){var viewport=shadow.getViewport(vp);_viewport.set(_viewportSize.x*viewport.x,_viewportSize.y*viewport.y,_viewportSize.x*viewport.z,_viewportSize.y*viewport.w);_state.viewport(_viewport);shadow.updateMatrices(light,vp);_frustum=shadow.getFrustum();renderObject(scene,camera,shadow.camera,light,this.type);}// do blur pass for VSM
  3333. if(!shadow.isPointLightShadow&&this.type===VSMShadowMap){VSMPass(shadow,camera);}shadow.needsUpdate=false;}scope.needsUpdate=false;_renderer.setRenderTarget(currentRenderTarget,activeCubeFace,activeMipmapLevel);};function VSMPass(shadow,camera){var geometry=_objects.update(fullScreenMesh);// vertical pass
  3334. shadowMaterialVertical.uniforms.shadow_pass.value=shadow.map.texture;shadowMaterialVertical.uniforms.resolution.value=shadow.mapSize;shadowMaterialVertical.uniforms.radius.value=shadow.radius;_renderer.setRenderTarget(shadow.mapPass);_renderer.clear();_renderer.renderBufferDirect(camera,null,geometry,shadowMaterialVertical,fullScreenMesh,null);// horizontal pass
  3335. shadowMaterialHorizontal.uniforms.shadow_pass.value=shadow.mapPass.texture;shadowMaterialHorizontal.uniforms.resolution.value=shadow.mapSize;shadowMaterialHorizontal.uniforms.radius.value=shadow.radius;_renderer.setRenderTarget(shadow.map);_renderer.clear();_renderer.renderBufferDirect(camera,null,geometry,shadowMaterialHorizontal,fullScreenMesh,null);}function getDepthMaterialVariant(useMorphing,useSkinning,useInstancing){var index=useMorphing<<0|useSkinning<<1|useInstancing<<2;var material=_depthMaterials[index];if(material===undefined){material=new MeshDepthMaterial({depthPacking:RGBADepthPacking,morphTargets:useMorphing,skinning:useSkinning});_depthMaterials[index]=material;}return material;}function getDistanceMaterialVariant(useMorphing,useSkinning,useInstancing){var index=useMorphing<<0|useSkinning<<1|useInstancing<<2;var material=_distanceMaterials[index];if(material===undefined){material=new MeshDistanceMaterial({morphTargets:useMorphing,skinning:useSkinning});_distanceMaterials[index]=material;}return material;}function getDepthMaterial(object,geometry,material,light,shadowCameraNear,shadowCameraFar,type){var result=null;var getMaterialVariant=getDepthMaterialVariant;var customMaterial=object.customDepthMaterial;if(light.isPointLight===true){getMaterialVariant=getDistanceMaterialVariant;customMaterial=object.customDistanceMaterial;}if(customMaterial===undefined){var useMorphing=false;if(material.morphTargets===true){useMorphing=geometry.morphAttributes&&geometry.morphAttributes.position&&geometry.morphAttributes.position.length>0;}var useSkinning=false;if(object.isSkinnedMesh===true){if(material.skinning===true){useSkinning=true;}else {console.warn('THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:',object);}}var useInstancing=object.isInstancedMesh===true;result=getMaterialVariant(useMorphing,useSkinning,useInstancing);}else {result=customMaterial;}if(_renderer.localClippingEnabled&&material.clipShadows===true&&material.clippingPlanes.length!==0){// in this case we need a unique material instance reflecting the
  3336. // appropriate state
  3337. var keyA=result.uuid,keyB=material.uuid;var materialsForVariant=_materialCache[keyA];if(materialsForVariant===undefined){materialsForVariant={};_materialCache[keyA]=materialsForVariant;}var cachedMaterial=materialsForVariant[keyB];if(cachedMaterial===undefined){cachedMaterial=result.clone();materialsForVariant[keyB]=cachedMaterial;}result=cachedMaterial;}result.visible=material.visible;result.wireframe=material.wireframe;if(type===VSMShadowMap){result.side=material.shadowSide!==null?material.shadowSide:material.side;}else {result.side=material.shadowSide!==null?material.shadowSide:shadowSide[material.side];}result.clipShadows=material.clipShadows;result.clippingPlanes=material.clippingPlanes;result.clipIntersection=material.clipIntersection;result.wireframeLinewidth=material.wireframeLinewidth;result.linewidth=material.linewidth;if(light.isPointLight===true&&result.isMeshDistanceMaterial===true){result.referencePosition.setFromMatrixPosition(light.matrixWorld);result.nearDistance=shadowCameraNear;result.farDistance=shadowCameraFar;}return result;}function renderObject(object,camera,shadowCamera,light,type){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible&&(object.isMesh||object.isLine||object.isPoints)){if((object.castShadow||object.receiveShadow&&type===VSMShadowMap)&&(!object.frustumCulled||_frustum.intersectsObject(object))){object.modelViewMatrix.multiplyMatrices(shadowCamera.matrixWorldInverse,object.matrixWorld);var geometry=_objects.update(object);var material=object.material;if(Array.isArray(material)){var groups=geometry.groups;for(var k=0,kl=groups.length;k<kl;k++){var group=groups[k];var groupMaterial=material[group.materialIndex];if(groupMaterial&&groupMaterial.visible){var depthMaterial=getDepthMaterial(object,geometry,groupMaterial,light,shadowCamera.near,shadowCamera.far,type);_renderer.renderBufferDirect(shadowCamera,null,geometry,depthMaterial,object,group);}}}else if(material.visible){var _depthMaterial=getDepthMaterial(object,geometry,material,light,shadowCamera.near,shadowCamera.far,type);_renderer.renderBufferDirect(shadowCamera,null,geometry,_depthMaterial,object,null);}}}var children=object.children;for(var _i103=0,l=children.length;_i103<l;_i103++){renderObject(children[_i103],camera,shadowCamera,light,type);}}}function WebGLState(gl,extensions,capabilities){var isWebGL2=capabilities.isWebGL2;function ColorBuffer(){var locked=false;var color=new Vector4();var currentColorMask=null;var currentColorClear=new Vector4(0,0,0,0);return {setMask:function setMask(colorMask){if(currentColorMask!==colorMask&&!locked){gl.colorMask(colorMask,colorMask,colorMask,colorMask);currentColorMask=colorMask;}},setLocked:function setLocked(lock){locked=lock;},setClear:function setClear(r,g,b,a,premultipliedAlpha){if(premultipliedAlpha===true){r*=a;g*=a;b*=a;}color.set(r,g,b,a);if(currentColorClear.equals(color)===false){gl.clearColor(r,g,b,a);currentColorClear.copy(color);}},reset:function reset(){locked=false;currentColorMask=null;currentColorClear.set(-1,0,0,0);// set to invalid state
  3338. }};}function DepthBuffer(){var locked=false;var currentDepthMask=null;var currentDepthFunc=null;var currentDepthClear=null;return {setTest:function setTest(depthTest){if(depthTest){enable(2929);}else {disable(2929);}},setMask:function setMask(depthMask){if(currentDepthMask!==depthMask&&!locked){gl.depthMask(depthMask);currentDepthMask=depthMask;}},setFunc:function setFunc(depthFunc){if(currentDepthFunc!==depthFunc){if(depthFunc){switch(depthFunc){case NeverDepth:gl.depthFunc(512);break;case AlwaysDepth:gl.depthFunc(519);break;case LessDepth:gl.depthFunc(513);break;case LessEqualDepth:gl.depthFunc(515);break;case EqualDepth:gl.depthFunc(514);break;case GreaterEqualDepth:gl.depthFunc(518);break;case GreaterDepth:gl.depthFunc(516);break;case NotEqualDepth:gl.depthFunc(517);break;default:gl.depthFunc(515);}}else {gl.depthFunc(515);}currentDepthFunc=depthFunc;}},setLocked:function setLocked(lock){locked=lock;},setClear:function setClear(depth){if(currentDepthClear!==depth){gl.clearDepth(depth);currentDepthClear=depth;}},reset:function reset(){locked=false;currentDepthMask=null;currentDepthFunc=null;currentDepthClear=null;}};}function StencilBuffer(){var locked=false;var currentStencilMask=null;var currentStencilFunc=null;var currentStencilRef=null;var currentStencilFuncMask=null;var currentStencilFail=null;var currentStencilZFail=null;var currentStencilZPass=null;var currentStencilClear=null;return {setTest:function setTest(stencilTest){if(!locked){if(stencilTest){enable(2960);}else {disable(2960);}}},setMask:function setMask(stencilMask){if(currentStencilMask!==stencilMask&&!locked){gl.stencilMask(stencilMask);currentStencilMask=stencilMask;}},setFunc:function setFunc(stencilFunc,stencilRef,stencilMask){if(currentStencilFunc!==stencilFunc||currentStencilRef!==stencilRef||currentStencilFuncMask!==stencilMask){gl.stencilFunc(stencilFunc,stencilRef,stencilMask);currentStencilFunc=stencilFunc;currentStencilRef=stencilRef;currentStencilFuncMask=stencilMask;}},setOp:function setOp(stencilFail,stencilZFail,stencilZPass){if(currentStencilFail!==stencilFail||currentStencilZFail!==stencilZFail||currentStencilZPass!==stencilZPass){gl.stencilOp(stencilFail,stencilZFail,stencilZPass);currentStencilFail=stencilFail;currentStencilZFail=stencilZFail;currentStencilZPass=stencilZPass;}},setLocked:function setLocked(lock){locked=lock;},setClear:function setClear(stencil){if(currentStencilClear!==stencil){gl.clearStencil(stencil);currentStencilClear=stencil;}},reset:function reset(){locked=false;currentStencilMask=null;currentStencilFunc=null;currentStencilRef=null;currentStencilFuncMask=null;currentStencilFail=null;currentStencilZFail=null;currentStencilZPass=null;currentStencilClear=null;}};}//
  3339. var colorBuffer=new ColorBuffer();var depthBuffer=new DepthBuffer();var stencilBuffer=new StencilBuffer();var enabledCapabilities={};var currentProgram=null;var currentBlendingEnabled=null;var currentBlending=null;var currentBlendEquation=null;var currentBlendSrc=null;var currentBlendDst=null;var currentBlendEquationAlpha=null;var currentBlendSrcAlpha=null;var currentBlendDstAlpha=null;var currentPremultipledAlpha=false;var currentFlipSided=null;var currentCullFace=null;var currentLineWidth=null;var currentPolygonOffsetFactor=null;var currentPolygonOffsetUnits=null;var maxTextures=gl.getParameter(35661);var lineWidthAvailable=false;var version=0;var glVersion=gl.getParameter(7938);if(glVersion.indexOf('WebGL')!==-1){version=parseFloat(/^WebGL (\d)/.exec(glVersion)[1]);lineWidthAvailable=version>=1.0;}else if(glVersion.indexOf('OpenGL ES')!==-1){version=parseFloat(/^OpenGL ES (\d)/.exec(glVersion)[1]);lineWidthAvailable=version>=2.0;}var currentTextureSlot=null;var currentBoundTextures={};var currentScissor=new Vector4();var currentViewport=new Vector4();function createTexture(type,target,count){var data=new Uint8Array(4);// 4 is required to match default unpack alignment of 4.
  3340. var texture=gl.createTexture();gl.bindTexture(type,texture);gl.texParameteri(type,10241,9728);gl.texParameteri(type,10240,9728);for(var _i104=0;_i104<count;_i104++){gl.texImage2D(target+_i104,0,6408,1,1,0,6408,5121,data);}return texture;}var emptyTextures={};emptyTextures[3553]=createTexture(3553,3553,1);emptyTextures[34067]=createTexture(34067,34069,6);// init
  3341. colorBuffer.setClear(0,0,0,1);depthBuffer.setClear(1);stencilBuffer.setClear(0);enable(2929);depthBuffer.setFunc(LessEqualDepth);setFlipSided(false);setCullFace(CullFaceBack);enable(2884);setBlending(NoBlending);//
  3342. function enable(id){if(enabledCapabilities[id]!==true){gl.enable(id);enabledCapabilities[id]=true;}}function disable(id){if(enabledCapabilities[id]!==false){gl.disable(id);enabledCapabilities[id]=false;}}function useProgram(program){if(currentProgram!==program){gl.useProgram(program);currentProgram=program;return true;}return false;}var equationToGL={[AddEquation]:32774,[SubtractEquation]:32778,[ReverseSubtractEquation]:32779};if(isWebGL2){equationToGL[MinEquation]=32775;equationToGL[MaxEquation]=32776;}else {var extension=extensions.get('EXT_blend_minmax');if(extension!==null){equationToGL[MinEquation]=extension.MIN_EXT;equationToGL[MaxEquation]=extension.MAX_EXT;}}var factorToGL={[ZeroFactor]:0,[OneFactor]:1,[SrcColorFactor]:768,[SrcAlphaFactor]:770,[SrcAlphaSaturateFactor]:776,[DstColorFactor]:774,[DstAlphaFactor]:772,[OneMinusSrcColorFactor]:769,[OneMinusSrcAlphaFactor]:771,[OneMinusDstColorFactor]:775,[OneMinusDstAlphaFactor]:773};function setBlending(blending,blendEquation,blendSrc,blendDst,blendEquationAlpha,blendSrcAlpha,blendDstAlpha,premultipliedAlpha){if(blending===NoBlending){if(currentBlendingEnabled){disable(3042);currentBlendingEnabled=false;}return;}if(!currentBlendingEnabled){enable(3042);currentBlendingEnabled=true;}if(blending!==CustomBlending){if(blending!==currentBlending||premultipliedAlpha!==currentPremultipledAlpha){if(currentBlendEquation!==AddEquation||currentBlendEquationAlpha!==AddEquation){gl.blendEquation(32774);currentBlendEquation=AddEquation;currentBlendEquationAlpha=AddEquation;}if(premultipliedAlpha){switch(blending){case NormalBlending:gl.blendFuncSeparate(1,771,1,771);break;case AdditiveBlending:gl.blendFunc(1,1);break;case SubtractiveBlending:gl.blendFuncSeparate(0,0,769,771);break;case MultiplyBlending:gl.blendFuncSeparate(0,768,0,770);break;default:console.error('THREE.WebGLState: Invalid blending: ',blending);break;}}else {switch(blending){case NormalBlending:gl.blendFuncSeparate(770,771,1,771);break;case AdditiveBlending:gl.blendFunc(770,1);break;case SubtractiveBlending:gl.blendFunc(0,769);break;case MultiplyBlending:gl.blendFunc(0,768);break;default:console.error('THREE.WebGLState: Invalid blending: ',blending);break;}}currentBlendSrc=null;currentBlendDst=null;currentBlendSrcAlpha=null;currentBlendDstAlpha=null;currentBlending=blending;currentPremultipledAlpha=premultipliedAlpha;}return;}// custom blending
  3343. blendEquationAlpha=blendEquationAlpha||blendEquation;blendSrcAlpha=blendSrcAlpha||blendSrc;blendDstAlpha=blendDstAlpha||blendDst;if(blendEquation!==currentBlendEquation||blendEquationAlpha!==currentBlendEquationAlpha){gl.blendEquationSeparate(equationToGL[blendEquation],equationToGL[blendEquationAlpha]);currentBlendEquation=blendEquation;currentBlendEquationAlpha=blendEquationAlpha;}if(blendSrc!==currentBlendSrc||blendDst!==currentBlendDst||blendSrcAlpha!==currentBlendSrcAlpha||blendDstAlpha!==currentBlendDstAlpha){gl.blendFuncSeparate(factorToGL[blendSrc],factorToGL[blendDst],factorToGL[blendSrcAlpha],factorToGL[blendDstAlpha]);currentBlendSrc=blendSrc;currentBlendDst=blendDst;currentBlendSrcAlpha=blendSrcAlpha;currentBlendDstAlpha=blendDstAlpha;}currentBlending=blending;currentPremultipledAlpha=null;}function setMaterial(material,frontFaceCW){material.side===DoubleSide?disable(2884):enable(2884);var flipSided=material.side===BackSide;if(frontFaceCW)flipSided=!flipSided;setFlipSided(flipSided);material.blending===NormalBlending&&material.transparent===false?setBlending(NoBlending):setBlending(material.blending,material.blendEquation,material.blendSrc,material.blendDst,material.blendEquationAlpha,material.blendSrcAlpha,material.blendDstAlpha,material.premultipliedAlpha);depthBuffer.setFunc(material.depthFunc);depthBuffer.setTest(material.depthTest);depthBuffer.setMask(material.depthWrite);colorBuffer.setMask(material.colorWrite);var stencilWrite=material.stencilWrite;stencilBuffer.setTest(stencilWrite);if(stencilWrite){stencilBuffer.setMask(material.stencilWriteMask);stencilBuffer.setFunc(material.stencilFunc,material.stencilRef,material.stencilFuncMask);stencilBuffer.setOp(material.stencilFail,material.stencilZFail,material.stencilZPass);}setPolygonOffset(material.polygonOffset,material.polygonOffsetFactor,material.polygonOffsetUnits);}//
  3344. function setFlipSided(flipSided){if(currentFlipSided!==flipSided){if(flipSided){gl.frontFace(2304);}else {gl.frontFace(2305);}currentFlipSided=flipSided;}}function setCullFace(cullFace){if(cullFace!==CullFaceNone){enable(2884);if(cullFace!==currentCullFace){if(cullFace===CullFaceBack){gl.cullFace(1029);}else if(cullFace===CullFaceFront){gl.cullFace(1028);}else {gl.cullFace(1032);}}}else {disable(2884);}currentCullFace=cullFace;}function setLineWidth(width){if(width!==currentLineWidth){if(lineWidthAvailable)gl.lineWidth(width);currentLineWidth=width;}}function setPolygonOffset(polygonOffset,factor,units){if(polygonOffset){enable(32823);if(currentPolygonOffsetFactor!==factor||currentPolygonOffsetUnits!==units){gl.polygonOffset(factor,units);currentPolygonOffsetFactor=factor;currentPolygonOffsetUnits=units;}}else {disable(32823);}}function setScissorTest(scissorTest){if(scissorTest){enable(3089);}else {disable(3089);}}// texture
  3345. function activeTexture(webglSlot){if(webglSlot===undefined)webglSlot=33984+maxTextures-1;if(currentTextureSlot!==webglSlot){gl.activeTexture(webglSlot);currentTextureSlot=webglSlot;}}function bindTexture(webglType,webglTexture){if(currentTextureSlot===null){activeTexture();}var boundTexture=currentBoundTextures[currentTextureSlot];if(boundTexture===undefined){boundTexture={type:undefined,texture:undefined};currentBoundTextures[currentTextureSlot]=boundTexture;}if(boundTexture.type!==webglType||boundTexture.texture!==webglTexture){gl.bindTexture(webglType,webglTexture||emptyTextures[webglType]);boundTexture.type=webglType;boundTexture.texture=webglTexture;}}function unbindTexture(){var boundTexture=currentBoundTextures[currentTextureSlot];if(boundTexture!==undefined&&boundTexture.type!==undefined){gl.bindTexture(boundTexture.type,null);boundTexture.type=undefined;boundTexture.texture=undefined;}}function compressedTexImage2D(){try{gl.compressedTexImage2D.apply(gl,arguments);}catch(error){console.error('THREE.WebGLState:',error);}}function texImage2D(){try{gl.texImage2D.apply(gl,arguments);}catch(error){console.error('THREE.WebGLState:',error);}}function texImage3D(){try{gl.texImage3D.apply(gl,arguments);}catch(error){console.error('THREE.WebGLState:',error);}}//
  3346. function scissor(scissor){if(currentScissor.equals(scissor)===false){gl.scissor(scissor.x,scissor.y,scissor.z,scissor.w);currentScissor.copy(scissor);}}function viewport(viewport){if(currentViewport.equals(viewport)===false){gl.viewport(viewport.x,viewport.y,viewport.z,viewport.w);currentViewport.copy(viewport);}}//
  3347. function reset(){enabledCapabilities={};currentTextureSlot=null;currentBoundTextures={};currentProgram=null;currentBlendingEnabled=null;currentBlending=null;currentBlendEquation=null;currentBlendSrc=null;currentBlendDst=null;currentBlendEquationAlpha=null;currentBlendSrcAlpha=null;currentBlendDstAlpha=null;currentPremultipledAlpha=false;currentFlipSided=null;currentCullFace=null;currentLineWidth=null;currentPolygonOffsetFactor=null;currentPolygonOffsetUnits=null;colorBuffer.reset();depthBuffer.reset();stencilBuffer.reset();}return {buffers:{color:colorBuffer,depth:depthBuffer,stencil:stencilBuffer},enable:enable,disable:disable,useProgram:useProgram,setBlending:setBlending,setMaterial:setMaterial,setFlipSided:setFlipSided,setCullFace:setCullFace,setLineWidth:setLineWidth,setPolygonOffset:setPolygonOffset,setScissorTest:setScissorTest,activeTexture:activeTexture,bindTexture:bindTexture,unbindTexture:unbindTexture,compressedTexImage2D:compressedTexImage2D,texImage2D:texImage2D,texImage3D:texImage3D,scissor:scissor,viewport:viewport,reset:reset};}function WebGLTextures(_gl,extensions,state,properties,capabilities,utils,info){var isWebGL2=capabilities.isWebGL2;var maxTextures=capabilities.maxTextures;var maxCubemapSize=capabilities.maxCubemapSize;var maxTextureSize=capabilities.maxTextureSize;var maxSamples=capabilities.maxSamples;var _videoTextures=new WeakMap();var _canvas;// cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  3348. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  3349. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  3350. var useOffscreenCanvas=false;try{useOffscreenCanvas=typeof OffscreenCanvas!=='undefined'&&new OffscreenCanvas(1,1).getContext('2d')!==null;}catch(err){// Ignore any errors
  3351. }function createCanvas(width,height){// Use OffscreenCanvas when available. Specially needed in web workers
  3352. return useOffscreenCanvas?new OffscreenCanvas(width,height):document.createElementNS('http://www.w3.org/1999/xhtml','canvas');}function resizeImage(image,needsPowerOfTwo,needsNewCanvas,maxSize){var scale=1;// handle case if texture exceeds max size
  3353. if(image.width>maxSize||image.height>maxSize){scale=maxSize/Math.max(image.width,image.height);}// only perform resize if necessary
  3354. if(scale<1||needsPowerOfTwo===true){// only perform resize for certain image types
  3355. if(typeof HTMLImageElement!=='undefined'&&image instanceof HTMLImageElement||typeof HTMLCanvasElement!=='undefined'&&image instanceof HTMLCanvasElement||typeof ImageBitmap!=='undefined'&&image instanceof ImageBitmap){var floor=needsPowerOfTwo?MathUtils.floorPowerOfTwo:Math.floor;var width=floor(scale*image.width);var height=floor(scale*image.height);if(_canvas===undefined)_canvas=createCanvas(width,height);// cube textures can't reuse the same canvas
  3356. var canvas=needsNewCanvas?createCanvas(width,height):_canvas;canvas.width=width;canvas.height=height;var context=canvas.getContext('2d');context.drawImage(image,0,0,width,height);console.warn('THREE.WebGLRenderer: Texture has been resized from ('+image.width+'x'+image.height+') to ('+width+'x'+height+').');return canvas;}else {if('data'in image){console.warn('THREE.WebGLRenderer: Image in DataTexture is too big ('+image.width+'x'+image.height+').');}return image;}}return image;}function isPowerOfTwo(image){return MathUtils.isPowerOfTwo(image.width)&&MathUtils.isPowerOfTwo(image.height);}function textureNeedsPowerOfTwo(texture){if(isWebGL2)return false;return texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping||texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function textureNeedsGenerateMipmaps(texture,supportsMips){return texture.generateMipmaps&&supportsMips&&texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter;}function generateMipmap(target,texture,width,height){_gl.generateMipmap(target);var textureProperties=properties.get(texture);// Note: Math.log( x ) * Math.LOG2E used instead of Math.log2( x ) which is not supported by IE11
  3357. textureProperties.__maxMipLevel=Math.log(Math.max(width,height))*Math.LOG2E;}function getInternalFormat(internalFormatName,glFormat,glType){if(isWebGL2===false)return glFormat;if(internalFormatName!==null){if(_gl[internalFormatName]!==undefined)return _gl[internalFormatName];console.warn('THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \''+internalFormatName+'\'');}var internalFormat=glFormat;if(glFormat===6403){if(glType===5126)internalFormat=33326;if(glType===5131)internalFormat=33325;if(glType===5121)internalFormat=33321;}if(glFormat===6407){if(glType===5126)internalFormat=34837;if(glType===5131)internalFormat=34843;if(glType===5121)internalFormat=32849;}if(glFormat===6408){if(glType===5126)internalFormat=34836;if(glType===5131)internalFormat=34842;if(glType===5121)internalFormat=32856;}if(internalFormat===33325||internalFormat===33326||internalFormat===34842||internalFormat===34836){extensions.get('EXT_color_buffer_float');}return internalFormat;}// Fallback filters for non-power-of-2 textures
  3358. function filterFallback(f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return 9728;}return 9729;}//
  3359. function onTextureDispose(event){var texture=event.target;texture.removeEventListener('dispose',onTextureDispose);deallocateTexture(texture);if(texture.isVideoTexture){_videoTextures.delete(texture);}info.memory.textures--;}function onRenderTargetDispose(event){var renderTarget=event.target;renderTarget.removeEventListener('dispose',onRenderTargetDispose);deallocateRenderTarget(renderTarget);info.memory.textures--;}//
  3360. function deallocateTexture(texture){var textureProperties=properties.get(texture);if(textureProperties.__webglInit===undefined)return;_gl.deleteTexture(textureProperties.__webglTexture);properties.remove(texture);}function deallocateRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var textureProperties=properties.get(renderTarget.texture);if(!renderTarget)return;if(textureProperties.__webglTexture!==undefined){_gl.deleteTexture(textureProperties.__webglTexture);}if(renderTarget.depthTexture){renderTarget.depthTexture.dispose();}if(renderTarget.isWebGLCubeRenderTarget){for(var _i105=0;_i105<6;_i105++){_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer[_i105]);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer[_i105]);}}else {_gl.deleteFramebuffer(renderTargetProperties.__webglFramebuffer);if(renderTargetProperties.__webglDepthbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthbuffer);if(renderTargetProperties.__webglMultisampledFramebuffer)_gl.deleteFramebuffer(renderTargetProperties.__webglMultisampledFramebuffer);if(renderTargetProperties.__webglColorRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglColorRenderbuffer);if(renderTargetProperties.__webglDepthRenderbuffer)_gl.deleteRenderbuffer(renderTargetProperties.__webglDepthRenderbuffer);}properties.remove(renderTarget.texture);properties.remove(renderTarget);}//
  3361. var textureUnits=0;function resetTextureUnits(){textureUnits=0;}function allocateTextureUnit(){var textureUnit=textureUnits;if(textureUnit>=maxTextures){console.warn('THREE.WebGLTextures: Trying to use '+textureUnit+' texture units while this GPU supports only '+maxTextures);}textureUnits+=1;return textureUnit;}//
  3362. function setTexture2D(texture,slot){var textureProperties=properties.get(texture);if(texture.isVideoTexture)updateVideoTexture(texture);if(texture.version>0&&textureProperties.__version!==texture.version){var image=texture.image;if(image===undefined){console.warn('THREE.WebGLRenderer: Texture marked for update but image is undefined');}else if(image.complete===false){console.warn('THREE.WebGLRenderer: Texture marked for update but image is incomplete');}else {uploadTexture(textureProperties,texture,slot);return;}}state.activeTexture(33984+slot);state.bindTexture(3553,textureProperties.__webglTexture);}function setTexture2DArray(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(35866,textureProperties.__webglTexture);}function setTexture3D(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(32879,textureProperties.__webglTexture);}function setTextureCube(texture,slot){var textureProperties=properties.get(texture);if(texture.version>0&&textureProperties.__version!==texture.version){uploadCubeTexture(textureProperties,texture,slot);return;}state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);}var wrappingToGL={[RepeatWrapping]:10497,[ClampToEdgeWrapping]:33071,[MirroredRepeatWrapping]:33648};var filterToGL={[NearestFilter]:9728,[NearestMipmapNearestFilter]:9984,[NearestMipmapLinearFilter]:9986,[LinearFilter]:9729,[LinearMipmapNearestFilter]:9985,[LinearMipmapLinearFilter]:9987};function setTextureParameters(textureType,texture,supportsMips){if(supportsMips){_gl.texParameteri(textureType,10242,wrappingToGL[texture.wrapS]);_gl.texParameteri(textureType,10243,wrappingToGL[texture.wrapT]);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,wrappingToGL[texture.wrapR]);}_gl.texParameteri(textureType,10240,filterToGL[texture.magFilter]);_gl.texParameteri(textureType,10241,filterToGL[texture.minFilter]);}else {_gl.texParameteri(textureType,10242,33071);_gl.texParameteri(textureType,10243,33071);if(textureType===32879||textureType===35866){_gl.texParameteri(textureType,32882,33071);}if(texture.wrapS!==ClampToEdgeWrapping||texture.wrapT!==ClampToEdgeWrapping){console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.');}_gl.texParameteri(textureType,10240,filterFallback(texture.magFilter));_gl.texParameteri(textureType,10241,filterFallback(texture.minFilter));if(texture.minFilter!==NearestFilter&&texture.minFilter!==LinearFilter){console.warn('THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.');}}var extension=extensions.get('EXT_texture_filter_anisotropic');if(extension){if(texture.type===FloatType&&extensions.get('OES_texture_float_linear')===null)return;if(texture.type===HalfFloatType&&(isWebGL2||extensions.get('OES_texture_half_float_linear'))===null)return;if(texture.anisotropy>1||properties.get(texture).__currentAnisotropy){_gl.texParameterf(textureType,extension.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(texture.anisotropy,capabilities.getMaxAnisotropy()));properties.get(texture).__currentAnisotropy=texture.anisotropy;}}}function initTexture(textureProperties,texture){if(textureProperties.__webglInit===undefined){textureProperties.__webglInit=true;texture.addEventListener('dispose',onTextureDispose);textureProperties.__webglTexture=_gl.createTexture();info.memory.textures++;}}function uploadTexture(textureProperties,texture,slot){var textureType=3553;if(texture.isDataTexture2DArray)textureType=35866;if(texture.isDataTexture3D)textureType=32879;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(textureType,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);_gl.pixelStorei(37441,texture.premultiplyAlpha);_gl.pixelStorei(3317,texture.unpackAlignment);var needsPowerOfTwo=textureNeedsPowerOfTwo(texture)&&isPowerOfTwo(texture.image)===false;var image=resizeImage(texture.image,needsPowerOfTwo,false,maxTextureSize);var supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format);var glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(textureType,texture,supportsMips);var mipmap;var mipmaps=texture.mipmaps;if(texture.isDepthTexture){// populate depth texture with dummy data
  3363. glInternalFormat=6402;if(isWebGL2){if(texture.type===FloatType){glInternalFormat=36012;}else if(texture.type===UnsignedIntType){glInternalFormat=33190;}else if(texture.type===UnsignedInt248Type$1){glInternalFormat=35056;}else {glInternalFormat=33189;// WebGL2 requires sized internalformat for glTexImage2D
  3364. }}else {if(texture.type===FloatType){console.error('WebGLRenderer: Floating point depth texture requires WebGL2.');}}// validation checks for WebGL 1
  3365. if(texture.format===DepthFormat&&glInternalFormat===6402){// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  3366. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  3367. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  3368. if(texture.type!==UnsignedShortType&&texture.type!==UnsignedIntType){console.warn('THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.');texture.type=UnsignedShortType;glType=utils.convert(texture.type);}}if(texture.format===DepthStencilFormat&&glInternalFormat===6402){// Depth stencil textures need the DEPTH_STENCIL internal format
  3369. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  3370. glInternalFormat=34041;// The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  3371. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  3372. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  3373. if(texture.type!==UnsignedInt248Type$1){console.warn('THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.');texture.type=UnsignedInt248Type$1;glType=utils.convert(texture.type);}}//
  3374. state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,null);}else if(texture.isDataTexture){// use manually created mipmaps if available
  3375. // if there are no manual mipmaps
  3376. // set 0 level mipmap and then use GL to generate other mipmap levels
  3377. if(mipmaps.length>0&&supportsMips){for(var _i106=0,il=mipmaps.length;_i106<il;_i106++){mipmap=mipmaps[_i106];state.texImage2D(3553,_i106,glInternalFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data);}texture.generateMipmaps=false;textureProperties.__maxMipLevel=mipmaps.length-1;}else {state.texImage2D(3553,0,glInternalFormat,image.width,image.height,0,glFormat,glType,image.data);textureProperties.__maxMipLevel=0;}}else if(texture.isCompressedTexture){for(var _i107=0,_il9=mipmaps.length;_i107<_il9;_i107++){mipmap=mipmaps[_i107];if(texture.format!==RGBAFormat&&texture.format!==RGBFormat){if(glFormat!==null){state.compressedTexImage2D(3553,_i107,glInternalFormat,mipmap.width,mipmap.height,0,mipmap.data);}else {console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()');}}else {state.texImage2D(3553,_i107,glInternalFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data);}}textureProperties.__maxMipLevel=mipmaps.length-1;}else if(texture.isDataTexture2DArray){state.texImage3D(35866,0,glInternalFormat,image.width,image.height,image.depth,0,glFormat,glType,image.data);textureProperties.__maxMipLevel=0;}else if(texture.isDataTexture3D){state.texImage3D(32879,0,glInternalFormat,image.width,image.height,image.depth,0,glFormat,glType,image.data);textureProperties.__maxMipLevel=0;}else {// regular Texture (image, video, canvas)
  3378. // use manually created mipmaps if available
  3379. // if there are no manual mipmaps
  3380. // set 0 level mipmap and then use GL to generate other mipmap levels
  3381. if(mipmaps.length>0&&supportsMips){for(var _i108=0,_il10=mipmaps.length;_i108<_il10;_i108++){mipmap=mipmaps[_i108];state.texImage2D(3553,_i108,glInternalFormat,glFormat,glType,mipmap);}texture.generateMipmaps=false;textureProperties.__maxMipLevel=mipmaps.length-1;}else {state.texImage2D(3553,0,glInternalFormat,glFormat,glType,image);textureProperties.__maxMipLevel=0;}}if(textureNeedsGenerateMipmaps(texture,supportsMips)){generateMipmap(textureType,texture,image.width,image.height);}textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture);}function uploadCubeTexture(textureProperties,texture,slot){if(texture.image.length!==6)return;initTexture(textureProperties,texture);state.activeTexture(33984+slot);state.bindTexture(34067,textureProperties.__webglTexture);_gl.pixelStorei(37440,texture.flipY);var isCompressed=texture&&(texture.isCompressedTexture||texture.image[0].isCompressedTexture);var isDataTexture=texture.image[0]&&texture.image[0].isDataTexture;var cubeImage=[];for(var _i109=0;_i109<6;_i109++){if(!isCompressed&&!isDataTexture){cubeImage[_i109]=resizeImage(texture.image[_i109],false,true,maxCubemapSize);}else {cubeImage[_i109]=isDataTexture?texture.image[_i109].image:texture.image[_i109];}}var image=cubeImage[0],supportsMips=isPowerOfTwo(image)||isWebGL2,glFormat=utils.convert(texture.format),glType=utils.convert(texture.type),glInternalFormat=getInternalFormat(texture.internalFormat,glFormat,glType);setTextureParameters(34067,texture,supportsMips);var mipmaps;if(isCompressed){for(var _i110=0;_i110<6;_i110++){mipmaps=cubeImage[_i110].mipmaps;for(var j=0;j<mipmaps.length;j++){var mipmap=mipmaps[j];if(texture.format!==RGBAFormat&&texture.format!==RGBFormat){if(glFormat!==null){state.compressedTexImage2D(34069+_i110,j,glInternalFormat,mipmap.width,mipmap.height,0,mipmap.data);}else {console.warn('THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()');}}else {state.texImage2D(34069+_i110,j,glInternalFormat,mipmap.width,mipmap.height,0,glFormat,glType,mipmap.data);}}}textureProperties.__maxMipLevel=mipmaps.length-1;}else {mipmaps=texture.mipmaps;for(var _i111=0;_i111<6;_i111++){if(isDataTexture){state.texImage2D(34069+_i111,0,glInternalFormat,cubeImage[_i111].width,cubeImage[_i111].height,0,glFormat,glType,cubeImage[_i111].data);for(var _j3=0;_j3<mipmaps.length;_j3++){var _mipmap=mipmaps[_j3];var mipmapImage=_mipmap.image[_i111].image;state.texImage2D(34069+_i111,_j3+1,glInternalFormat,mipmapImage.width,mipmapImage.height,0,glFormat,glType,mipmapImage.data);}}else {state.texImage2D(34069+_i111,0,glInternalFormat,glFormat,glType,cubeImage[_i111]);for(var _j4=0;_j4<mipmaps.length;_j4++){var _mipmap2=mipmaps[_j4];state.texImage2D(34069+_i111,_j4+1,glInternalFormat,glFormat,glType,_mipmap2.image[_i111]);}}}textureProperties.__maxMipLevel=mipmaps.length;}if(textureNeedsGenerateMipmaps(texture,supportsMips)){// We assume images for cube map have the same size.
  3382. generateMipmap(34067,texture,image.width,image.height);}textureProperties.__version=texture.version;if(texture.onUpdate)texture.onUpdate(texture);}// Render targets
  3383. // Setup storage for target texture and bind it to correct framebuffer
  3384. function setupFrameBufferTexture(framebuffer,renderTarget,attachment,textureTarget){var glFormat=utils.convert(renderTarget.texture.format);var glType=utils.convert(renderTarget.texture.type);var glInternalFormat=getInternalFormat(renderTarget.texture.internalFormat,glFormat,glType);state.texImage2D(textureTarget,0,glInternalFormat,renderTarget.width,renderTarget.height,0,glFormat,glType,null);_gl.bindFramebuffer(36160,framebuffer);_gl.framebufferTexture2D(36160,attachment,textureTarget,properties.get(renderTarget.texture).__webglTexture,0);_gl.bindFramebuffer(36160,null);}// Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  3385. function setupRenderBufferStorage(renderbuffer,renderTarget,isMultisample){_gl.bindRenderbuffer(36161,renderbuffer);if(renderTarget.depthBuffer&&!renderTarget.stencilBuffer){var glInternalFormat=33189;if(isMultisample){var depthTexture=renderTarget.depthTexture;if(depthTexture&&depthTexture.isDepthTexture){if(depthTexture.type===FloatType){glInternalFormat=36012;}else if(depthTexture.type===UnsignedIntType){glInternalFormat=33190;}}var samples=getRenderTargetSamples(renderTarget);_gl.renderbufferStorageMultisample(36161,samples,glInternalFormat,renderTarget.width,renderTarget.height);}else {_gl.renderbufferStorage(36161,glInternalFormat,renderTarget.width,renderTarget.height);}_gl.framebufferRenderbuffer(36160,36096,36161,renderbuffer);}else if(renderTarget.depthBuffer&&renderTarget.stencilBuffer){if(isMultisample){var _samples=getRenderTargetSamples(renderTarget);_gl.renderbufferStorageMultisample(36161,_samples,35056,renderTarget.width,renderTarget.height);}else {_gl.renderbufferStorage(36161,34041,renderTarget.width,renderTarget.height);}_gl.framebufferRenderbuffer(36160,33306,36161,renderbuffer);}else {var glFormat=utils.convert(renderTarget.texture.format);var glType=utils.convert(renderTarget.texture.type);var _glInternalFormat=getInternalFormat(renderTarget.texture.internalFormat,glFormat,glType);if(isMultisample){var _samples2=getRenderTargetSamples(renderTarget);_gl.renderbufferStorageMultisample(36161,_samples2,_glInternalFormat,renderTarget.width,renderTarget.height);}else {_gl.renderbufferStorage(36161,_glInternalFormat,renderTarget.width,renderTarget.height);}}_gl.bindRenderbuffer(36161,null);}// Setup resources for a Depth Texture for a FBO (needs an extension)
  3386. function setupDepthTexture(framebuffer,renderTarget){var isCube=renderTarget&&renderTarget.isWebGLCubeRenderTarget;if(isCube)throw new Error('Depth Texture with cube render targets is not supported');_gl.bindFramebuffer(36160,framebuffer);if(!(renderTarget.depthTexture&&renderTarget.depthTexture.isDepthTexture)){throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');}// upload an empty depth texture with framebuffer size
  3387. if(!properties.get(renderTarget.depthTexture).__webglTexture||renderTarget.depthTexture.image.width!==renderTarget.width||renderTarget.depthTexture.image.height!==renderTarget.height){renderTarget.depthTexture.image.width=renderTarget.width;renderTarget.depthTexture.image.height=renderTarget.height;renderTarget.depthTexture.needsUpdate=true;}setTexture2D(renderTarget.depthTexture,0);var webglDepthTexture=properties.get(renderTarget.depthTexture).__webglTexture;if(renderTarget.depthTexture.format===DepthFormat){_gl.framebufferTexture2D(36160,36096,3553,webglDepthTexture,0);}else if(renderTarget.depthTexture.format===DepthStencilFormat){_gl.framebufferTexture2D(36160,33306,3553,webglDepthTexture,0);}else {throw new Error('Unknown depthTexture format');}}// Setup GL resources for a non-texture depth buffer
  3388. function setupDepthRenderbuffer(renderTarget){var renderTargetProperties=properties.get(renderTarget);var isCube=renderTarget.isWebGLCubeRenderTarget===true;if(renderTarget.depthTexture){if(isCube)throw new Error('target.depthTexture not supported in Cube render targets');setupDepthTexture(renderTargetProperties.__webglFramebuffer,renderTarget);}else {if(isCube){renderTargetProperties.__webglDepthbuffer=[];for(var _i112=0;_i112<6;_i112++){_gl.bindFramebuffer(36160,renderTargetProperties.__webglFramebuffer[_i112]);renderTargetProperties.__webglDepthbuffer[_i112]=_gl.createRenderbuffer();setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer[_i112],renderTarget,false);}}else {_gl.bindFramebuffer(36160,renderTargetProperties.__webglFramebuffer);renderTargetProperties.__webglDepthbuffer=_gl.createRenderbuffer();setupRenderBufferStorage(renderTargetProperties.__webglDepthbuffer,renderTarget,false);}}_gl.bindFramebuffer(36160,null);}// Set up GL resources for the render target
  3389. function setupRenderTarget(renderTarget){var renderTargetProperties=properties.get(renderTarget);var textureProperties=properties.get(renderTarget.texture);renderTarget.addEventListener('dispose',onRenderTargetDispose);textureProperties.__webglTexture=_gl.createTexture();info.memory.textures++;var isCube=renderTarget.isWebGLCubeRenderTarget===true;var isMultisample=renderTarget.isWebGLMultisampleRenderTarget===true;var supportsMips=isPowerOfTwo(renderTarget)||isWebGL2;// Handles WebGL2 RGBFormat fallback - #18858
  3390. if(isWebGL2&&renderTarget.texture.format===RGBFormat&&(renderTarget.texture.type===FloatType||renderTarget.texture.type===HalfFloatType)){renderTarget.texture.format=RGBAFormat;console.warn('THREE.WebGLRenderer: Rendering to textures with RGB format is not supported. Using RGBA format instead.');}// Setup framebuffer
  3391. if(isCube){renderTargetProperties.__webglFramebuffer=[];for(var _i113=0;_i113<6;_i113++){renderTargetProperties.__webglFramebuffer[_i113]=_gl.createFramebuffer();}}else {renderTargetProperties.__webglFramebuffer=_gl.createFramebuffer();if(isMultisample){if(isWebGL2){renderTargetProperties.__webglMultisampledFramebuffer=_gl.createFramebuffer();renderTargetProperties.__webglColorRenderbuffer=_gl.createRenderbuffer();_gl.bindRenderbuffer(36161,renderTargetProperties.__webglColorRenderbuffer);var glFormat=utils.convert(renderTarget.texture.format);var glType=utils.convert(renderTarget.texture.type);var glInternalFormat=getInternalFormat(renderTarget.texture.internalFormat,glFormat,glType);var samples=getRenderTargetSamples(renderTarget);_gl.renderbufferStorageMultisample(36161,samples,glInternalFormat,renderTarget.width,renderTarget.height);_gl.bindFramebuffer(36160,renderTargetProperties.__webglMultisampledFramebuffer);_gl.framebufferRenderbuffer(36160,36064,36161,renderTargetProperties.__webglColorRenderbuffer);_gl.bindRenderbuffer(36161,null);if(renderTarget.depthBuffer){renderTargetProperties.__webglDepthRenderbuffer=_gl.createRenderbuffer();setupRenderBufferStorage(renderTargetProperties.__webglDepthRenderbuffer,renderTarget,true);}_gl.bindFramebuffer(36160,null);}else {console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');}}}// Setup color buffer
  3392. if(isCube){state.bindTexture(34067,textureProperties.__webglTexture);setTextureParameters(34067,renderTarget.texture,supportsMips);for(var _i114=0;_i114<6;_i114++){setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer[_i114],renderTarget,36064,34069+_i114);}if(textureNeedsGenerateMipmaps(renderTarget.texture,supportsMips)){generateMipmap(34067,renderTarget.texture,renderTarget.width,renderTarget.height);}state.bindTexture(34067,null);}else {state.bindTexture(3553,textureProperties.__webglTexture);setTextureParameters(3553,renderTarget.texture,supportsMips);setupFrameBufferTexture(renderTargetProperties.__webglFramebuffer,renderTarget,36064,3553);if(textureNeedsGenerateMipmaps(renderTarget.texture,supportsMips)){generateMipmap(3553,renderTarget.texture,renderTarget.width,renderTarget.height);}state.bindTexture(3553,null);}// Setup depth and stencil buffers
  3393. if(renderTarget.depthBuffer){setupDepthRenderbuffer(renderTarget);}}function updateRenderTargetMipmap(renderTarget){var texture=renderTarget.texture;var supportsMips=isPowerOfTwo(renderTarget)||isWebGL2;if(textureNeedsGenerateMipmaps(texture,supportsMips)){var target=renderTarget.isWebGLCubeRenderTarget?34067:3553;var webglTexture=properties.get(texture).__webglTexture;state.bindTexture(target,webglTexture);generateMipmap(target,texture,renderTarget.width,renderTarget.height);state.bindTexture(target,null);}}function updateMultisampleRenderTarget(renderTarget){if(renderTarget.isWebGLMultisampleRenderTarget){if(isWebGL2){var renderTargetProperties=properties.get(renderTarget);_gl.bindFramebuffer(36008,renderTargetProperties.__webglMultisampledFramebuffer);_gl.bindFramebuffer(36009,renderTargetProperties.__webglFramebuffer);var width=renderTarget.width;var height=renderTarget.height;var mask=16384;if(renderTarget.depthBuffer)mask|=256;if(renderTarget.stencilBuffer)mask|=1024;_gl.blitFramebuffer(0,0,width,height,0,0,width,height,mask,9728);_gl.bindFramebuffer(36160,renderTargetProperties.__webglMultisampledFramebuffer);// see #18905
  3394. }else {console.warn('THREE.WebGLRenderer: WebGLMultisampleRenderTarget can only be used with WebGL2.');}}}function getRenderTargetSamples(renderTarget){return isWebGL2&&renderTarget.isWebGLMultisampleRenderTarget?Math.min(maxSamples,renderTarget.samples):0;}function updateVideoTexture(texture){var frame=info.render.frame;// Check the last frame we updated the VideoTexture
  3395. if(_videoTextures.get(texture)!==frame){_videoTextures.set(texture,frame);texture.update();}}// backwards compatibility
  3396. var warnedTexture2D=false;var warnedTextureCube=false;function safeSetTexture2D(texture,slot){if(texture&&texture.isWebGLRenderTarget){if(warnedTexture2D===false){console.warn('THREE.WebGLTextures.safeSetTexture2D: don\'t use render targets as textures. Use their .texture property instead.');warnedTexture2D=true;}texture=texture.texture;}setTexture2D(texture,slot);}function safeSetTextureCube(texture,slot){if(texture&&texture.isWebGLCubeRenderTarget){if(warnedTextureCube===false){console.warn('THREE.WebGLTextures.safeSetTextureCube: don\'t use cube render targets as textures. Use their .texture property instead.');warnedTextureCube=true;}texture=texture.texture;}setTextureCube(texture,slot);}//
  3397. this.allocateTextureUnit=allocateTextureUnit;this.resetTextureUnits=resetTextureUnits;this.setTexture2D=setTexture2D;this.setTexture2DArray=setTexture2DArray;this.setTexture3D=setTexture3D;this.setTextureCube=setTextureCube;this.setupRenderTarget=setupRenderTarget;this.updateRenderTargetMipmap=updateRenderTargetMipmap;this.updateMultisampleRenderTarget=updateMultisampleRenderTarget;this.safeSetTexture2D=safeSetTexture2D;this.safeSetTextureCube=safeSetTextureCube;}function WebGLUtils(gl,extensions,capabilities){var isWebGL2=capabilities.isWebGL2;function convert(p){var extension;if(p===UnsignedByteType)return 5121;if(p===UnsignedShort4444Type)return 32819;if(p===UnsignedShort5551Type)return 32820;if(p===UnsignedShort565Type)return 33635;if(p===ByteType)return 5120;if(p===ShortType)return 5122;if(p===UnsignedShortType)return 5123;if(p===IntType)return 5124;if(p===UnsignedIntType)return 5125;if(p===FloatType)return 5126;if(p===HalfFloatType){if(isWebGL2)return 5131;extension=extensions.get('OES_texture_half_float');if(extension!==null){return extension.HALF_FLOAT_OES;}else {return null;}}if(p===AlphaFormat)return 6406;if(p===RGBFormat)return 6407;if(p===RGBAFormat)return 6408;if(p===LuminanceFormat)return 6409;if(p===LuminanceAlphaFormat)return 6410;if(p===DepthFormat)return 6402;if(p===DepthStencilFormat)return 34041;if(p===RedFormat)return 6403;// WebGL2 formats.
  3398. if(p===RedIntegerFormat)return 36244;if(p===RGFormat)return 33319;if(p===RGIntegerFormat)return 33320;if(p===RGBIntegerFormat)return 36248;if(p===RGBAIntegerFormat)return 36249;if(p===RGB_S3TC_DXT1_Format||p===RGBA_S3TC_DXT1_Format$1||p===RGBA_S3TC_DXT3_Format||p===RGBA_S3TC_DXT5_Format$1){extension=extensions.get('WEBGL_compressed_texture_s3tc');if(extension!==null){if(p===RGB_S3TC_DXT1_Format)return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT1_Format$1)return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(p===RGBA_S3TC_DXT3_Format)return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(p===RGBA_S3TC_DXT5_Format$1)return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;}else {return null;}}if(p===RGB_PVRTC_4BPPV1_Format||p===RGB_PVRTC_2BPPV1_Format||p===RGBA_PVRTC_4BPPV1_Format||p===RGBA_PVRTC_2BPPV1_Format){extension=extensions.get('WEBGL_compressed_texture_pvrtc');if(extension!==null){if(p===RGB_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(p===RGB_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(p===RGBA_PVRTC_4BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(p===RGBA_PVRTC_2BPPV1_Format)return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;}else {return null;}}if(p===RGB_ETC1_Format){extension=extensions.get('WEBGL_compressed_texture_etc1');if(extension!==null){return extension.COMPRESSED_RGB_ETC1_WEBGL;}else {return null;}}if(p===RGB_ETC2_Format||p===RGBA_ETC2_EAC_Format){extension=extensions.get('WEBGL_compressed_texture_etc');if(extension!==null){if(p===RGB_ETC2_Format)return extension.COMPRESSED_RGB8_ETC2;if(p===RGBA_ETC2_EAC_Format)return extension.COMPRESSED_RGBA8_ETC2_EAC;}}if(p===RGBA_ASTC_4x4_Format||p===RGBA_ASTC_5x4_Format||p===RGBA_ASTC_5x5_Format||p===RGBA_ASTC_6x5_Format||p===RGBA_ASTC_6x6_Format||p===RGBA_ASTC_8x5_Format||p===RGBA_ASTC_8x6_Format||p===RGBA_ASTC_8x8_Format||p===RGBA_ASTC_10x5_Format||p===RGBA_ASTC_10x6_Format||p===RGBA_ASTC_10x8_Format||p===RGBA_ASTC_10x10_Format||p===RGBA_ASTC_12x10_Format||p===RGBA_ASTC_12x12_Format||p===SRGB8_ALPHA8_ASTC_4x4_Format||p===SRGB8_ALPHA8_ASTC_5x4_Format||p===SRGB8_ALPHA8_ASTC_5x5_Format||p===SRGB8_ALPHA8_ASTC_6x5_Format||p===SRGB8_ALPHA8_ASTC_6x6_Format||p===SRGB8_ALPHA8_ASTC_8x5_Format||p===SRGB8_ALPHA8_ASTC_8x6_Format||p===SRGB8_ALPHA8_ASTC_8x8_Format||p===SRGB8_ALPHA8_ASTC_10x5_Format||p===SRGB8_ALPHA8_ASTC_10x6_Format||p===SRGB8_ALPHA8_ASTC_10x8_Format||p===SRGB8_ALPHA8_ASTC_10x10_Format||p===SRGB8_ALPHA8_ASTC_12x10_Format||p===SRGB8_ALPHA8_ASTC_12x12_Format){extension=extensions.get('WEBGL_compressed_texture_astc');if(extension!==null){// TODO Complete?
  3399. return p;}else {return null;}}if(p===RGBA_BPTC_Format){extension=extensions.get('EXT_texture_compression_bptc');if(extension!==null){// TODO Complete?
  3400. return p;}else {return null;}}if(p===UnsignedInt248Type$1){if(isWebGL2)return 34042;extension=extensions.get('WEBGL_depth_texture');if(extension!==null){return extension.UNSIGNED_INT_24_8_WEBGL;}else {return null;}}}return {convert:convert};}function ArrayCamera(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];PerspectiveCamera.call(this);this.cameras=array;}ArrayCamera.prototype=Object.assign(Object.create(PerspectiveCamera.prototype),{constructor:ArrayCamera,isArrayCamera:true});function Group(){Object3D.call(this);this.type='Group';}Group.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Group,isGroup:true});function WebXRController(){this._targetRay=null;this._grip=null;this._hand=null;}Object.assign(WebXRController.prototype,{constructor:WebXRController,getHandSpace:function getHandSpace(){if(this._hand===null){this._hand=new Group();this._hand.matrixAutoUpdate=false;this._hand.visible=false;this._hand.joints=[];this._hand.inputState={pinching:false};if(window.XRHand){for(var _i115=0;_i115<=window.XRHand.LITTLE_PHALANX_TIP;_i115++){// The transform of this joint will be updated with the joint pose on each frame
  3401. var joint=new Group();joint.matrixAutoUpdate=false;joint.visible=false;this._hand.joints.push(joint);// ??
  3402. this._hand.add(joint);}}}return this._hand;},getTargetRaySpace:function getTargetRaySpace(){if(this._targetRay===null){this._targetRay=new Group();this._targetRay.matrixAutoUpdate=false;this._targetRay.visible=false;}return this._targetRay;},getGripSpace:function getGripSpace(){if(this._grip===null){this._grip=new Group();this._grip.matrixAutoUpdate=false;this._grip.visible=false;}return this._grip;},dispatchEvent:function dispatchEvent(event){if(this._targetRay!==null){this._targetRay.dispatchEvent(event);}if(this._grip!==null){this._grip.dispatchEvent(event);}if(this._hand!==null){this._hand.dispatchEvent(event);}return this;},disconnect:function disconnect(inputSource){this.dispatchEvent({type:'disconnected',data:inputSource});if(this._targetRay!==null){this._targetRay.visible=false;}if(this._grip!==null){this._grip.visible=false;}if(this._hand!==null){this._hand.visible=false;}return this;},update:function update(inputSource,frame,referenceSpace){var inputPose=null;var gripPose=null;var handPose=null;var targetRay=this._targetRay;var grip=this._grip;var hand=this._hand;if(inputSource&&frame.session.visibilityState!=='visible-blurred'){if(hand&&inputSource.hand){handPose=true;for(var _i116=0;_i116<=window.XRHand.LITTLE_PHALANX_TIP;_i116++){if(inputSource.hand[_i116]){// Update the joints groups with the XRJoint poses
  3403. var jointPose=frame.getJointPose(inputSource.hand[_i116],referenceSpace);var joint=hand.joints[_i116];if(jointPose!==null){joint.matrix.fromArray(jointPose.transform.matrix);joint.matrix.decompose(joint.position,joint.rotation,joint.scale);joint.jointRadius=jointPose.radius;}joint.visible=jointPose!==null;// Custom events
  3404. // Check pinch
  3405. var indexTip=hand.joints[window.XRHand.INDEX_PHALANX_TIP];var thumbTip=hand.joints[window.XRHand.THUMB_PHALANX_TIP];var distance=indexTip.position.distanceTo(thumbTip.position);var distanceToPinch=0.02;var threshold=0.005;if(hand.inputState.pinching&&distance>distanceToPinch+threshold){hand.inputState.pinching=false;this.dispatchEvent({type:'pinchend',handedness:inputSource.handedness,target:this});}else if(!hand.inputState.pinching&&distance<=distanceToPinch-threshold){hand.inputState.pinching=true;this.dispatchEvent({type:'pinchstart',handedness:inputSource.handedness,target:this});}}}}else {if(targetRay!==null){inputPose=frame.getPose(inputSource.targetRaySpace,referenceSpace);if(inputPose!==null){targetRay.matrix.fromArray(inputPose.transform.matrix);targetRay.matrix.decompose(targetRay.position,targetRay.rotation,targetRay.scale);}}if(grip!==null&&inputSource.gripSpace){gripPose=frame.getPose(inputSource.gripSpace,referenceSpace);if(gripPose!==null){grip.matrix.fromArray(gripPose.transform.matrix);grip.matrix.decompose(grip.position,grip.rotation,grip.scale);}}}}if(targetRay!==null){targetRay.visible=inputPose!==null;}if(grip!==null){grip.visible=gripPose!==null;}if(hand!==null){hand.visible=handPose!==null;}return this;}});function WebXRManager(renderer,gl){var scope=this;var session=null;var framebufferScaleFactor=1.0;var referenceSpace=null;var referenceSpaceType='local-floor';var pose=null;var controllers=[];var inputSourcesMap=new Map();//
  3406. var cameraL=new PerspectiveCamera();cameraL.layers.enable(1);cameraL.viewport=new Vector4();var cameraR=new PerspectiveCamera();cameraR.layers.enable(2);cameraR.viewport=new Vector4();var cameras=[cameraL,cameraR];var cameraVR=new ArrayCamera();cameraVR.layers.enable(1);cameraVR.layers.enable(2);var _currentDepthNear=null;var _currentDepthFar=null;//
  3407. this.enabled=false;this.isPresenting=false;this.getController=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getTargetRaySpace();};this.getControllerGrip=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getGripSpace();};this.getHand=function(index){var controller=controllers[index];if(controller===undefined){controller=new WebXRController();controllers[index]=controller;}return controller.getHandSpace();};//
  3408. function onSessionEvent(event){var controller=inputSourcesMap.get(event.inputSource);if(controller){controller.dispatchEvent({type:event.type,data:event.inputSource});}}function onSessionEnd(){inputSourcesMap.forEach(function(controller,inputSource){controller.disconnect(inputSource);});inputSourcesMap.clear();//
  3409. renderer.setFramebuffer(null);renderer.setRenderTarget(renderer.getRenderTarget());// Hack #15830
  3410. animation.stop();scope.isPresenting=false;scope.dispatchEvent({type:'sessionend'});}function onRequestReferenceSpace(value){referenceSpace=value;animation.setContext(session);animation.start();scope.isPresenting=true;scope.dispatchEvent({type:'sessionstart'});}this.setFramebufferScaleFactor=function(value){framebufferScaleFactor=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change framebuffer scale while presenting.');}};this.setReferenceSpaceType=function(value){referenceSpaceType=value;if(scope.isPresenting===true){console.warn('THREE.WebXRManager: Cannot change reference space type while presenting.');}};this.getReferenceSpace=function(){return referenceSpace;};this.getSession=function(){return session;};this.setSession=function(value){session=value;if(session!==null){session.addEventListener('select',onSessionEvent);session.addEventListener('selectstart',onSessionEvent);session.addEventListener('selectend',onSessionEvent);session.addEventListener('squeeze',onSessionEvent);session.addEventListener('squeezestart',onSessionEvent);session.addEventListener('squeezeend',onSessionEvent);session.addEventListener('end',onSessionEnd);var attributes=gl.getContextAttributes();if(attributes.xrCompatible!==true){gl.makeXRCompatible();}var layerInit={antialias:attributes.antialias,alpha:attributes.alpha,depth:attributes.depth,stencil:attributes.stencil,framebufferScaleFactor:framebufferScaleFactor};// eslint-disable-next-line no-undef
  3411. var baseLayer=new XRWebGLLayer(session,gl,layerInit);session.updateRenderState({baseLayer:baseLayer});session.requestReferenceSpace(referenceSpaceType).then(onRequestReferenceSpace);//
  3412. session.addEventListener('inputsourceschange',updateInputSources);}};function updateInputSources(event){var inputSources=session.inputSources;// Assign inputSources to available controllers
  3413. for(var _i117=0;_i117<controllers.length;_i117++){inputSourcesMap.set(inputSources[_i117],controllers[_i117]);}// Notify disconnected
  3414. for(var _i118=0;_i118<event.removed.length;_i118++){var inputSource=event.removed[_i118];var controller=inputSourcesMap.get(inputSource);if(controller){controller.dispatchEvent({type:'disconnected',data:inputSource});inputSourcesMap.delete(inputSource);}}// Notify connected
  3415. for(var _i119=0;_i119<event.added.length;_i119++){var _inputSource=event.added[_i119];var _controller=inputSourcesMap.get(_inputSource);if(_controller){_controller.dispatchEvent({type:'connected',data:_inputSource});}}}//
  3416. var cameraLPos=new Vector3();var cameraRPos=new Vector3();/**
  3417. * Assumes 2 cameras that are parallel and share an X-axis, and that
  3418. * the cameras' projection and world matrices have already been set.
  3419. * And that near and far planes are identical for both cameras.
  3420. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  3421. */function setProjectionFromUnion(camera,cameraL,cameraR){cameraLPos.setFromMatrixPosition(cameraL.matrixWorld);cameraRPos.setFromMatrixPosition(cameraR.matrixWorld);var ipd=cameraLPos.distanceTo(cameraRPos);var projL=cameraL.projectionMatrix.elements;var projR=cameraR.projectionMatrix.elements;// VR systems will have identical far and near planes, and
  3422. // most likely identical top and bottom frustum extents.
  3423. // Use the left camera for these values.
  3424. var near=projL[14]/(projL[10]-1);var far=projL[14]/(projL[10]+1);var topFov=(projL[9]+1)/projL[5];var bottomFov=(projL[9]-1)/projL[5];var leftFov=(projL[8]-1)/projL[0];var rightFov=(projR[8]+1)/projR[0];var left=near*leftFov;var right=near*rightFov;// Calculate the new camera's position offset from the
  3425. // left camera. xOffset should be roughly half `ipd`.
  3426. var zOffset=ipd/(-leftFov+rightFov);var xOffset=zOffset*-leftFov;// TODO: Better way to apply this offset?
  3427. cameraL.matrixWorld.decompose(camera.position,camera.quaternion,camera.scale);camera.translateX(xOffset);camera.translateZ(zOffset);camera.matrixWorld.compose(camera.position,camera.quaternion,camera.scale);camera.matrixWorldInverse.copy(camera.matrixWorld).invert();// Find the union of the frustum values of the cameras and scale
  3428. // the values so that the near plane's position does not change in world space,
  3429. // although must now be relative to the new union camera.
  3430. var near2=near+zOffset;var far2=far+zOffset;var left2=left-xOffset;var right2=right+(ipd-xOffset);var top2=topFov*far/far2*near2;var bottom2=bottomFov*far/far2*near2;camera.projectionMatrix.makePerspective(left2,right2,top2,bottom2,near2,far2);}function updateCamera(camera,parent){if(parent===null){camera.matrixWorld.copy(camera.matrix);}else {camera.matrixWorld.multiplyMatrices(parent.matrixWorld,camera.matrix);}camera.matrixWorldInverse.copy(camera.matrixWorld).invert();}this.getCamera=function(camera){cameraVR.near=cameraR.near=cameraL.near=camera.near;cameraVR.far=cameraR.far=cameraL.far=camera.far;if(_currentDepthNear!==cameraVR.near||_currentDepthFar!==cameraVR.far){// Note that the new renderState won't apply until the next frame. See #18320
  3431. session.updateRenderState({depthNear:cameraVR.near,depthFar:cameraVR.far});_currentDepthNear=cameraVR.near;_currentDepthFar=cameraVR.far;}var parent=camera.parent;var cameras=cameraVR.cameras;updateCamera(cameraVR,parent);for(var _i120=0;_i120<cameras.length;_i120++){updateCamera(cameras[_i120],parent);}// update camera and its children
  3432. camera.matrixWorld.copy(cameraVR.matrixWorld);var children=camera.children;for(var _i121=0,l=children.length;_i121<l;_i121++){children[_i121].updateMatrixWorld(true);}// update projection matrix for proper view frustum culling
  3433. if(cameras.length===2){setProjectionFromUnion(cameraVR,cameraL,cameraR);}else {// assume single camera setup (AR)
  3434. cameraVR.projectionMatrix.copy(cameraL.projectionMatrix);}return cameraVR;};// Animation Loop
  3435. var onAnimationFrameCallback=null;function onAnimationFrame(time,frame){pose=frame.getViewerPose(referenceSpace);if(pose!==null){var views=pose.views;var baseLayer=session.renderState.baseLayer;renderer.setFramebuffer(baseLayer.framebuffer);var cameraVRNeedsUpdate=false;// check if it's necessary to rebuild cameraVR's camera list
  3436. if(views.length!==cameraVR.cameras.length){cameraVR.cameras.length=0;cameraVRNeedsUpdate=true;}for(var _i122=0;_i122<views.length;_i122++){var view=views[_i122];var viewport=baseLayer.getViewport(view);var camera=cameras[_i122];camera.matrix.fromArray(view.transform.matrix);camera.projectionMatrix.fromArray(view.projectionMatrix);camera.viewport.set(viewport.x,viewport.y,viewport.width,viewport.height);if(_i122===0){cameraVR.matrix.copy(camera.matrix);}if(cameraVRNeedsUpdate===true){cameraVR.cameras.push(camera);}}}//
  3437. var inputSources=session.inputSources;for(var _i123=0;_i123<controllers.length;_i123++){var controller=controllers[_i123];var inputSource=inputSources[_i123];controller.update(inputSource,frame,referenceSpace);}if(onAnimationFrameCallback)onAnimationFrameCallback(time,frame);}var animation=new WebGLAnimation();animation.setAnimationLoop(onAnimationFrame);this.setAnimationLoop=function(callback){onAnimationFrameCallback=callback;};this.dispose=function(){};}Object.assign(WebXRManager.prototype,EventDispatcher.prototype);function WebGLMaterials(properties){function refreshFogUniforms(uniforms,fog){uniforms.fogColor.value.copy(fog.color);if(fog.isFog){uniforms.fogNear.value=fog.near;uniforms.fogFar.value=fog.far;}else if(fog.isFogExp2){uniforms.fogDensity.value=fog.density;}}function refreshMaterialUniforms(uniforms,material,pixelRatio,height){if(material.isMeshBasicMaterial){refreshUniformsCommon(uniforms,material);}else if(material.isMeshLambertMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsLambert(uniforms,material);}else if(material.isMeshToonMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsToon(uniforms,material);}else if(material.isMeshPhongMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsPhong(uniforms,material);}else if(material.isMeshStandardMaterial){refreshUniformsCommon(uniforms,material);if(material.isMeshPhysicalMaterial){refreshUniformsPhysical(uniforms,material);}else {refreshUniformsStandard(uniforms,material);}}else if(material.isMeshMatcapMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsMatcap(uniforms,material);}else if(material.isMeshDepthMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsDepth(uniforms,material);}else if(material.isMeshDistanceMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsDistance(uniforms,material);}else if(material.isMeshNormalMaterial){refreshUniformsCommon(uniforms,material);refreshUniformsNormal(uniforms,material);}else if(material.isLineBasicMaterial){refreshUniformsLine(uniforms,material);if(material.isLineDashedMaterial){refreshUniformsDash(uniforms,material);}}else if(material.isPointsMaterial){refreshUniformsPoints(uniforms,material,pixelRatio,height);}else if(material.isSpriteMaterial){refreshUniformsSprites(uniforms,material);}else if(material.isShadowMaterial){uniforms.color.value.copy(material.color);uniforms.opacity.value=material.opacity;}else if(material.isShaderMaterial){material.uniformsNeedUpdate=false;// #15581
  3438. }}function refreshUniformsCommon(uniforms,material){uniforms.opacity.value=material.opacity;if(material.color){uniforms.diffuse.value.copy(material.color);}if(material.emissive){uniforms.emissive.value.copy(material.emissive).multiplyScalar(material.emissiveIntensity);}if(material.map){uniforms.map.value=material.map;}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap;}if(material.specularMap){uniforms.specularMap.value=material.specularMap;}var envMap=properties.get(material).envMap;if(envMap){uniforms.envMap.value=envMap;uniforms.flipEnvMap.value=envMap.isCubeTexture&&envMap._needsFlipEnvMap?-1:1;uniforms.reflectivity.value=material.reflectivity;uniforms.refractionRatio.value=material.refractionRatio;var maxMipLevel=properties.get(envMap).__maxMipLevel;if(maxMipLevel!==undefined){uniforms.maxMipLevel.value=maxMipLevel;}}if(material.lightMap){uniforms.lightMap.value=material.lightMap;uniforms.lightMapIntensity.value=material.lightMapIntensity;}if(material.aoMap){uniforms.aoMap.value=material.aoMap;uniforms.aoMapIntensity.value=material.aoMapIntensity;}// uv repeat and offset setting priorities
  3439. // 1. color map
  3440. // 2. specular map
  3441. // 3. displacementMap map
  3442. // 4. normal map
  3443. // 5. bump map
  3444. // 6. roughnessMap map
  3445. // 7. metalnessMap map
  3446. // 8. alphaMap map
  3447. // 9. emissiveMap map
  3448. // 10. clearcoat map
  3449. // 11. clearcoat normal map
  3450. // 12. clearcoat roughnessMap map
  3451. var uvScaleMap;if(material.map){uvScaleMap=material.map;}else if(material.specularMap){uvScaleMap=material.specularMap;}else if(material.displacementMap){uvScaleMap=material.displacementMap;}else if(material.normalMap){uvScaleMap=material.normalMap;}else if(material.bumpMap){uvScaleMap=material.bumpMap;}else if(material.roughnessMap){uvScaleMap=material.roughnessMap;}else if(material.metalnessMap){uvScaleMap=material.metalnessMap;}else if(material.alphaMap){uvScaleMap=material.alphaMap;}else if(material.emissiveMap){uvScaleMap=material.emissiveMap;}else if(material.clearcoatMap){uvScaleMap=material.clearcoatMap;}else if(material.clearcoatNormalMap){uvScaleMap=material.clearcoatNormalMap;}else if(material.clearcoatRoughnessMap){uvScaleMap=material.clearcoatRoughnessMap;}if(uvScaleMap!==undefined){// backwards compatibility
  3452. if(uvScaleMap.isWebGLRenderTarget){uvScaleMap=uvScaleMap.texture;}if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix();}uniforms.uvTransform.value.copy(uvScaleMap.matrix);}// uv repeat and offset setting priorities for uv2
  3453. // 1. ao map
  3454. // 2. light map
  3455. var uv2ScaleMap;if(material.aoMap){uv2ScaleMap=material.aoMap;}else if(material.lightMap){uv2ScaleMap=material.lightMap;}if(uv2ScaleMap!==undefined){// backwards compatibility
  3456. if(uv2ScaleMap.isWebGLRenderTarget){uv2ScaleMap=uv2ScaleMap.texture;}if(uv2ScaleMap.matrixAutoUpdate===true){uv2ScaleMap.updateMatrix();}uniforms.uv2Transform.value.copy(uv2ScaleMap.matrix);}}function refreshUniformsLine(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;}function refreshUniformsDash(uniforms,material){uniforms.dashSize.value=material.dashSize;uniforms.totalSize.value=material.dashSize+material.gapSize;uniforms.scale.value=material.scale;}function refreshUniformsPoints(uniforms,material,pixelRatio,height){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.size.value=material.size*pixelRatio;uniforms.scale.value=height*0.5;if(material.map){uniforms.map.value=material.map;}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap;}// uv repeat and offset setting priorities
  3457. // 1. color map
  3458. // 2. alpha map
  3459. var uvScaleMap;if(material.map){uvScaleMap=material.map;}else if(material.alphaMap){uvScaleMap=material.alphaMap;}if(uvScaleMap!==undefined){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix();}uniforms.uvTransform.value.copy(uvScaleMap.matrix);}}function refreshUniformsSprites(uniforms,material){uniforms.diffuse.value.copy(material.color);uniforms.opacity.value=material.opacity;uniforms.rotation.value=material.rotation;if(material.map){uniforms.map.value=material.map;}if(material.alphaMap){uniforms.alphaMap.value=material.alphaMap;}// uv repeat and offset setting priorities
  3460. // 1. color map
  3461. // 2. alpha map
  3462. var uvScaleMap;if(material.map){uvScaleMap=material.map;}else if(material.alphaMap){uvScaleMap=material.alphaMap;}if(uvScaleMap!==undefined){if(uvScaleMap.matrixAutoUpdate===true){uvScaleMap.updateMatrix();}uniforms.uvTransform.value.copy(uvScaleMap.matrix);}}function refreshUniformsLambert(uniforms,material){if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap;}}function refreshUniformsPhong(uniforms,material){uniforms.specular.value.copy(material.specular);uniforms.shininess.value=Math.max(material.shininess,1e-4);// to prevent pow( 0.0, 0.0 )
  3463. if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap;}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale;if(material.side===BackSide)uniforms.bumpScale.value*=-1;}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale);if(material.side===BackSide)uniforms.normalScale.value.negate();}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}}function refreshUniformsToon(uniforms,material){if(material.gradientMap){uniforms.gradientMap.value=material.gradientMap;}if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap;}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale;if(material.side===BackSide)uniforms.bumpScale.value*=-1;}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale);if(material.side===BackSide)uniforms.normalScale.value.negate();}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}}function refreshUniformsStandard(uniforms,material){uniforms.roughness.value=material.roughness;uniforms.metalness.value=material.metalness;if(material.roughnessMap){uniforms.roughnessMap.value=material.roughnessMap;}if(material.metalnessMap){uniforms.metalnessMap.value=material.metalnessMap;}if(material.emissiveMap){uniforms.emissiveMap.value=material.emissiveMap;}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale;if(material.side===BackSide)uniforms.bumpScale.value*=-1;}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale);if(material.side===BackSide)uniforms.normalScale.value.negate();}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}var envMap=properties.get(material).envMap;if(envMap){//uniforms.envMap.value = material.envMap; // part of uniforms common
  3464. uniforms.envMapIntensity.value=material.envMapIntensity;}}function refreshUniformsPhysical(uniforms,material){refreshUniformsStandard(uniforms,material);uniforms.reflectivity.value=material.reflectivity;// also part of uniforms common
  3465. uniforms.clearcoat.value=material.clearcoat;uniforms.clearcoatRoughness.value=material.clearcoatRoughness;if(material.sheen)uniforms.sheen.value.copy(material.sheen);if(material.clearcoatMap){uniforms.clearcoatMap.value=material.clearcoatMap;}if(material.clearcoatRoughnessMap){uniforms.clearcoatRoughnessMap.value=material.clearcoatRoughnessMap;}if(material.clearcoatNormalMap){uniforms.clearcoatNormalScale.value.copy(material.clearcoatNormalScale);uniforms.clearcoatNormalMap.value=material.clearcoatNormalMap;if(material.side===BackSide){uniforms.clearcoatNormalScale.value.negate();}}uniforms.transmission.value=material.transmission;if(material.transmissionMap){uniforms.transmissionMap.value=material.transmissionMap;}}function refreshUniformsMatcap(uniforms,material){if(material.matcap){uniforms.matcap.value=material.matcap;}if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale;if(material.side===BackSide)uniforms.bumpScale.value*=-1;}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale);if(material.side===BackSide)uniforms.normalScale.value.negate();}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}}function refreshUniformsDepth(uniforms,material){if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}}function refreshUniformsDistance(uniforms,material){if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}uniforms.referencePosition.value.copy(material.referencePosition);uniforms.nearDistance.value=material.nearDistance;uniforms.farDistance.value=material.farDistance;}function refreshUniformsNormal(uniforms,material){if(material.bumpMap){uniforms.bumpMap.value=material.bumpMap;uniforms.bumpScale.value=material.bumpScale;if(material.side===BackSide)uniforms.bumpScale.value*=-1;}if(material.normalMap){uniforms.normalMap.value=material.normalMap;uniforms.normalScale.value.copy(material.normalScale);if(material.side===BackSide)uniforms.normalScale.value.negate();}if(material.displacementMap){uniforms.displacementMap.value=material.displacementMap;uniforms.displacementScale.value=material.displacementScale;uniforms.displacementBias.value=material.displacementBias;}}return {refreshFogUniforms:refreshFogUniforms,refreshMaterialUniforms:refreshMaterialUniforms};}function createCanvasElement(){var canvas=document.createElementNS('http://www.w3.org/1999/xhtml','canvas');canvas.style.display='block';return canvas;}function WebGLRenderer(parameters){parameters=parameters||{};var _canvas=parameters.canvas!==undefined?parameters.canvas:createCanvasElement(),_context=parameters.context!==undefined?parameters.context:null,_alpha=parameters.alpha!==undefined?parameters.alpha:false,_depth=parameters.depth!==undefined?parameters.depth:true,_stencil=parameters.stencil!==undefined?parameters.stencil:true,_antialias=parameters.antialias!==undefined?parameters.antialias:false,_premultipliedAlpha=parameters.premultipliedAlpha!==undefined?parameters.premultipliedAlpha:true,_preserveDrawingBuffer=parameters.preserveDrawingBuffer!==undefined?parameters.preserveDrawingBuffer:false,_powerPreference=parameters.powerPreference!==undefined?parameters.powerPreference:'default',_failIfMajorPerformanceCaveat=parameters.failIfMajorPerformanceCaveat!==undefined?parameters.failIfMajorPerformanceCaveat:false;var currentRenderList=null;var currentRenderState=null;// render() can be called from within a callback triggered by another render.
  3466. // We track this so that the nested render call gets its state isolated from the parent render call.
  3467. var renderStateStack=[];// public properties
  3468. this.domElement=_canvas;// Debug configuration container
  3469. this.debug={/**
  3470. * Enables error checking and reporting when shader programs are being compiled
  3471. * @type {boolean}
  3472. */checkShaderErrors:true};// clearing
  3473. this.autoClear=true;this.autoClearColor=true;this.autoClearDepth=true;this.autoClearStencil=true;// scene graph
  3474. this.sortObjects=true;// user-defined clipping
  3475. this.clippingPlanes=[];this.localClippingEnabled=false;// physically based shading
  3476. this.gammaFactor=2.0;// for backwards compatibility
  3477. this.outputEncoding=LinearEncoding;// physical lights
  3478. this.physicallyCorrectLights=false;// tone mapping
  3479. this.toneMapping=NoToneMapping;this.toneMappingExposure=1.0;// morphs
  3480. this.maxMorphTargets=8;this.maxMorphNormals=4;// internal properties
  3481. var _this=this;var _isContextLost=false;// internal state cache
  3482. var _framebuffer=null;var _currentActiveCubeFace=0;var _currentActiveMipmapLevel=0;var _currentRenderTarget=null;var _currentFramebuffer=null;var _currentMaterialId=-1;var _currentCamera=null;var _currentViewport=new Vector4();var _currentScissor=new Vector4();var _currentScissorTest=null;//
  3483. var _width=_canvas.width;var _height=_canvas.height;var _pixelRatio=1;var _opaqueSort=null;var _transparentSort=null;var _viewport=new Vector4(0,0,_width,_height);var _scissor=new Vector4(0,0,_width,_height);var _scissorTest=false;// frustum
  3484. var _frustum=new Frustum();// clipping
  3485. var _clippingEnabled=false;var _localClippingEnabled=false;// camera matrices cache
  3486. var _projScreenMatrix=new Matrix4();var _vector3=new Vector3();var _emptyScene={background:null,fog:null,environment:null,overrideMaterial:null,isScene:true};function getTargetPixelRatio(){return _currentRenderTarget===null?_pixelRatio:1;}// initialize
  3487. var _gl=_context;function getContext(contextNames,contextAttributes){for(var _i124=0;_i124<contextNames.length;_i124++){var contextName=contextNames[_i124];var context=_canvas.getContext(contextName,contextAttributes);if(context!==null)return context;}return null;}try{var contextAttributes={alpha:_alpha,depth:_depth,stencil:_stencil,antialias:_antialias,premultipliedAlpha:_premultipliedAlpha,preserveDrawingBuffer:_preserveDrawingBuffer,powerPreference:_powerPreference,failIfMajorPerformanceCaveat:_failIfMajorPerformanceCaveat};// event listeners must be registered before WebGL context is created, see #12753
  3488. _canvas.addEventListener('webglcontextlost',onContextLost,false);_canvas.addEventListener('webglcontextrestored',onContextRestore,false);if(_gl===null){var contextNames=['webgl2','webgl','experimental-webgl'];if(_this.isWebGL1Renderer===true){contextNames.shift();}_gl=getContext(contextNames,contextAttributes);if(_gl===null){if(getContext(contextNames)){throw new Error('Error creating WebGL context with your selected attributes.');}else {throw new Error('Error creating WebGL context.');}}}// Some experimental-webgl implementations do not have getShaderPrecisionFormat
  3489. if(_gl.getShaderPrecisionFormat===undefined){_gl.getShaderPrecisionFormat=function(){return {'rangeMin':1,'rangeMax':1,'precision':1};};}}catch(error){console.error('THREE.WebGLRenderer: '+error.message);throw error;}var extensions,capabilities,state,info;var properties,textures,cubemaps,attributes,geometries,objects;var programCache,materials,renderLists,renderStates,clipping;var background,morphtargets,bufferRenderer,indexedBufferRenderer;var utils,bindingStates;function initGLContext(){extensions=new WebGLExtensions(_gl);capabilities=new WebGLCapabilities(_gl,extensions,parameters);if(capabilities.isWebGL2===false){extensions.get('WEBGL_depth_texture');extensions.get('OES_texture_float');extensions.get('OES_texture_half_float');extensions.get('OES_texture_half_float_linear');extensions.get('OES_standard_derivatives');extensions.get('OES_element_index_uint');extensions.get('OES_vertex_array_object');extensions.get('ANGLE_instanced_arrays');}extensions.get('OES_texture_float_linear');utils=new WebGLUtils(_gl,extensions,capabilities);state=new WebGLState(_gl,extensions,capabilities);state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());info=new WebGLInfo(_gl);properties=new WebGLProperties();textures=new WebGLTextures(_gl,extensions,state,properties,capabilities,utils,info);cubemaps=new WebGLCubeMaps(_this);attributes=new WebGLAttributes(_gl,capabilities);bindingStates=new WebGLBindingStates(_gl,extensions,attributes,capabilities);geometries=new WebGLGeometries(_gl,attributes,info,bindingStates);objects=new WebGLObjects(_gl,geometries,attributes,info);morphtargets=new WebGLMorphtargets(_gl);clipping=new WebGLClipping(properties);programCache=new WebGLPrograms(_this,cubemaps,extensions,capabilities,bindingStates,clipping);materials=new WebGLMaterials(properties);renderLists=new WebGLRenderLists(properties);renderStates=new WebGLRenderStates(extensions,capabilities);background=new WebGLBackground(_this,cubemaps,state,objects,_premultipliedAlpha);bufferRenderer=new WebGLBufferRenderer(_gl,extensions,info,capabilities);indexedBufferRenderer=new WebGLIndexedBufferRenderer(_gl,extensions,info,capabilities);info.programs=programCache.programs;_this.capabilities=capabilities;_this.extensions=extensions;_this.properties=properties;_this.renderLists=renderLists;_this.state=state;_this.info=info;_this._textures=textures;//add
  3490. }initGLContext();// xr
  3491. var xr=new WebXRManager(_this,_gl);this.xr=xr;// shadow map
  3492. var shadowMap=new WebGLShadowMap(_this,objects,capabilities.maxTextureSize);this.shadowMap=shadowMap;// API
  3493. this.getContext=function(){return _gl;};this.getContextAttributes=function(){return _gl.getContextAttributes();};this.forceContextLoss=function(){var extension=extensions.get('WEBGL_lose_context');if(extension)extension.loseContext();};this.forceContextRestore=function(){var extension=extensions.get('WEBGL_lose_context');if(extension)extension.restoreContext();};this.getPixelRatio=function(){return _pixelRatio;};this.setPixelRatio=function(value){if(value===undefined)return;_pixelRatio=value;this.setSize(_width,_height,false);};this.getSize=function(target){if(target===undefined){console.warn('WebGLRenderer: .getsize() now requires a Vector2 as an argument');target=new Vector2();}return target.set(_width,_height);};this.setSize=function(width,height,updateStyle){if(xr.isPresenting){console.warn('THREE.WebGLRenderer: Can\'t change size while VR device is presenting.');return;}_width=width;_height=height;_canvas.width=Math.floor(width*_pixelRatio);_canvas.height=Math.floor(height*_pixelRatio);if(updateStyle!==false){_canvas.style.width=width+'px';_canvas.style.height=height+'px';}this.setViewport(0,0,width,height);};this.getDrawingBufferSize=function(target){if(target===undefined){console.warn('WebGLRenderer: .getdrawingBufferSize() now requires a Vector2 as an argument');target=new Vector2();}return target.set(_width*_pixelRatio,_height*_pixelRatio).floor();};this.setDrawingBufferSize=function(width,height,pixelRatio){_width=width;_height=height;_pixelRatio=pixelRatio;_canvas.width=Math.floor(width*pixelRatio);_canvas.height=Math.floor(height*pixelRatio);this.setViewport(0,0,width,height);};this.getCurrentViewport=function(target){if(target===undefined){console.warn('WebGLRenderer: .getCurrentViewport() now requires a Vector4 as an argument');target=new Vector4();}return target.copy(_currentViewport);};this.getViewport=function(target){return target.copy(_viewport);};this.setViewport=function(x,y,width,height){if(x.isVector4){_viewport.set(x.x,x.y,x.z,x.w);}else {_viewport.set(x,y,width,height);}state.viewport(_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor());};this.getScissor=function(target){return target.copy(_scissor);};this.setScissor=function(x,y,width,height){if(x.isVector4){_scissor.set(x.x,x.y,x.z,x.w);}else {_scissor.set(x,y,width,height);}state.scissor(_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor());};this.getScissorTest=function(){return _scissorTest;};this.setScissorTest=function(boolean){state.setScissorTest(_scissorTest=boolean);};this.setOpaqueSort=function(method){_opaqueSort=method;};this.setTransparentSort=function(method){_transparentSort=method;};// Clearing
  3494. this.getClearColor=function(target){if(target===undefined){console.warn('WebGLRenderer: .getClearColor() now requires a Color as an argument');target=new Color();}return target.copy(background.getClearColor());};this.setClearColor=function(){background.setClearColor.apply(background,arguments);};this.getClearAlpha=function(){return background.getClearAlpha();};this.setClearAlpha=function(){background.setClearAlpha.apply(background,arguments);};this.clear=function(color,depth,stencil){var bits=0;if(color===undefined||color)bits|=16384;if(depth===undefined||depth)bits|=256;if(stencil===undefined||stencil)bits|=1024;_gl.clear(bits);};this.clearColor=function(){this.clear(true,false,false);};this.clearDepth=function(){this.clear(false,true,false);};this.clearStencil=function(){this.clear(false,false,true);};//
  3495. this.dispose=function(){_canvas.removeEventListener('webglcontextlost',onContextLost,false);_canvas.removeEventListener('webglcontextrestored',onContextRestore,false);renderLists.dispose();renderStates.dispose();properties.dispose();cubemaps.dispose();objects.dispose();bindingStates.dispose();xr.dispose();animation.stop();};// Events
  3496. function onContextLost(event){event.preventDefault();console.log('THREE.WebGLRenderer: Context Lost.');_isContextLost=true;}function onContextRestore(/* event */){console.log('THREE.WebGLRenderer: Context Restored.');_isContextLost=false;initGLContext();}function onMaterialDispose(event){var material=event.target;material.removeEventListener('dispose',onMaterialDispose);deallocateMaterial(material);}// Buffer deallocation
  3497. function deallocateMaterial(material){releaseMaterialProgramReference(material);properties.remove(material);}function releaseMaterialProgramReference(material){var programInfo=properties.get(material).program;if(programInfo!==undefined){programCache.releaseProgram(programInfo);}}// Buffer rendering
  3498. function renderObjectImmediate(object,program){object.render(function(object){_this.renderBufferImmediate(object,program);});}this.renderBufferImmediate=function(object,program){bindingStates.initAttributes();var buffers=properties.get(object);if(object.hasPositions&&!buffers.position)buffers.position=_gl.createBuffer();if(object.hasNormals&&!buffers.normal)buffers.normal=_gl.createBuffer();if(object.hasUvs&&!buffers.uv)buffers.uv=_gl.createBuffer();if(object.hasColors&&!buffers.color)buffers.color=_gl.createBuffer();var programAttributes=program.getAttributes();if(object.hasPositions){_gl.bindBuffer(34962,buffers.position);_gl.bufferData(34962,object.positionArray,35048);bindingStates.enableAttribute(programAttributes.position);_gl.vertexAttribPointer(programAttributes.position,3,5126,false,0,0);}if(object.hasNormals){_gl.bindBuffer(34962,buffers.normal);_gl.bufferData(34962,object.normalArray,35048);bindingStates.enableAttribute(programAttributes.normal);_gl.vertexAttribPointer(programAttributes.normal,3,5126,false,0,0);}if(object.hasUvs){_gl.bindBuffer(34962,buffers.uv);_gl.bufferData(34962,object.uvArray,35048);bindingStates.enableAttribute(programAttributes.uv);_gl.vertexAttribPointer(programAttributes.uv,2,5126,false,0,0);}if(object.hasColors){_gl.bindBuffer(34962,buffers.color);_gl.bufferData(34962,object.colorArray,35048);bindingStates.enableAttribute(programAttributes.color);_gl.vertexAttribPointer(programAttributes.color,3,5126,false,0,0);}bindingStates.disableUnusedAttributes();_gl.drawArrays(4,0,object.count);object.count=0;};this.renderBufferDirect=function(camera,scene,geometry,material,object,group){if(scene===null)scene=_emptyScene;// renderBufferDirect second parameter used to be fog (could be null)
  3499. var frontFaceCW=object.isMesh&&object.matrixWorld.determinant()<0;var program=setProgram(camera,scene,material,object);state.setMaterial(material,frontFaceCW);//
  3500. var index=geometry.index;var position=geometry.attributes.position;//
  3501. if(index===null){if(position===undefined||position.count===0)return;}else if(index.count===0){return;}//
  3502. var rangeFactor=1;if(material.wireframe===true){index=geometries.getWireframeAttribute(geometry);rangeFactor=2;}if(material.morphTargets||material.morphNormals){morphtargets.update(object,geometry,material,program);}bindingStates.setup(object,material,program,geometry,index);var attribute;var renderer=bufferRenderer;if(index!==null){attribute=attributes.get(index);renderer=indexedBufferRenderer;renderer.setIndex(attribute);}//
  3503. var dataCount=index!==null?index.count:position.count;var rangeStart=geometry.drawRange.start*rangeFactor;var rangeCount=geometry.drawRange.count*rangeFactor;var groupStart=group!==null?group.start*rangeFactor:0;var groupCount=group!==null?group.count*rangeFactor:Infinity;var drawStart=Math.max(rangeStart,groupStart);var drawEnd=Math.min(dataCount,rangeStart+rangeCount,groupStart+groupCount)-1;var drawCount=Math.max(0,drawEnd-drawStart+1);if(drawCount===0)return;//
  3504. if(object.isMesh){if(material.wireframe===true){state.setLineWidth(material.wireframeLinewidth*getTargetPixelRatio());renderer.setMode(1);}else {renderer.setMode(4);}}else if(object.isLine){var lineWidth=material.linewidth;if(lineWidth===undefined)lineWidth=1;// Not using Line*Material
  3505. state.setLineWidth(lineWidth*getTargetPixelRatio());if(object.isLineSegments){renderer.setMode(1);}else if(object.isLineLoop){renderer.setMode(2);}else {renderer.setMode(3);}}else if(object.isPoints){renderer.setMode(0);}else if(object.isSprite){renderer.setMode(4);}if(object.isInstancedMesh){renderer.renderInstances(drawStart,drawCount,object.count);}else if(geometry.isInstancedBufferGeometry){var instanceCount=Math.min(geometry.instanceCount,geometry._maxInstanceCount);renderer.renderInstances(drawStart,drawCount,instanceCount);}else {renderer.render(drawStart,drawCount);}};// Compile
  3506. this.compile=function(scene,camera){currentRenderState=renderStates.get(scene);currentRenderState.init();scene.traverseVisible(function(object){if(object.isLight&&object.layers.test(camera.layers)){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object);}}});currentRenderState.setupLights();var compiled=new WeakMap();scene.traverse(function(object){var material=object.material;if(material){if(Array.isArray(material)){for(var _i125=0;_i125<material.length;_i125++){var material2=material[_i125];if(compiled.has(material2)===false){initMaterial(material2,scene,object);compiled.set(material2);}}}else if(compiled.has(material)===false){initMaterial(material,scene,object);compiled.set(material);}}});};// Animation Loop
  3507. var onAnimationFrameCallback=null;function onAnimationFrame(time){if(xr.isPresenting)return;if(onAnimationFrameCallback)onAnimationFrameCallback(time);}var animation=new WebGLAnimation();animation.setAnimationLoop(onAnimationFrame);if(typeof window!=='undefined')animation.setContext(window);this.setAnimationLoop=function(callback){onAnimationFrameCallback=callback;xr.setAnimationLoop(callback);callback===null?animation.stop():animation.start();};// Rendering
  3508. this.render=function(scene,camera){var renderTarget,forceClear;if(arguments[2]!==undefined){console.warn('THREE.WebGLRenderer.render(): the renderTarget argument has been removed. Use .setRenderTarget() instead.');renderTarget=arguments[2];}if(arguments[3]!==undefined){console.warn('THREE.WebGLRenderer.render(): the forceClear argument has been removed. Use .clear() instead.');forceClear=arguments[3];}if(camera!==undefined&&camera.isCamera!==true){console.error('THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.');return;}if(_isContextLost===true)return;// reset caching for this frame
  3509. bindingStates.resetDefaultState();_currentMaterialId=-1;_currentCamera=null;// update scene graph
  3510. if(scene.autoUpdate===true)scene.updateMatrixWorld();// update camera matrices and frustum
  3511. if(camera.parent===null)camera.updateMatrixWorld();if(xr.enabled===true&&xr.isPresenting===true){camera=xr.getCamera(camera);}//
  3512. if(scene.isScene===true)scene.onBeforeRender(_this,scene,camera,renderTarget||_currentRenderTarget);currentRenderState=renderStates.get(scene,renderStateStack.length);currentRenderState.init();renderStateStack.push(currentRenderState);_projScreenMatrix.multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse);_frustum.setFromProjectionMatrix(_projScreenMatrix);_localClippingEnabled=this.localClippingEnabled;_clippingEnabled=clipping.init(this.clippingPlanes,_localClippingEnabled,camera);currentRenderList=renderLists.get(scene,camera);currentRenderList.init();projectObject(scene,camera,0,_this.sortObjects);currentRenderList.finish();if(_this.sortObjects===true){currentRenderList.sort(_opaqueSort,_transparentSort);}//
  3513. if(_clippingEnabled===true)clipping.beginShadows();var shadowsArray=currentRenderState.state.shadowsArray;shadowMap.render(shadowsArray,scene,camera);currentRenderState.setupLights();currentRenderState.setupLightsView(camera);if(_clippingEnabled===true)clipping.endShadows();//
  3514. if(this.info.autoReset===true)this.info.reset();if(renderTarget!==undefined){this.setRenderTarget(renderTarget);}//
  3515. background.render(currentRenderList,scene,camera,forceClear);// render scene
  3516. var opaqueObjects=currentRenderList.opaque;var transparentObjects=currentRenderList.transparent;if(opaqueObjects.length>0)renderObjects(opaqueObjects,scene,camera);if(transparentObjects.length>0)renderObjects(transparentObjects,scene,camera);//
  3517. if(scene.isScene===true)scene.onAfterRender(_this,scene,camera);//
  3518. if(_currentRenderTarget!==null){// Generate mipmap if we're using any kind of mipmap filtering
  3519. textures.updateRenderTargetMipmap(_currentRenderTarget);// resolve multisample renderbuffers to a single-sample texture if necessary
  3520. textures.updateMultisampleRenderTarget(_currentRenderTarget);}// Ensure depth buffer writing is enabled so it can be cleared on next render
  3521. state.buffers.depth.setTest(true);state.buffers.depth.setMask(true);state.buffers.color.setMask(true);state.setPolygonOffset(false);// _gl.finish();
  3522. renderStateStack.pop();if(renderStateStack.length>0){currentRenderState=renderStateStack[renderStateStack.length-1];}else {currentRenderState=null;}currentRenderList=null;};function projectObject(object,camera,groupOrder,sortObjects){if(object.visible===false)return;var visible=object.layers.test(camera.layers);if(visible){if(object.isGroup){groupOrder=object.renderOrder;}else if(object.isLOD){if(object.autoUpdate===true)object.update(camera);}else if(object.isLight){currentRenderState.pushLight(object);if(object.castShadow){currentRenderState.pushShadow(object);}}else if(object.isSprite){if(!object.frustumCulled||_frustum.intersectsSprite(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var geometry=objects.update(object);var material=object.material;if(material.visible){currentRenderList.push(object,geometry,material,groupOrder,_vector3.z,null);}}}else if(object.isImmediateRenderObject){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}currentRenderList.push(object,null,object.material,groupOrder,_vector3.z,null);}else if(object.isMesh||object.isLine||object.isPoints){if(object.isSkinnedMesh){// update skeleton only once in a frame
  3523. if(object.skeleton.frame!==info.render.frame){object.skeleton.update();object.skeleton.frame=info.render.frame;}}if(!object.frustumCulled||_frustum.intersectsObject(object)){if(sortObjects){_vector3.setFromMatrixPosition(object.matrixWorld).applyMatrix4(_projScreenMatrix);}var _geometry2=objects.update(object);var _material=object.material;if(Array.isArray(_material)){var groups=_geometry2.groups;for(var _i126=0,l=groups.length;_i126<l;_i126++){var group=groups[_i126];var groupMaterial=_material[group.materialIndex];if(groupMaterial&&groupMaterial.visible){currentRenderList.push(object,_geometry2,groupMaterial,groupOrder,_vector3.z,group);}}}else if(_material.visible){currentRenderList.push(object,_geometry2,_material,groupOrder,_vector3.z,null);}}}}var children=object.children;for(var _i127=0,_l5=children.length;_i127<_l5;_i127++){projectObject(children[_i127],camera,groupOrder,sortObjects);}}function renderObjects(renderList,scene,camera){var overrideMaterial=scene.isScene===true?scene.overrideMaterial:null;for(var _i128=0,l=renderList.length;_i128<l;_i128++){var renderItem=renderList[_i128];var object=renderItem.object;var geometry=renderItem.geometry;var material=overrideMaterial===null?renderItem.material:overrideMaterial;var group=renderItem.group;if(camera.isArrayCamera){var cameras=camera.cameras;for(var j=0,jl=cameras.length;j<jl;j++){var camera2=cameras[j];if(object.layers.test(camera2.layers)){state.viewport(_currentViewport.copy(camera2.viewport));currentRenderState.setupLightsView(camera2);renderObject(object,scene,camera2,geometry,material,group);}}}else {renderObject(object,scene,camera,geometry,material,group);}}}function renderObject(object,scene,camera,geometry,material,group){object.onBeforeRender(_this,scene,camera,geometry,material,group);object.modelViewMatrix.multiplyMatrices(camera.matrixWorldInverse,object.matrixWorld);object.normalMatrix.getNormalMatrix(object.modelViewMatrix);if(object.isImmediateRenderObject){var program=setProgram(camera,scene,material,object);state.setMaterial(material);bindingStates.reset();renderObjectImmediate(object,program);}else {_this.renderBufferDirect(camera,scene,geometry,material,object,group);}object.onAfterRender(_this,scene,camera,geometry,material,group);}function initMaterial(material,scene,object){if(scene.isScene!==true)scene=_emptyScene;// scene could be a Mesh, Line, Points, ...
  3524. var materialProperties=properties.get(material);var lights=currentRenderState.state.lights;var shadowsArray=currentRenderState.state.shadowsArray;var lightsStateVersion=lights.state.version;var parameters=programCache.getParameters(material,lights.state,shadowsArray,scene,object);var programCacheKey=programCache.getProgramCacheKey(parameters);var program=materialProperties.program;var programChange=true;if(program===undefined){// new material
  3525. material.addEventListener('dispose',onMaterialDispose);}else if(program.cacheKey!==programCacheKey){// changed glsl or parameters
  3526. releaseMaterialProgramReference(material);}else if(materialProperties.lightsStateVersion!==lightsStateVersion){programChange=false;}else if(parameters.shaderID!==undefined){// same glsl and uniform list, envMap still needs the update here to avoid a frame-late effect
  3527. var environment=material.isMeshStandardMaterial?scene.environment:null;materialProperties.envMap=cubemaps.get(material.envMap||environment);return;}else {// only rebuild uniform list
  3528. programChange=false;}if(programChange){parameters.uniforms=programCache.getUniforms(material);material.onBeforeCompile(parameters,_this);program=programCache.acquireProgram(parameters,programCacheKey);materialProperties.program=program;materialProperties.uniforms=parameters.uniforms;materialProperties.outputEncoding=parameters.outputEncoding;}var uniforms=materialProperties.uniforms;if(!material.isShaderMaterial&&!material.isRawShaderMaterial||material.clipping===true){materialProperties.numClippingPlanes=clipping.numPlanes;materialProperties.numIntersection=clipping.numIntersection;uniforms.clippingPlanes=clipping.uniform;}materialProperties.environment=material.isMeshStandardMaterial?scene.environment:null;materialProperties.fog=scene.fog;materialProperties.envMap=cubemaps.get(material.envMap||materialProperties.environment);// store the light setup it was created for
  3529. materialProperties.needsLights=materialNeedsLights(material);materialProperties.lightsStateVersion=lightsStateVersion;if(materialProperties.needsLights){// wire up the material to this renderer's lighting state
  3530. uniforms.ambientLightColor.value=lights.state.ambient;uniforms.lightProbe.value=lights.state.probe;uniforms.directionalLights.value=lights.state.directional;uniforms.directionalLightShadows.value=lights.state.directionalShadow;uniforms.spotLights.value=lights.state.spot;uniforms.spotLightShadows.value=lights.state.spotShadow;uniforms.rectAreaLights.value=lights.state.rectArea;uniforms.ltc_1.value=lights.state.rectAreaLTC1;uniforms.ltc_2.value=lights.state.rectAreaLTC2;uniforms.pointLights.value=lights.state.point;uniforms.pointLightShadows.value=lights.state.pointShadow;uniforms.hemisphereLights.value=lights.state.hemi;uniforms.directionalShadowMap.value=lights.state.directionalShadowMap;uniforms.directionalShadowMatrix.value=lights.state.directionalShadowMatrix;uniforms.spotShadowMap.value=lights.state.spotShadowMap;uniforms.spotShadowMatrix.value=lights.state.spotShadowMatrix;uniforms.pointShadowMap.value=lights.state.pointShadowMap;uniforms.pointShadowMatrix.value=lights.state.pointShadowMatrix;// TODO (abelnation): add area lights shadow info to uniforms
  3531. }var progUniforms=materialProperties.program.getUniforms();var uniformsList=WebGLUniforms.seqWithValue(progUniforms.seq,uniforms);materialProperties.uniformsList=uniformsList;}function setProgram(camera,scene,material,object){if(scene.isScene!==true)scene=_emptyScene;// scene could be a Mesh, Line, Points, ...
  3532. textures.resetTextureUnits();var fog=scene.fog;var environment=material.isMeshStandardMaterial?scene.environment:null;var encoding=_currentRenderTarget===null?_this.outputEncoding:_currentRenderTarget.texture.encoding;var envMap=cubemaps.get(material.envMap||environment);var materialProperties=properties.get(material);var lights=currentRenderState.state.lights;if(_clippingEnabled===true){if(_localClippingEnabled===true||camera!==_currentCamera){var useCache=camera===_currentCamera&&material.id===_currentMaterialId;// we might want to call this function with some ClippingGroup
  3533. // object instead of the material, once it becomes feasible
  3534. // (#8465, #8379)
  3535. clipping.setState(material,camera,useCache);}}if(material.version===materialProperties.__version){if(material.fog&&materialProperties.fog!==fog){initMaterial(material,scene,object);}else if(materialProperties.environment!==environment){initMaterial(material,scene,object);}else if(materialProperties.needsLights&&materialProperties.lightsStateVersion!==lights.state.version){initMaterial(material,scene,object);}else if(materialProperties.numClippingPlanes!==undefined&&(materialProperties.numClippingPlanes!==clipping.numPlanes||materialProperties.numIntersection!==clipping.numIntersection)){initMaterial(material,scene,object);}else if(materialProperties.outputEncoding!==encoding){initMaterial(material,scene,object);}else if(materialProperties.envMap!==envMap){initMaterial(material,scene,object);}}else {initMaterial(material,scene,object);materialProperties.__version=material.version;}var refreshProgram=false;var refreshMaterial=false;var refreshLights=false;var program=materialProperties.program,p_uniforms=program.getUniforms(),m_uniforms=materialProperties.uniforms;if(state.useProgram(program.program)){refreshProgram=true;refreshMaterial=true;refreshLights=true;}if(material.id!==_currentMaterialId){_currentMaterialId=material.id;refreshMaterial=true;}if(refreshProgram||_currentCamera!==camera){p_uniforms.setValue(_gl,'projectionMatrix',camera.projectionMatrix);if(capabilities.logarithmicDepthBuffer){p_uniforms.setValue(_gl,'logDepthBufFC',2.0/(Math.log(camera.far+1.0)/Math.LN2));}if(_currentCamera!==camera){_currentCamera=camera;// lighting uniforms depend on the camera so enforce an update
  3536. // now, in case this material supports lights - or later, when
  3537. // the next material that does gets activated:
  3538. refreshMaterial=true;// set to true on material change
  3539. refreshLights=true;// remains set until update done
  3540. }// load material specific uniforms
  3541. // (shader material also gets them for the sake of genericity)
  3542. if(material.isShaderMaterial||material.isMeshPhongMaterial||material.isMeshToonMaterial||material.isMeshStandardMaterial||material.envMap){var uCamPos=p_uniforms.map.cameraPosition;if(uCamPos!==undefined){uCamPos.setValue(_gl,_vector3.setFromMatrixPosition(camera.matrixWorld));}}if(material.isMeshPhongMaterial||material.isMeshToonMaterial||material.isMeshLambertMaterial||material.isMeshBasicMaterial||material.isMeshStandardMaterial||material.isShaderMaterial){p_uniforms.setValue(_gl,'isOrthographic',camera.isOrthographicCamera===true);}if(material.isMeshPhongMaterial||material.isMeshToonMaterial||material.isMeshLambertMaterial||material.isMeshBasicMaterial||material.isMeshStandardMaterial||material.isShaderMaterial||material.isShadowMaterial||material.skinning){p_uniforms.setValue(_gl,'viewMatrix',camera.matrixWorldInverse);}}// skinning uniforms must be set even if material didn't change
  3543. // auto-setting of texture unit for bone texture must go before other textures
  3544. // otherwise textures used for skinning can take over texture units reserved for other material textures
  3545. if(material.skinning){p_uniforms.setOptional(_gl,object,'bindMatrix');p_uniforms.setOptional(_gl,object,'bindMatrixInverse');var skeleton=object.skeleton;if(skeleton){var bones=skeleton.bones;if(capabilities.floatVertexTextures){if(skeleton.boneTexture===null){// layout (1 matrix = 4 pixels)
  3546. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  3547. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  3548. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  3549. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  3550. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  3551. var size=Math.sqrt(bones.length*4);// 4 pixels needed for 1 matrix
  3552. size=MathUtils.ceilPowerOfTwo(size);size=Math.max(size,4);var boneMatrices=new Float32Array(size*size*4);// 4 floats per RGBA pixel
  3553. boneMatrices.set(skeleton.boneMatrices);// copy current values
  3554. var boneTexture=new DataTexture(boneMatrices,size,size,RGBAFormat,FloatType);skeleton.boneMatrices=boneMatrices;skeleton.boneTexture=boneTexture;skeleton.boneTextureSize=size;}p_uniforms.setValue(_gl,'boneTexture',skeleton.boneTexture,textures);p_uniforms.setValue(_gl,'boneTextureSize',skeleton.boneTextureSize);}else {p_uniforms.setOptional(_gl,skeleton,'boneMatrices');}}}if(refreshMaterial||materialProperties.receiveShadow!==object.receiveShadow){materialProperties.receiveShadow=object.receiveShadow;p_uniforms.setValue(_gl,'receiveShadow',object.receiveShadow);}if(refreshMaterial){p_uniforms.setValue(_gl,'toneMappingExposure',_this.toneMappingExposure);if(materialProperties.needsLights){// the current material requires lighting info
  3555. // note: all lighting uniforms are always set correctly
  3556. // they simply reference the renderer's state for their
  3557. // values
  3558. //
  3559. // use the current material's .needsUpdate flags to set
  3560. // the GL state when required
  3561. markUniformsLightsNeedsUpdate(m_uniforms,refreshLights);}// refresh uniforms common to several materials
  3562. if(fog&&material.fog){materials.refreshFogUniforms(m_uniforms,fog);}materials.refreshMaterialUniforms(m_uniforms,material,_pixelRatio,_height);WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);}if(material.isShaderMaterial&&material.uniformsNeedUpdate===true){WebGLUniforms.upload(_gl,materialProperties.uniformsList,m_uniforms,textures);material.uniformsNeedUpdate=false;}if(material.isSpriteMaterial){p_uniforms.setValue(_gl,'center',object.center);}// common matrices
  3563. p_uniforms.setValue(_gl,'modelViewMatrix',object.modelViewMatrix);p_uniforms.setValue(_gl,'normalMatrix',object.normalMatrix);p_uniforms.setValue(_gl,'modelMatrix',object.matrixWorld);return program;}// If uniforms are marked as clean, they don't need to be loaded to the GPU.
  3564. function markUniformsLightsNeedsUpdate(uniforms,value){uniforms.ambientLightColor.needsUpdate=value;uniforms.lightProbe.needsUpdate=value;uniforms.directionalLights.needsUpdate=value;uniforms.directionalLightShadows.needsUpdate=value;uniforms.pointLights.needsUpdate=value;uniforms.pointLightShadows.needsUpdate=value;uniforms.spotLights.needsUpdate=value;uniforms.spotLightShadows.needsUpdate=value;uniforms.rectAreaLights.needsUpdate=value;uniforms.hemisphereLights.needsUpdate=value;}function materialNeedsLights(material){return material.isMeshLambertMaterial||material.isMeshToonMaterial||material.isMeshPhongMaterial||material.isMeshStandardMaterial||material.isShadowMaterial||material.isShaderMaterial&&material.lights===true;}//
  3565. this.setFramebuffer=function(value){if(_framebuffer!==value&&_currentRenderTarget===null)_gl.bindFramebuffer(36160,value);_framebuffer=value;};this.getActiveCubeFace=function(){return _currentActiveCubeFace;};this.getActiveMipmapLevel=function(){return _currentActiveMipmapLevel;};this.getRenderList=function(){return currentRenderList;};this.setRenderList=function(renderList){currentRenderList=renderList;};this.getRenderTarget=function(){return _currentRenderTarget;};this.setRenderTarget=function(renderTarget){var activeCubeFace=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var activeMipmapLevel=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;_currentRenderTarget=renderTarget;_currentActiveCubeFace=activeCubeFace;_currentActiveMipmapLevel=activeMipmapLevel;if(renderTarget&&properties.get(renderTarget).__webglFramebuffer===undefined){textures.setupRenderTarget(renderTarget);}var framebuffer=_framebuffer;var isCube=false;if(renderTarget){var __webglFramebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget){framebuffer=__webglFramebuffer[activeCubeFace];isCube=true;}else if(renderTarget.isWebGLMultisampleRenderTarget){framebuffer=properties.get(renderTarget).__webglMultisampledFramebuffer;}else {framebuffer=__webglFramebuffer;}_currentViewport.copy(renderTarget.viewport);_currentScissor.copy(renderTarget.scissor);_currentScissorTest=renderTarget.scissorTest;}else {_currentViewport.copy(_viewport).multiplyScalar(_pixelRatio).floor();_currentScissor.copy(_scissor).multiplyScalar(_pixelRatio).floor();_currentScissorTest=_scissorTest;}if(_currentFramebuffer!==framebuffer){_gl.bindFramebuffer(36160,framebuffer);_currentFramebuffer=framebuffer;}state.viewport(_currentViewport);state.scissor(_currentScissor);state.setScissorTest(_currentScissorTest);if(isCube){var textureProperties=properties.get(renderTarget.texture);_gl.framebufferTexture2D(36160,36064,34069+activeCubeFace,textureProperties.__webglTexture,activeMipmapLevel);}};this.readRenderTargetPixels=function(renderTarget,x,y,width,height,buffer,activeCubeFaceIndex){if(!(renderTarget&&renderTarget.isWebGLRenderTarget)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.');return;}var framebuffer=properties.get(renderTarget).__webglFramebuffer;if(renderTarget.isWebGLCubeRenderTarget&&activeCubeFaceIndex!==undefined){framebuffer=framebuffer[activeCubeFaceIndex];}if(framebuffer){var restore=false;if(framebuffer!==_currentFramebuffer){_gl.bindFramebuffer(36160,framebuffer);restore=true;}try{var texture=renderTarget.texture;var textureFormat=texture.format;var textureType=texture.type;if(textureFormat!==RGBAFormat&&utils.convert(textureFormat)!==_gl.getParameter(35739)){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.');return;}if(textureType!==UnsignedByteType&&utils.convert(textureType)!==_gl.getParameter(35738)&&// IE11, Edge and Chrome Mac < 52 (#9513)
  3566. !(textureType===FloatType&&(capabilities.isWebGL2||extensions.get('OES_texture_float')||extensions.get('WEBGL_color_buffer_float')))&&// Chrome Mac >= 52 and Firefox
  3567. !(textureType===HalfFloatType&&(capabilities.isWebGL2?extensions.get('EXT_color_buffer_float'):extensions.get('EXT_color_buffer_half_float')))){console.error('THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.');return;}if(_gl.checkFramebufferStatus(36160)===36053){// the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  3568. if(x>=0&&x<=renderTarget.width-width&&y>=0&&y<=renderTarget.height-height){_gl.readPixels(x,y,width,height,utils.convert(textureFormat),utils.convert(textureType),buffer);}}else {console.error('THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.');}}finally{if(restore){_gl.bindFramebuffer(36160,_currentFramebuffer);}}}};this.copyFramebufferToTexture=function(position,texture){var level=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var levelScale=Math.pow(2,-level);var width=Math.floor(texture.image.width*levelScale);var height=Math.floor(texture.image.height*levelScale);var glFormat=utils.convert(texture.format);textures.setTexture2D(texture,0);_gl.copyTexImage2D(3553,level,glFormat,position.x,position.y,width,height,0);state.unbindTexture();};this.copyTextureToTexture=function(position,srcTexture,dstTexture){var level=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var width=srcTexture.image.width;var height=srcTexture.image.height;var glFormat=utils.convert(dstTexture.format);var glType=utils.convert(dstTexture.type);textures.setTexture2D(dstTexture,0);// As another texture upload may have changed pixelStorei
  3569. // parameters, make sure they are correct for the dstTexture
  3570. _gl.pixelStorei(37440,dstTexture.flipY);_gl.pixelStorei(37441,dstTexture.premultiplyAlpha);_gl.pixelStorei(3317,dstTexture.unpackAlignment);if(srcTexture.isDataTexture){_gl.texSubImage2D(3553,level,position.x,position.y,width,height,glFormat,glType,srcTexture.image.data);}else {if(srcTexture.isCompressedTexture){_gl.compressedTexSubImage2D(3553,level,position.x,position.y,srcTexture.mipmaps[0].width,srcTexture.mipmaps[0].height,glFormat,srcTexture.mipmaps[0].data);}else {_gl.texSubImage2D(3553,level,position.x,position.y,glFormat,glType,srcTexture.image);}}// Generate mipmaps only when copying level 0
  3571. if(level===0&&dstTexture.generateMipmaps)_gl.generateMipmap(3553);state.unbindTexture();};this.initTexture=function(texture){textures.setTexture2D(texture,0);state.unbindTexture();};this.resetState=function(){state.reset();bindingStates.reset();};if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:this}));// eslint-disable-line no-undef
  3572. }}function WebGL1Renderer(parameters){WebGLRenderer.call(this,parameters);}WebGL1Renderer.prototype=Object.assign(Object.create(WebGLRenderer.prototype),{constructor:WebGL1Renderer,isWebGL1Renderer:true});class FogExp2{constructor(color,density){Object.defineProperty(this,'isFogExp2',{value:true});this.name='';this.color=new Color(color);this.density=density!==undefined?density:0.00025;}clone(){return new FogExp2(this.color,this.density);}toJSON(/* meta */){return {type:'FogExp2',color:this.color.getHex(),density:this.density};}}class Fog{constructor(color,near,far){Object.defineProperty(this,'isFog',{value:true});this.name='';this.color=new Color(color);this.near=near!==undefined?near:1;this.far=far!==undefined?far:1000;}clone(){return new Fog(this.color,this.near,this.far);}toJSON(/* meta */){return {type:'Fog',color:this.color.getHex(),near:this.near,far:this.far};}}class Scene extends Object3D{constructor(){super();Object.defineProperty(this,'isScene',{value:true});this.type='Scene';this.background=null;this.environment=null;this.fog=null;this.overrideMaterial=null;this.autoUpdate=true;// checked by the renderer
  3573. if(typeof __THREE_DEVTOOLS__!=='undefined'){__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('observe',{detail:this}));// eslint-disable-line no-undef
  3574. }}copy(source,recursive){super.copy(source,recursive);if(source.background!==null)this.background=source.background.clone();if(source.environment!==null)this.environment=source.environment.clone();if(source.fog!==null)this.fog=source.fog.clone();if(source.overrideMaterial!==null)this.overrideMaterial=source.overrideMaterial.clone();this.autoUpdate=source.autoUpdate;this.matrixAutoUpdate=source.matrixAutoUpdate;return this;}toJSON(meta){var data=super.toJSON(meta);if(this.background!==null)data.object.background=this.background.toJSON(meta);if(this.environment!==null)data.object.environment=this.environment.toJSON(meta);if(this.fog!==null)data.object.fog=this.fog.toJSON();return data;}}function InterleavedBuffer(array,stride){this.array=array;this.stride=stride;this.count=array!==undefined?array.length/stride:0;this.usage=StaticDrawUsage;this.updateRange={offset:0,count:-1};this.version=0;this.uuid=MathUtils.generateUUID();}Object.defineProperty(InterleavedBuffer.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(InterleavedBuffer.prototype,{isInterleavedBuffer:true,onUploadCallback:function onUploadCallback(){},setUsage:function setUsage(value){this.usage=value;return this;},copy:function copy(source){this.array=new source.array.constructor(source.array);this.count=source.count;this.stride=source.stride;this.usage=source.usage;return this;},copyAt:function copyAt(index1,attribute,index2){index1*=this.stride;index2*=attribute.stride;for(var _i129=0,l=this.stride;_i129<l;_i129++){this.array[index1+_i129]=attribute.array[index2+_i129];}return this;},set:function set(value){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.array.set(value,offset);return this;},clone:function clone(data){if(data.arrayBuffers===undefined){data.arrayBuffers={};}if(this.array.buffer._uuid===undefined){this.array.buffer._uuid=MathUtils.generateUUID();}if(data.arrayBuffers[this.array.buffer._uuid]===undefined){data.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer;}var array=new this.array.constructor(data.arrayBuffers[this.array.buffer._uuid]);var ib=new InterleavedBuffer(array,this.stride);ib.setUsage(this.usage);return ib;},onUpload:function onUpload(callback){this.onUploadCallback=callback;return this;},toJSON:function toJSON(data){if(data.arrayBuffers===undefined){data.arrayBuffers={};}// generate UUID for array buffer if necessary
  3575. if(this.array.buffer._uuid===undefined){this.array.buffer._uuid=MathUtils.generateUUID();}if(data.arrayBuffers[this.array.buffer._uuid]===undefined){data.arrayBuffers[this.array.buffer._uuid]=Array.prototype.slice.call(new Uint32Array(this.array.buffer));}//
  3576. return {uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride};}});var _vector$6=new Vector3();function InterleavedBufferAttribute(interleavedBuffer,itemSize,offset,normalized){this.name='';this.data=interleavedBuffer;this.itemSize=itemSize;this.offset=offset;this.normalized=normalized===true;}Object.defineProperties(InterleavedBufferAttribute.prototype,{count:{get:function get(){return this.data.count;}},array:{get:function get(){return this.data.array;}},needsUpdate:{set:function set(value){this.data.needsUpdate=value;}}});Object.assign(InterleavedBufferAttribute.prototype,{isInterleavedBufferAttribute:true,applyMatrix4:function applyMatrix4(m){for(var _i130=0,l=this.data.count;_i130<l;_i130++){_vector$6.x=this.getX(_i130);_vector$6.y=this.getY(_i130);_vector$6.z=this.getZ(_i130);_vector$6.applyMatrix4(m);this.setXYZ(_i130,_vector$6.x,_vector$6.y,_vector$6.z);}return this;},setX:function setX(index,x){this.data.array[index*this.data.stride+this.offset]=x;return this;},setY:function setY(index,y){this.data.array[index*this.data.stride+this.offset+1]=y;return this;},setZ:function setZ(index,z){this.data.array[index*this.data.stride+this.offset+2]=z;return this;},setW:function setW(index,w){this.data.array[index*this.data.stride+this.offset+3]=w;return this;},getX:function getX(index){return this.data.array[index*this.data.stride+this.offset];},getY:function getY(index){return this.data.array[index*this.data.stride+this.offset+1];},getZ:function getZ(index){return this.data.array[index*this.data.stride+this.offset+2];},getW:function getW(index){return this.data.array[index*this.data.stride+this.offset+3];},setXY:function setXY(index,x,y){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;return this;},setXYZ:function setXYZ(index,x,y,z){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;this.data.array[index+2]=z;return this;},setXYZW:function setXYZW(index,x,y,z,w){index=index*this.data.stride+this.offset;this.data.array[index+0]=x;this.data.array[index+1]=y;this.data.array[index+2]=z;this.data.array[index+3]=w;return this;},clone:function clone(data){if(data===undefined){console.log('THREE.InterleavedBufferAttribute.clone(): Cloning an interlaved buffer attribute will deinterleave buffer data.');var array=[];for(var _i131=0;_i131<this.count;_i131++){var index=_i131*this.data.stride+this.offset;for(var j=0;j<this.itemSize;j++){array.push(this.data.array[index+j]);}}return new BufferAttribute(new this.array.constructor(array),this.itemSize,this.normalized);}else {if(data.interleavedBuffers===undefined){data.interleavedBuffers={};}if(data.interleavedBuffers[this.data.uuid]===undefined){data.interleavedBuffers[this.data.uuid]=this.data.clone(data);}return new InterleavedBufferAttribute(data.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized);}},toJSON:function toJSON(data){if(data===undefined){console.log('THREE.InterleavedBufferAttribute.toJSON(): Serializing an interlaved buffer attribute will deinterleave buffer data.');var array=[];for(var _i132=0;_i132<this.count;_i132++){var index=_i132*this.data.stride+this.offset;for(var j=0;j<this.itemSize;j++){array.push(this.data.array[index+j]);}}// deinterleave data and save it as an ordinary buffer attribute for now
  3577. return {itemSize:this.itemSize,type:this.array.constructor.name,array:array,normalized:this.normalized};}else {// save as true interlaved attribtue
  3578. if(data.interleavedBuffers===undefined){data.interleavedBuffers={};}if(data.interleavedBuffers[this.data.uuid]===undefined){data.interleavedBuffers[this.data.uuid]=this.data.toJSON(data);}return {isInterleavedBufferAttribute:true,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized};}}});/**
  3579. * parameters = {
  3580. * color: <hex>,
  3581. * map: new THREE.Texture( <Image> ),
  3582. * alphaMap: new THREE.Texture( <Image> ),
  3583. * rotation: <float>,
  3584. * sizeAttenuation: <bool>
  3585. * }
  3586. */function SpriteMaterial(parameters){Material.call(this);this.type='SpriteMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.rotation=0;this.sizeAttenuation=true;this.transparent=true;this.setValues(parameters);}SpriteMaterial.prototype=Object.create(Material.prototype);SpriteMaterial.prototype.constructor=SpriteMaterial;SpriteMaterial.prototype.isSpriteMaterial=true;SpriteMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.alphaMap=source.alphaMap;this.rotation=source.rotation;this.sizeAttenuation=source.sizeAttenuation;return this;};var _geometry;var _intersectPoint=new Vector3();var _worldScale=new Vector3();var _mvPosition=new Vector3();var _alignedPosition=new Vector2();var _rotatedPosition=new Vector2();var _viewWorldMatrix=new Matrix4();var _vA$1=new Vector3();var _vB$1=new Vector3();var _vC$1=new Vector3();var _uvA$1=new Vector2();var _uvB$1=new Vector2();var _uvC$1=new Vector2();function Sprite$1(material){Object3D.call(this);this.type='Sprite';if(_geometry===undefined){_geometry=new BufferGeometry();var float32Array=new Float32Array([-0.5,-0.5,0,0,0,0.5,-0.5,0,1,0,0.5,0.5,0,1,1,-0.5,0.5,0,0,1]);var interleavedBuffer=new InterleavedBuffer(float32Array,5);_geometry.setIndex([0,1,2,0,2,3]);_geometry.setAttribute('position',new InterleavedBufferAttribute(interleavedBuffer,3,0,false));_geometry.setAttribute('uv',new InterleavedBufferAttribute(interleavedBuffer,2,3,false));}this.geometry=_geometry;this.material=material!==undefined?material:new SpriteMaterial();this.center=new Vector2(0.5,0.5);}Sprite$1.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Sprite$1,isSprite:true,raycast:function raycast(raycaster,intersects){if(raycaster.camera===null){console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.');}_worldScale.setFromMatrixScale(this.matrixWorld);_viewWorldMatrix.copy(raycaster.camera.matrixWorld);this.modelViewMatrix.multiplyMatrices(raycaster.camera.matrixWorldInverse,this.matrixWorld);_mvPosition.setFromMatrixPosition(this.modelViewMatrix);if(raycaster.camera.isPerspectiveCamera&&this.material.sizeAttenuation===false){_worldScale.multiplyScalar(-_mvPosition.z);}var rotation=this.material.rotation;var sin,cos;if(rotation!==0){cos=Math.cos(rotation);sin=Math.sin(rotation);}var center=this.center;transformVertex(_vA$1.set(-0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vB$1.set(0.5,-0.5,0),_mvPosition,center,_worldScale,sin,cos);transformVertex(_vC$1.set(0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvA$1.set(0,0);_uvB$1.set(1,0);_uvC$1.set(1,1);// check first triangle
  3587. var intersect=raycaster.ray.intersectTriangle(_vA$1,_vB$1,_vC$1,false,_intersectPoint);if(intersect===null){// check second triangle
  3588. transformVertex(_vB$1.set(-0.5,0.5,0),_mvPosition,center,_worldScale,sin,cos);_uvB$1.set(0,1);intersect=raycaster.ray.intersectTriangle(_vA$1,_vC$1,_vB$1,false,_intersectPoint);if(intersect===null){return;}}var distance=raycaster.ray.origin.distanceTo(_intersectPoint);if(distance<raycaster.near||distance>raycaster.far)return;intersects.push({distance:distance,point:_intersectPoint.clone(),uv:Triangle.getUV(_intersectPoint,_vA$1,_vB$1,_vC$1,_uvA$1,_uvB$1,_uvC$1,new Vector2()),face:null,object:this});},copy:function copy(source){Object3D.prototype.copy.call(this,source);if(source.center!==undefined)this.center.copy(source.center);this.material=source.material;return this;}});function transformVertex(vertexPosition,mvPosition,center,scale,sin,cos){// compute position in camera space
  3589. _alignedPosition.subVectors(vertexPosition,center).addScalar(0.5).multiply(scale);// to check if rotation is not zero
  3590. if(sin!==undefined){_rotatedPosition.x=cos*_alignedPosition.x-sin*_alignedPosition.y;_rotatedPosition.y=sin*_alignedPosition.x+cos*_alignedPosition.y;}else {_rotatedPosition.copy(_alignedPosition);}vertexPosition.copy(mvPosition);vertexPosition.x+=_rotatedPosition.x;vertexPosition.y+=_rotatedPosition.y;// transform to world space
  3591. vertexPosition.applyMatrix4(_viewWorldMatrix);}var _v1$4=new Vector3();var _v2$2=new Vector3();function LOD(){Object3D.call(this);this._currentLevel=0;this.type='LOD';Object.defineProperties(this,{levels:{enumerable:true,value:[]}});this.autoUpdate=true;}LOD.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:LOD,isLOD:true,copy:function copy(source){Object3D.prototype.copy.call(this,source,false);var levels=source.levels;for(var _i133=0,l=levels.length;_i133<l;_i133++){var level=levels[_i133];this.addLevel(level.object.clone(),level.distance);}this.autoUpdate=source.autoUpdate;return this;},addLevel:function addLevel(object){var distance=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;distance=Math.abs(distance);var levels=this.levels;var l;for(l=0;l<levels.length;l++){if(distance<levels[l].distance){break;}}levels.splice(l,0,{distance:distance,object:object});this.add(object);return this;},getCurrentLevel:function getCurrentLevel(){return this._currentLevel;},getObjectForDistance:function getObjectForDistance(distance){var levels=this.levels;if(levels.length>0){var _i134,l;for(_i134=1,l=levels.length;_i134<l;_i134++){if(distance<levels[_i134].distance){break;}}return levels[_i134-1].object;}return null;},raycast:function raycast(raycaster,intersects){var levels=this.levels;if(levels.length>0){_v1$4.setFromMatrixPosition(this.matrixWorld);var distance=raycaster.ray.origin.distanceTo(_v1$4);this.getObjectForDistance(distance).raycast(raycaster,intersects);}},update:function update(camera){var levels=this.levels;if(levels.length>1){_v1$4.setFromMatrixPosition(camera.matrixWorld);_v2$2.setFromMatrixPosition(this.matrixWorld);var distance=_v1$4.distanceTo(_v2$2)/camera.zoom;levels[0].object.visible=true;var _i135,l;for(_i135=1,l=levels.length;_i135<l;_i135++){if(distance>=levels[_i135].distance){levels[_i135-1].object.visible=false;levels[_i135].object.visible=true;}else {break;}}this._currentLevel=_i135-1;for(;_i135<l;_i135++){levels[_i135].object.visible=false;}}},toJSON:function toJSON(meta){var data=Object3D.prototype.toJSON.call(this,meta);if(this.autoUpdate===false)data.object.autoUpdate=false;data.object.levels=[];var levels=this.levels;for(var _i136=0,l=levels.length;_i136<l;_i136++){var level=levels[_i136];data.object.levels.push({object:level.object.uuid,distance:level.distance});}return data;}});var _basePosition=new Vector3();var _skinIndex=new Vector4();var _skinWeight=new Vector4();var _vector$7=new Vector3();var _matrix$1=new Matrix4();function SkinnedMesh(geometry,material){if(geometry&&geometry.isGeometry){console.error('THREE.SkinnedMesh no longer supports THREE.Geometry. Use THREE.BufferGeometry instead.');}Mesh.call(this,geometry,material);this.type='SkinnedMesh';this.bindMode='attached';this.bindMatrix=new Matrix4();this.bindMatrixInverse=new Matrix4();}SkinnedMesh.prototype=Object.assign(Object.create(Mesh.prototype),{constructor:SkinnedMesh,isSkinnedMesh:true,copy:function copy(source){Mesh.prototype.copy.call(this,source);this.bindMode=source.bindMode;this.bindMatrix.copy(source.bindMatrix);this.bindMatrixInverse.copy(source.bindMatrixInverse);this.skeleton=source.skeleton;return this;},bind:function bind(skeleton,bindMatrix){this.skeleton=skeleton;if(bindMatrix===undefined){this.updateMatrixWorld(true);this.skeleton.calculateInverses();bindMatrix=this.matrixWorld;}this.bindMatrix.copy(bindMatrix);this.bindMatrixInverse.copy(bindMatrix).invert();},pose:function pose(){this.skeleton.pose();},normalizeSkinWeights:function normalizeSkinWeights(){var vector=new Vector4();var skinWeight=this.geometry.attributes.skinWeight;for(var _i137=0,l=skinWeight.count;_i137<l;_i137++){vector.x=skinWeight.getX(_i137);vector.y=skinWeight.getY(_i137);vector.z=skinWeight.getZ(_i137);vector.w=skinWeight.getW(_i137);var scale=1.0/vector.manhattanLength();if(scale!==Infinity){vector.multiplyScalar(scale);}else {vector.set(1,0,0,0);// do something reasonable
  3592. }skinWeight.setXYZW(_i137,vector.x,vector.y,vector.z,vector.w);}},updateMatrixWorld:function updateMatrixWorld(force){Mesh.prototype.updateMatrixWorld.call(this,force);if(this.bindMode==='attached'){this.bindMatrixInverse.copy(this.matrixWorld).invert();}else if(this.bindMode==='detached'){this.bindMatrixInverse.copy(this.bindMatrix).invert();}else {console.warn('THREE.SkinnedMesh: Unrecognized bindMode: '+this.bindMode);}},boneTransform:function boneTransform(index,target){var skeleton=this.skeleton;var geometry=this.geometry;_skinIndex.fromBufferAttribute(geometry.attributes.skinIndex,index);_skinWeight.fromBufferAttribute(geometry.attributes.skinWeight,index);_basePosition.fromBufferAttribute(geometry.attributes.position,index).applyMatrix4(this.bindMatrix);target.set(0,0,0);for(var _i138=0;_i138<4;_i138++){var weight=_skinWeight.getComponent(_i138);if(weight!==0){var boneIndex=_skinIndex.getComponent(_i138);_matrix$1.multiplyMatrices(skeleton.bones[boneIndex].matrixWorld,skeleton.boneInverses[boneIndex]);target.addScaledVector(_vector$7.copy(_basePosition).applyMatrix4(_matrix$1),weight);}}return target.applyMatrix4(this.bindMatrixInverse);}});function Bone(){Object3D.call(this);this.type='Bone';}Bone.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Bone,isBone:true});var _offsetMatrix=new Matrix4();var _identityMatrix=new Matrix4();function Skeleton(){var bones=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var boneInverses=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];this.uuid=MathUtils.generateUUID();this.bones=bones.slice(0);this.boneInverses=boneInverses;this.boneMatrices=null;this.boneTexture=null;this.boneTextureSize=0;this.frame=-1;this.init();}Object.assign(Skeleton.prototype,{init:function init(){var bones=this.bones;var boneInverses=this.boneInverses;this.boneMatrices=new Float32Array(bones.length*16);// calculate inverse bone matrices if necessary
  3593. if(boneInverses.length===0){this.calculateInverses();}else {// handle special case
  3594. if(bones.length!==boneInverses.length){console.warn('THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.');this.boneInverses=[];for(var _i139=0,il=this.bones.length;_i139<il;_i139++){this.boneInverses.push(new Matrix4());}}}},calculateInverses:function calculateInverses(){this.boneInverses.length=0;for(var _i140=0,il=this.bones.length;_i140<il;_i140++){var inverse=new Matrix4();if(this.bones[_i140]){inverse.copy(this.bones[_i140].matrixWorld).invert();}this.boneInverses.push(inverse);}},pose:function pose(){// recover the bind-time world matrices
  3595. for(var _i141=0,il=this.bones.length;_i141<il;_i141++){var bone=this.bones[_i141];if(bone){bone.matrixWorld.copy(this.boneInverses[_i141]).invert();}}// compute the local matrices, positions, rotations and scales
  3596. for(var _i142=0,_il11=this.bones.length;_i142<_il11;_i142++){var _bone=this.bones[_i142];if(_bone){if(_bone.parent&&_bone.parent.isBone){_bone.matrix.copy(_bone.parent.matrixWorld).invert();_bone.matrix.multiply(_bone.matrixWorld);}else {_bone.matrix.copy(_bone.matrixWorld);}_bone.matrix.decompose(_bone.position,_bone.quaternion,_bone.scale);}}},update:function update(){var bones=this.bones;var boneInverses=this.boneInverses;var boneMatrices=this.boneMatrices;var boneTexture=this.boneTexture;// flatten bone matrices to array
  3597. for(var _i143=0,il=bones.length;_i143<il;_i143++){// compute the offset between the current and the original transform
  3598. var matrix=bones[_i143]?bones[_i143].matrixWorld:_identityMatrix;_offsetMatrix.multiplyMatrices(matrix,boneInverses[_i143]);_offsetMatrix.toArray(boneMatrices,_i143*16);}if(boneTexture!==null){boneTexture.needsUpdate=true;}},clone:function clone(){return new Skeleton(this.bones,this.boneInverses);},getBoneByName:function getBoneByName(name){for(var _i144=0,il=this.bones.length;_i144<il;_i144++){var bone=this.bones[_i144];if(bone.name===name){return bone;}}return undefined;},dispose:function dispose(){if(this.boneTexture!==null){this.boneTexture.dispose();this.boneTexture=null;}},fromJSON:function fromJSON(json,bones){this.uuid=json.uuid;for(var _i145=0,l=json.bones.length;_i145<l;_i145++){var uuid=json.bones[_i145];var bone=bones[uuid];if(bone===undefined){console.warn('THREE.Skeleton: No bone found with UUID:',uuid);bone=new Bone();}this.bones.push(bone);this.boneInverses.push(new Matrix4().fromArray(json.boneInverses[_i145]));}this.init();return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Skeleton',generator:'Skeleton.toJSON'},bones:[],boneInverses:[]};data.uuid=this.uuid;var bones=this.bones;var boneInverses=this.boneInverses;for(var _i146=0,l=bones.length;_i146<l;_i146++){var bone=bones[_i146];data.bones.push(bone.uuid);var boneInverse=boneInverses[_i146];data.boneInverses.push(boneInverse.toArray());}return data;}});var _instanceLocalMatrix=new Matrix4();var _instanceWorldMatrix=new Matrix4();var _instanceIntersects=[];var _mesh=new Mesh();function InstancedMesh(geometry,material,count){Mesh.call(this,geometry,material);this.instanceMatrix=new BufferAttribute(new Float32Array(count*16),16);this.instanceColor=null;this.count=count;this.frustumCulled=false;}InstancedMesh.prototype=Object.assign(Object.create(Mesh.prototype),{constructor:InstancedMesh,isInstancedMesh:true,copy:function copy(source){Mesh.prototype.copy.call(this,source);this.instanceMatrix.copy(source.instanceMatrix);this.count=source.count;return this;},getColorAt:function getColorAt(index,color){color.fromArray(this.instanceColor.array,index*3);},getMatrixAt:function getMatrixAt(index,matrix){matrix.fromArray(this.instanceMatrix.array,index*16);},raycast:function raycast(raycaster,intersects){var matrixWorld=this.matrixWorld;var raycastTimes=this.count;_mesh.geometry=this.geometry;_mesh.material=this.material;if(_mesh.material===undefined)return;for(var instanceId=0;instanceId<raycastTimes;instanceId++){// calculate the world matrix for each instance
  3599. this.getMatrixAt(instanceId,_instanceLocalMatrix);_instanceWorldMatrix.multiplyMatrices(matrixWorld,_instanceLocalMatrix);// the mesh represents this single instance
  3600. _mesh.matrixWorld=_instanceWorldMatrix;_mesh.raycast(raycaster,_instanceIntersects);// process the result of raycast
  3601. for(var _i147=0,l=_instanceIntersects.length;_i147<l;_i147++){var intersect=_instanceIntersects[_i147];intersect.instanceId=instanceId;intersect.object=this;intersects.push(intersect);}_instanceIntersects.length=0;}},setColorAt:function setColorAt(index,color){if(this.instanceColor===null){this.instanceColor=new BufferAttribute(new Float32Array(this.count*3),3);}color.toArray(this.instanceColor.array,index*3);},setMatrixAt:function setMatrixAt(index,matrix){matrix.toArray(this.instanceMatrix.array,index*16);},updateMorphTargets:function updateMorphTargets(){},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});/**
  3602. * parameters = {
  3603. * color: <hex>,
  3604. * opacity: <float>,
  3605. *
  3606. * linewidth: <float>,
  3607. * linecap: "round",
  3608. * linejoin: "round"
  3609. * }
  3610. */function LineBasicMaterial(parameters){Material.call(this);this.type='LineBasicMaterial';this.color=new Color(0xffffff);this.linewidth=1;this.linecap='round';this.linejoin='round';this.morphTargets=false;this.setValues(parameters);}LineBasicMaterial.prototype=Object.create(Material.prototype);LineBasicMaterial.prototype.constructor=LineBasicMaterial;LineBasicMaterial.prototype.isLineBasicMaterial=true;LineBasicMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.linewidth=source.linewidth;this.linecap=source.linecap;this.linejoin=source.linejoin;this.morphTargets=source.morphTargets;return this;};var _start=new Vector3();var _end=new Vector3();var _inverseMatrix$1=new Matrix4();var _ray$1=new Ray();var _sphere$2=new Sphere();function Line(){var geometry=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new LineBasicMaterial();Object3D.call(this);this.type='Line';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Line.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Line,isLine:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry
  3611. if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[0];for(var _i148=1,l=positionAttribute.count;_i148<l;_i148++){_start.fromBufferAttribute(positionAttribute,_i148-1);_end.fromBufferAttribute(positionAttribute,_i148);lineDistances[_i148]=lineDistances[_i148-1];lineDistances[_i148]+=_start.distanceTo(_end);}geometry.setAttribute('lineDistance',new Float32BufferAttribute(lineDistances,1));}else {console.warn('THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');}}else if(geometry.isGeometry){var vertices=geometry.vertices;var _lineDistances=geometry.lineDistances;_lineDistances[0]=0;for(var _i149=1,_l6=vertices.length;_i149<_l6;_i149++){_lineDistances[_i149]=_lineDistances[_i149-1];_lineDistances[_i149]+=vertices[_i149-1].distanceTo(vertices[_i149]);}}return this;},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Line.threshold;// Checking boundingSphere distance to ray
  3612. if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$2.copy(geometry.boundingSphere);_sphere$2.applyMatrix4(matrixWorld);_sphere$2.radius+=threshold;if(raycaster.ray.intersectsSphere(_sphere$2)===false)return;//
  3613. _inverseMatrix$1.copy(matrixWorld).invert();_ray$1.copy(raycaster.ray).applyMatrix4(_inverseMatrix$1);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;var vStart=new Vector3();var vEnd=new Vector3();var interSegment=new Vector3();var interRay=new Vector3();var step=this.isLineSegments?2:1;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positionAttribute=attributes.position;if(index!==null){var indices=index.array;for(var _i150=0,l=indices.length-1;_i150<l;_i150+=step){var a=indices[_i150];var b=indices[_i150+1];vStart.fromBufferAttribute(positionAttribute,a);vEnd.fromBufferAttribute(positionAttribute,b);var distSq=_ray$1.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(distSq>localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation
  3614. var distance=raycaster.ray.origin.distanceTo(interRay);if(distance<raycaster.near||distance>raycaster.far)continue;intersects.push({distance:distance,// What do we want? intersection point on the ray or on the segment??
  3615. // point: raycaster.ray.at( distance ),
  3616. point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i150,face:null,faceIndex:null,object:this});}}else {for(var _i151=0,_l7=positionAttribute.count-1;_i151<_l7;_i151+=step){vStart.fromBufferAttribute(positionAttribute,_i151);vEnd.fromBufferAttribute(positionAttribute,_i151+1);var _distSq=_ray$1.distanceSqToSegment(vStart,vEnd,interRay,interSegment);if(_distSq>localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation
  3617. var _distance=raycaster.ray.origin.distanceTo(interRay);if(_distance<raycaster.near||_distance>raycaster.far)continue;intersects.push({distance:_distance,// What do we want? intersection point on the ray or on the segment??
  3618. // point: raycaster.ray.at( distance ),
  3619. point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i151,face:null,faceIndex:null,object:this});}}}else if(geometry.isGeometry){var vertices=geometry.vertices;var nbVertices=vertices.length;for(var _i152=0;_i152<nbVertices-1;_i152+=step){var _distSq2=_ray$1.distanceSqToSegment(vertices[_i152],vertices[_i152+1],interRay,interSegment);if(_distSq2>localThresholdSq)continue;interRay.applyMatrix4(this.matrixWorld);//Move back to world space for distance calculation
  3620. var _distance2=raycaster.ray.origin.distanceTo(interRay);if(_distance2<raycaster.near||_distance2>raycaster.far)continue;intersects.push({distance:_distance2,// What do we want? intersection point on the ray or on the segment??
  3621. // point: raycaster.ray.at( distance ),
  3622. point:interSegment.clone().applyMatrix4(this.matrixWorld),index:_i152,face:null,faceIndex:null,object:this});}}},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m<ml;m++){var name=morphAttribute[m].name||String(m);this.morphTargetInfluences.push(0);this.morphTargetDictionary[name]=m;}}}}else {var morphTargets=geometry.morphTargets;if(morphTargets!==undefined&&morphTargets.length>0){console.error('THREE.Line.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});var _start$1=new Vector3();var _end$1=new Vector3();function LineSegments(geometry,material){Line.call(this,geometry,material);this.type='LineSegments';}LineSegments.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineSegments,isLineSegments:true,computeLineDistances:function computeLineDistances(){var geometry=this.geometry;if(geometry.isBufferGeometry){// we assume non-indexed geometry
  3623. if(geometry.index===null){var positionAttribute=geometry.attributes.position;var lineDistances=[];for(var _i153=0,l=positionAttribute.count;_i153<l;_i153+=2){_start$1.fromBufferAttribute(positionAttribute,_i153);_end$1.fromBufferAttribute(positionAttribute,_i153+1);lineDistances[_i153]=_i153===0?0:lineDistances[_i153-1];lineDistances[_i153+1]=lineDistances[_i153]+_start$1.distanceTo(_end$1);}geometry.setAttribute('lineDistance',new Float32BufferAttribute(lineDistances,1));}else {console.warn('THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.');}}else if(geometry.isGeometry){var vertices=geometry.vertices;var _lineDistances2=geometry.lineDistances;for(var _i154=0,_l8=vertices.length;_i154<_l8;_i154+=2){_start$1.copy(vertices[_i154]);_end$1.copy(vertices[_i154+1]);_lineDistances2[_i154]=_i154===0?0:_lineDistances2[_i154-1];_lineDistances2[_i154+1]=_lineDistances2[_i154]+_start$1.distanceTo(_end$1);}}return this;}});function LineLoop(geometry,material){Line.call(this,geometry,material);this.type='LineLoop';}LineLoop.prototype=Object.assign(Object.create(Line.prototype),{constructor:LineLoop,isLineLoop:true});/**
  3624. * parameters = {
  3625. * color: <hex>,
  3626. * opacity: <float>,
  3627. * map: new THREE.Texture( <Image> ),
  3628. * alphaMap: new THREE.Texture( <Image> ),
  3629. *
  3630. * size: <float>,
  3631. * sizeAttenuation: <bool>
  3632. *
  3633. * morphTargets: <bool>
  3634. * }
  3635. */function PointsMaterial(parameters){Material.call(this);this.type='PointsMaterial';this.color=new Color(0xffffff);this.map=null;this.alphaMap=null;this.size=1;this.sizeAttenuation=true;this.morphTargets=false;this.setValues(parameters);}PointsMaterial.prototype=Object.create(Material.prototype);PointsMaterial.prototype.constructor=PointsMaterial;PointsMaterial.prototype.isPointsMaterial=true;PointsMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.alphaMap=source.alphaMap;this.size=source.size;this.sizeAttenuation=source.sizeAttenuation;this.morphTargets=source.morphTargets;return this;};var _inverseMatrix$2=new Matrix4();var _ray$2=new Ray();var _sphere$3=new Sphere();var _position$1=new Vector3();function Points(){var geometry=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BufferGeometry();var material=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new PointsMaterial();Object3D.call(this);this.type='Points';this.geometry=geometry;this.material=material;this.updateMorphTargets();}Points.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Points,isPoints:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.material=source.material;this.geometry=source.geometry;return this;},raycast:function raycast(raycaster,intersects){var geometry=this.geometry;var matrixWorld=this.matrixWorld;var threshold=raycaster.params.Points.threshold;// Checking boundingSphere distance to ray
  3636. if(geometry.boundingSphere===null)geometry.computeBoundingSphere();_sphere$3.copy(geometry.boundingSphere);_sphere$3.applyMatrix4(matrixWorld);_sphere$3.radius+=threshold;if(raycaster.ray.intersectsSphere(_sphere$3)===false)return;//
  3637. _inverseMatrix$2.copy(matrixWorld).invert();_ray$2.copy(raycaster.ray).applyMatrix4(_inverseMatrix$2);var localThreshold=threshold/((this.scale.x+this.scale.y+this.scale.z)/3);var localThresholdSq=localThreshold*localThreshold;if(geometry.isBufferGeometry){var index=geometry.index;var attributes=geometry.attributes;var positionAttribute=attributes.position;if(index!==null){var indices=index.array;for(var _i155=0,il=indices.length;_i155<il;_i155++){var a=indices[_i155];_position$1.fromBufferAttribute(positionAttribute,a);testPoint(_position$1,a,localThresholdSq,matrixWorld,raycaster,intersects,this);}}else {for(var _i156=0,l=positionAttribute.count;_i156<l;_i156++){_position$1.fromBufferAttribute(positionAttribute,_i156);testPoint(_position$1,_i156,localThresholdSq,matrixWorld,raycaster,intersects,this);}}}else {var vertices=geometry.vertices;for(var _i157=0,_l9=vertices.length;_i157<_l9;_i157++){testPoint(vertices[_i157],_i157,localThresholdSq,matrixWorld,raycaster,intersects,this);}}},updateMorphTargets:function updateMorphTargets(){var geometry=this.geometry;if(geometry.isBufferGeometry){var morphAttributes=geometry.morphAttributes;var keys=Object.keys(morphAttributes);if(keys.length>0){var morphAttribute=morphAttributes[keys[0]];if(morphAttribute!==undefined){this.morphTargetInfluences=[];this.morphTargetDictionary={};for(var m=0,ml=morphAttribute.length;m<ml;m++){var name=morphAttribute[m].name||String(m);this.morphTargetInfluences.push(0);this.morphTargetDictionary[name]=m;}}}}else {var morphTargets=geometry.morphTargets;if(morphTargets!==undefined&&morphTargets.length>0){console.error('THREE.Points.updateMorphTargets() does not support THREE.Geometry. Use THREE.BufferGeometry instead.');}}}});function testPoint(point,index,localThresholdSq,matrixWorld,raycaster,intersects,object){var rayPointDistanceSq=_ray$2.distanceSqToPoint(point);if(rayPointDistanceSq<localThresholdSq){var intersectPoint=new Vector3();_ray$2.closestPointToPoint(point,intersectPoint);intersectPoint.applyMatrix4(matrixWorld);var distance=raycaster.ray.origin.distanceTo(intersectPoint);if(distance<raycaster.near||distance>raycaster.far)return;intersects.push({distance:distance,distanceToRay:Math.sqrt(rayPointDistanceSq),point:intersectPoint,index:index,face:null,object:object});}}function VideoTexture(video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,video,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.format=format!==undefined?format:RGBFormat;this.minFilter=minFilter!==undefined?minFilter:LinearFilter;this.magFilter=magFilter!==undefined?magFilter:LinearFilter;this.generateMipmaps=false;var scope=this;function updateVideo(){scope.needsUpdate=true;video.requestVideoFrameCallback(updateVideo);}if('requestVideoFrameCallback'in video){video.requestVideoFrameCallback(updateVideo);}}VideoTexture.prototype=Object.assign(Object.create(Texture.prototype),{constructor:VideoTexture,clone:function clone(){return new this.constructor(this.image).copy(this);},isVideoTexture:true,update:function update(){var video=this.image;var hasVideoFrameCallback='requestVideoFrameCallback'in video;if(hasVideoFrameCallback===false&&video.readyState>=video.HAVE_CURRENT_DATA){this.needsUpdate=true;}}});function CompressedTexture(mipmaps,width,height,format,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,encoding){Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy,encoding);this.image={width:width,height:height};this.mipmaps=mipmaps;// no flipping for cube textures
  3638. // (also flipping doesn't work for compressed textures )
  3639. this.flipY=false;// can't generate mipmaps for compressed textures
  3640. // mips must be embedded in DDS files
  3641. this.generateMipmaps=false;}CompressedTexture.prototype=Object.create(Texture.prototype);CompressedTexture.prototype.constructor=CompressedTexture;CompressedTexture.prototype.isCompressedTexture=true;function CanvasTexture(canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy){Texture.call(this,canvas,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.needsUpdate=true;}CanvasTexture.prototype=Object.create(Texture.prototype);CanvasTexture.prototype.constructor=CanvasTexture;CanvasTexture.prototype.isCanvasTexture=true;function DepthTexture(width,height,type,mapping,wrapS,wrapT,magFilter,minFilter,anisotropy,format){format=format!==undefined?format:DepthFormat;if(format!==DepthFormat&&format!==DepthStencilFormat){throw new Error('DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat');}if(type===undefined&&format===DepthFormat)type=UnsignedShortType;if(type===undefined&&format===DepthStencilFormat)type=UnsignedInt248Type$1;Texture.call(this,null,mapping,wrapS,wrapT,magFilter,minFilter,format,type,anisotropy);this.image={width:width,height:height};this.magFilter=magFilter!==undefined?magFilter:NearestFilter;this.minFilter=minFilter!==undefined?minFilter:NearestFilter;this.flipY=false;this.generateMipmaps=false;}DepthTexture.prototype=Object.create(Texture.prototype);DepthTexture.prototype.constructor=DepthTexture;DepthTexture.prototype.isDepthTexture=true;var _geometryId=0;// Geometry uses even numbers as Id
  3642. var _m1$3=new Matrix4();var _obj$1=new Object3D();var _offset$1=new Vector3();function Geometry(){Object.defineProperty(this,'id',{value:_geometryId+=2});this.uuid=MathUtils.generateUUID();this.name='';this.type='Geometry';this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;// update flags
  3643. this.elementsNeedUpdate=false;this.verticesNeedUpdate=false;this.uvsNeedUpdate=false;this.normalsNeedUpdate=false;this.colorsNeedUpdate=false;this.lineDistancesNeedUpdate=false;this.groupsNeedUpdate=false;}Geometry.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:Geometry,isGeometry:true,applyMatrix4:function applyMatrix4(matrix){var normalMatrix=new Matrix3().getNormalMatrix(matrix);for(var _i158=0,il=this.vertices.length;_i158<il;_i158++){var vertex=this.vertices[_i158];vertex.applyMatrix4(matrix);}for(var _i159=0,_il12=this.faces.length;_i159<_il12;_i159++){var face=this.faces[_i159];face.normal.applyMatrix3(normalMatrix).normalize();for(var j=0,jl=face.vertexNormals.length;j<jl;j++){face.vertexNormals[j].applyMatrix3(normalMatrix).normalize();}}if(this.boundingBox!==null){this.computeBoundingBox();}if(this.boundingSphere!==null){this.computeBoundingSphere();}this.verticesNeedUpdate=true;this.normalsNeedUpdate=true;return this;},rotateX:function rotateX(angle){// rotate geometry around world x-axis
  3644. _m1$3.makeRotationX(angle);this.applyMatrix4(_m1$3);return this;},rotateY:function rotateY(angle){// rotate geometry around world y-axis
  3645. _m1$3.makeRotationY(angle);this.applyMatrix4(_m1$3);return this;},rotateZ:function rotateZ(angle){// rotate geometry around world z-axis
  3646. _m1$3.makeRotationZ(angle);this.applyMatrix4(_m1$3);return this;},translate:function translate(x,y,z){// translate geometry
  3647. _m1$3.makeTranslation(x,y,z);this.applyMatrix4(_m1$3);return this;},scale:function scale(x,y,z){// scale geometry
  3648. _m1$3.makeScale(x,y,z);this.applyMatrix4(_m1$3);return this;},lookAt:function lookAt(vector){_obj$1.lookAt(vector);_obj$1.updateMatrix();this.applyMatrix4(_obj$1.matrix);return this;},fromBufferGeometry:function fromBufferGeometry(geometry){var scope=this;var index=geometry.index!==null?geometry.index:undefined;var attributes=geometry.attributes;if(attributes.position===undefined){console.error('THREE.Geometry.fromBufferGeometry(): Position attribute required for conversion.');return this;}var position=attributes.position;var normal=attributes.normal;var color=attributes.color;var uv=attributes.uv;var uv2=attributes.uv2;if(uv2!==undefined)this.faceVertexUvs[1]=[];for(var _i160=0;_i160<position.count;_i160++){scope.vertices.push(new Vector3().fromBufferAttribute(position,_i160));if(color!==undefined){scope.colors.push(new Color().fromBufferAttribute(color,_i160));}}function addFace(a,b,c,materialIndex){var vertexColors=color===undefined?[]:[scope.colors[a].clone(),scope.colors[b].clone(),scope.colors[c].clone()];var vertexNormals=normal===undefined?[]:[new Vector3().fromBufferAttribute(normal,a),new Vector3().fromBufferAttribute(normal,b),new Vector3().fromBufferAttribute(normal,c)];var face=new Face3(a,b,c,vertexNormals,vertexColors,materialIndex);scope.faces.push(face);if(uv!==undefined){scope.faceVertexUvs[0].push([new Vector2().fromBufferAttribute(uv,a),new Vector2().fromBufferAttribute(uv,b),new Vector2().fromBufferAttribute(uv,c)]);}if(uv2!==undefined){scope.faceVertexUvs[1].push([new Vector2().fromBufferAttribute(uv2,a),new Vector2().fromBufferAttribute(uv2,b),new Vector2().fromBufferAttribute(uv2,c)]);}}var groups=geometry.groups;if(groups.length>0){for(var _i161=0;_i161<groups.length;_i161++){var group=groups[_i161];var start=group.start;var count=group.count;for(var j=start,jl=start+count;j<jl;j+=3){if(index!==undefined){addFace(index.getX(j),index.getX(j+1),index.getX(j+2),group.materialIndex);}else {addFace(j,j+1,j+2,group.materialIndex);}}}}else {if(index!==undefined){for(var _i162=0;_i162<index.count;_i162+=3){addFace(index.getX(_i162),index.getX(_i162+1),index.getX(_i162+2));}}else {for(var _i163=0;_i163<position.count;_i163+=3){addFace(_i163,_i163+1,_i163+2);}}}this.computeFaceNormals();if(geometry.boundingBox!==null){this.boundingBox=geometry.boundingBox.clone();}if(geometry.boundingSphere!==null){this.boundingSphere=geometry.boundingSphere.clone();}return this;},center:function center(){this.computeBoundingBox();this.boundingBox.getCenter(_offset$1).negate();this.translate(_offset$1.x,_offset$1.y,_offset$1.z);return this;},normalize:function normalize(){this.computeBoundingSphere();var center=this.boundingSphere.center;var radius=this.boundingSphere.radius;var s=radius===0?1:1.0/radius;var matrix=new Matrix4();matrix.set(s,0,0,-s*center.x,0,s,0,-s*center.y,0,0,s,-s*center.z,0,0,0,1);this.applyMatrix4(matrix);return this;},computeFaceNormals:function computeFaceNormals(){var cb=new Vector3(),ab=new Vector3();for(var f=0,fl=this.faces.length;f<fl;f++){var face=this.faces[f];var vA=this.vertices[face.a];var vB=this.vertices[face.b];var vC=this.vertices[face.c];cb.subVectors(vC,vB);ab.subVectors(vA,vB);cb.cross(ab);cb.normalize();face.normal.copy(cb);}},computeVertexNormals:function computeVertexNormals(){var areaWeighted=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var vertices=new Array(this.vertices.length);for(var v=0,vl=this.vertices.length;v<vl;v++){vertices[v]=new Vector3();}if(areaWeighted){// vertex normals weighted by triangle areas
  3649. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3650. var cb=new Vector3(),ab=new Vector3();for(var f=0,fl=this.faces.length;f<fl;f++){var face=this.faces[f];var vA=this.vertices[face.a];var vB=this.vertices[face.b];var vC=this.vertices[face.c];cb.subVectors(vC,vB);ab.subVectors(vA,vB);cb.cross(ab);vertices[face.a].add(cb);vertices[face.b].add(cb);vertices[face.c].add(cb);}}else {this.computeFaceNormals();for(var _f=0,_fl=this.faces.length;_f<_fl;_f++){var _face=this.faces[_f];vertices[_face.a].add(_face.normal);vertices[_face.b].add(_face.normal);vertices[_face.c].add(_face.normal);}}for(var _v=0,_vl=this.vertices.length;_v<_vl;_v++){vertices[_v].normalize();}for(var _f3=0,_fl2=this.faces.length;_f3<_fl2;_f3++){var _face2=this.faces[_f3];var vertexNormals=_face2.vertexNormals;if(vertexNormals.length===3){vertexNormals[0].copy(vertices[_face2.a]);vertexNormals[1].copy(vertices[_face2.b]);vertexNormals[2].copy(vertices[_face2.c]);}else {vertexNormals[0]=vertices[_face2.a].clone();vertexNormals[1]=vertices[_face2.b].clone();vertexNormals[2]=vertices[_face2.c].clone();}}if(this.faces.length>0){this.normalsNeedUpdate=true;}},computeFlatVertexNormals:function computeFlatVertexNormals(){this.computeFaceNormals();for(var f=0,fl=this.faces.length;f<fl;f++){var face=this.faces[f];var vertexNormals=face.vertexNormals;if(vertexNormals.length===3){vertexNormals[0].copy(face.normal);vertexNormals[1].copy(face.normal);vertexNormals[2].copy(face.normal);}else {vertexNormals[0]=face.normal.clone();vertexNormals[1]=face.normal.clone();vertexNormals[2]=face.normal.clone();}}if(this.faces.length>0){this.normalsNeedUpdate=true;}},computeMorphNormals:function computeMorphNormals(){// save original normals
  3651. // - create temp variables on first access
  3652. // otherwise just copy (for faster repeated calls)
  3653. for(var f=0,fl=this.faces.length;f<fl;f++){var face=this.faces[f];if(!face.__originalFaceNormal){face.__originalFaceNormal=face.normal.clone();}else {face.__originalFaceNormal.copy(face.normal);}if(!face.__originalVertexNormals)face.__originalVertexNormals=[];for(var _i164=0,il=face.vertexNormals.length;_i164<il;_i164++){if(!face.__originalVertexNormals[_i164]){face.__originalVertexNormals[_i164]=face.vertexNormals[_i164].clone();}else {face.__originalVertexNormals[_i164].copy(face.vertexNormals[_i164]);}}}// use temp geometry to compute face and vertex normals for each morph
  3654. var tmpGeo=new Geometry();tmpGeo.faces=this.faces;for(var _i165=0,_il13=this.morphTargets.length;_i165<_il13;_i165++){// create on first access
  3655. if(!this.morphNormals[_i165]){this.morphNormals[_i165]={};this.morphNormals[_i165].faceNormals=[];this.morphNormals[_i165].vertexNormals=[];var dstNormalsFace=this.morphNormals[_i165].faceNormals;var dstNormalsVertex=this.morphNormals[_i165].vertexNormals;for(var _f4=0,_fl3=this.faces.length;_f4<_fl3;_f4++){var faceNormal=new Vector3();var vertexNormals={a:new Vector3(),b:new Vector3(),c:new Vector3()};dstNormalsFace.push(faceNormal);dstNormalsVertex.push(vertexNormals);}}var morphNormals=this.morphNormals[_i165];// set vertices to morph target
  3656. tmpGeo.vertices=this.morphTargets[_i165].vertices;// compute morph normals
  3657. tmpGeo.computeFaceNormals();tmpGeo.computeVertexNormals();// store morph normals
  3658. for(var _f5=0,_fl4=this.faces.length;_f5<_fl4;_f5++){var _face3=this.faces[_f5];var _faceNormal=morphNormals.faceNormals[_f5];var _vertexNormals=morphNormals.vertexNormals[_f5];_faceNormal.copy(_face3.normal);_vertexNormals.a.copy(_face3.vertexNormals[0]);_vertexNormals.b.copy(_face3.vertexNormals[1]);_vertexNormals.c.copy(_face3.vertexNormals[2]);}}// restore original normals
  3659. for(var _f6=0,_fl5=this.faces.length;_f6<_fl5;_f6++){var _face4=this.faces[_f6];_face4.normal=_face4.__originalFaceNormal;_face4.vertexNormals=_face4.__originalVertexNormals;}},computeBoundingBox:function computeBoundingBox(){if(this.boundingBox===null){this.boundingBox=new Box3();}this.boundingBox.setFromPoints(this.vertices);},computeBoundingSphere:function computeBoundingSphere(){if(this.boundingSphere===null){this.boundingSphere=new Sphere();}this.boundingSphere.setFromPoints(this.vertices);},merge:function merge(geometry,matrix){var materialIndexOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;if(!(geometry&&geometry.isGeometry)){console.error('THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.',geometry);return;}var normalMatrix;var vertexOffset=this.vertices.length,vertices1=this.vertices,vertices2=geometry.vertices,faces1=this.faces,faces2=geometry.faces,colors1=this.colors,colors2=geometry.colors;if(matrix!==undefined){normalMatrix=new Matrix3().getNormalMatrix(matrix);}// vertices
  3660. for(var _i166=0,il=vertices2.length;_i166<il;_i166++){var vertex=vertices2[_i166];var vertexCopy=vertex.clone();if(matrix!==undefined)vertexCopy.applyMatrix4(matrix);vertices1.push(vertexCopy);}// colors
  3661. for(var _i167=0,_il14=colors2.length;_i167<_il14;_i167++){colors1.push(colors2[_i167].clone());}// faces
  3662. for(var _i168=0,_il15=faces2.length;_i168<_il15;_i168++){var face=faces2[_i168];var normal=void 0,color=void 0;var faceVertexNormals=face.vertexNormals,faceVertexColors=face.vertexColors;var faceCopy=new Face3(face.a+vertexOffset,face.b+vertexOffset,face.c+vertexOffset);faceCopy.normal.copy(face.normal);if(normalMatrix!==undefined){faceCopy.normal.applyMatrix3(normalMatrix).normalize();}for(var j=0,jl=faceVertexNormals.length;j<jl;j++){normal=faceVertexNormals[j].clone();if(normalMatrix!==undefined){normal.applyMatrix3(normalMatrix).normalize();}faceCopy.vertexNormals.push(normal);}faceCopy.color.copy(face.color);for(var _j5=0,_jl2=faceVertexColors.length;_j5<_jl2;_j5++){color=faceVertexColors[_j5];faceCopy.vertexColors.push(color.clone());}faceCopy.materialIndex=face.materialIndex+materialIndexOffset;faces1.push(faceCopy);}// uvs
  3663. for(var _i169=0,_il16=geometry.faceVertexUvs.length;_i169<_il16;_i169++){var faceVertexUvs2=geometry.faceVertexUvs[_i169];if(this.faceVertexUvs[_i169]===undefined)this.faceVertexUvs[_i169]=[];for(var _j6=0,_jl3=faceVertexUvs2.length;_j6<_jl3;_j6++){var uvs2=faceVertexUvs2[_j6],uvsCopy=[];for(var k=0,kl=uvs2.length;k<kl;k++){uvsCopy.push(uvs2[k].clone());}this.faceVertexUvs[_i169].push(uvsCopy);}}},mergeMesh:function mergeMesh(mesh){if(!(mesh&&mesh.isMesh)){console.error('THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.',mesh);return;}if(mesh.matrixAutoUpdate)mesh.updateMatrix();this.merge(mesh.geometry,mesh.matrix);},/*
  3664. * Checks for duplicate vertices with hashmap.
  3665. * Duplicated vertices are removed
  3666. * and faces' vertices are updated.
  3667. */mergeVertices:function mergeVertices(){var precisionPoints=arguments.length>0&&arguments[0]!==undefined?arguments[0]:4;var verticesMap={};// Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  3668. var unique=[],changes=[];var precision=Math.pow(10,precisionPoints);for(var _i170=0,il=this.vertices.length;_i170<il;_i170++){var v=this.vertices[_i170];var key=Math.round(v.x*precision)+'_'+Math.round(v.y*precision)+'_'+Math.round(v.z*precision);if(verticesMap[key]===undefined){verticesMap[key]=_i170;unique.push(this.vertices[_i170]);changes[_i170]=unique.length-1;}else {//console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3669. changes[_i170]=changes[verticesMap[key]];}}// if faces are completely degenerate after merging vertices, we
  3670. // have to remove them from the geometry.
  3671. var faceIndicesToRemove=[];for(var _i171=0,_il17=this.faces.length;_i171<_il17;_i171++){var face=this.faces[_i171];face.a=changes[face.a];face.b=changes[face.b];face.c=changes[face.c];var indices=[face.a,face.b,face.c];// if any duplicate vertices are found in a Face3
  3672. // we have to remove the face as nothing can be saved
  3673. for(var n=0;n<3;n++){if(indices[n]===indices[(n+1)%3]){faceIndicesToRemove.push(_i171);break;}}}for(var _i172=faceIndicesToRemove.length-1;_i172>=0;_i172--){var idx=faceIndicesToRemove[_i172];this.faces.splice(idx,1);for(var j=0,jl=this.faceVertexUvs.length;j<jl;j++){this.faceVertexUvs[j].splice(idx,1);}}// Use unique set of vertices
  3674. var diff=this.vertices.length-unique.length;this.vertices=unique;return diff;},setFromPoints:function setFromPoints(points){this.vertices=[];for(var _i173=0,l=points.length;_i173<l;_i173++){var point=points[_i173];this.vertices.push(new Vector3(point.x,point.y,point.z||0));}return this;},sortFacesByMaterialIndex:function sortFacesByMaterialIndex(){var faces=this.faces;var length=faces.length;// tag faces
  3675. for(var _i174=0;_i174<length;_i174++){faces[_i174]._id=_i174;}// sort faces
  3676. function materialIndexSort(a,b){return a.materialIndex-b.materialIndex;}faces.sort(materialIndexSort);// sort uvs
  3677. var uvs1=this.faceVertexUvs[0];var uvs2=this.faceVertexUvs[1];var newUvs1,newUvs2;if(uvs1&&uvs1.length===length)newUvs1=[];if(uvs2&&uvs2.length===length)newUvs2=[];for(var _i175=0;_i175<length;_i175++){var id=faces[_i175]._id;if(newUvs1)newUvs1.push(uvs1[id]);if(newUvs2)newUvs2.push(uvs2[id]);}if(newUvs1)this.faceVertexUvs[0]=newUvs1;if(newUvs2)this.faceVertexUvs[1]=newUvs2;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Geometry',generator:'Geometry.toJSON'}};// standard Geometry serialization
  3678. data.uuid=this.uuid;data.type=this.type;if(this.name!=='')data.name=this.name;if(this.parameters!==undefined){var parameters=this.parameters;for(var key in parameters){if(parameters[key]!==undefined)data[key]=parameters[key];}return data;}var vertices=[];for(var _i176=0;_i176<this.vertices.length;_i176++){var vertex=this.vertices[_i176];vertices.push(vertex.x,vertex.y,vertex.z);}var faces=[];var normals=[];var normalsHash={};var colors=[];var colorsHash={};var uvs=[];var uvsHash={};for(var _i177=0;_i177<this.faces.length;_i177++){var face=this.faces[_i177];var hasMaterial=true;var hasFaceUv=false;// deprecated
  3679. var hasFaceVertexUv=this.faceVertexUvs[0][_i177]!==undefined;var hasFaceNormal=face.normal.length()>0;var hasFaceVertexNormal=face.vertexNormals.length>0;var hasFaceColor=face.color.r!==1||face.color.g!==1||face.color.b!==1;var hasFaceVertexColor=face.vertexColors.length>0;var faceType=0;faceType=setBit(faceType,0,0);// isQuad
  3680. faceType=setBit(faceType,1,hasMaterial);faceType=setBit(faceType,2,hasFaceUv);faceType=setBit(faceType,3,hasFaceVertexUv);faceType=setBit(faceType,4,hasFaceNormal);faceType=setBit(faceType,5,hasFaceVertexNormal);faceType=setBit(faceType,6,hasFaceColor);faceType=setBit(faceType,7,hasFaceVertexColor);faces.push(faceType);faces.push(face.a,face.b,face.c);faces.push(face.materialIndex);if(hasFaceVertexUv){var faceVertexUvs=this.faceVertexUvs[0][_i177];faces.push(getUvIndex(faceVertexUvs[0]),getUvIndex(faceVertexUvs[1]),getUvIndex(faceVertexUvs[2]));}if(hasFaceNormal){faces.push(getNormalIndex(face.normal));}if(hasFaceVertexNormal){var vertexNormals=face.vertexNormals;faces.push(getNormalIndex(vertexNormals[0]),getNormalIndex(vertexNormals[1]),getNormalIndex(vertexNormals[2]));}if(hasFaceColor){faces.push(getColorIndex(face.color));}if(hasFaceVertexColor){var vertexColors=face.vertexColors;faces.push(getColorIndex(vertexColors[0]),getColorIndex(vertexColors[1]),getColorIndex(vertexColors[2]));}}function setBit(value,position,enabled){return enabled?value|1<<position:value&~(1<<position);}function getNormalIndex(normal){var hash=normal.x.toString()+normal.y.toString()+normal.z.toString();if(normalsHash[hash]!==undefined){return normalsHash[hash];}normalsHash[hash]=normals.length/3;normals.push(normal.x,normal.y,normal.z);return normalsHash[hash];}function getColorIndex(color){var hash=color.r.toString()+color.g.toString()+color.b.toString();if(colorsHash[hash]!==undefined){return colorsHash[hash];}colorsHash[hash]=colors.length;colors.push(color.getHex());return colorsHash[hash];}function getUvIndex(uv){var hash=uv.x.toString()+uv.y.toString();if(uvsHash[hash]!==undefined){return uvsHash[hash];}uvsHash[hash]=uvs.length/2;uvs.push(uv.x,uv.y);return uvsHash[hash];}data.data={};data.data.vertices=vertices;data.data.normals=normals;if(colors.length>0)data.data.colors=colors;if(uvs.length>0)data.data.uvs=[uvs];// temporal backward compatibility
  3681. data.data.faces=faces;return data;},clone:function clone(){/*
  3682. // Handle primitives
  3683. const parameters = this.parameters;
  3684. if ( parameters !== undefined ) {
  3685. const values = [];
  3686. for ( const key in parameters ) {
  3687. values.push( parameters[ key ] );
  3688. }
  3689. const geometry = Object.create( this.constructor.prototype );
  3690. this.constructor.apply( geometry, values );
  3691. return geometry;
  3692. }
  3693. return new this.constructor().copy( this );
  3694. */return new Geometry().copy(this);},copy:function copy(source){// reset
  3695. this.vertices=[];this.colors=[];this.faces=[];this.faceVertexUvs=[[]];this.morphTargets=[];this.morphNormals=[];this.skinWeights=[];this.skinIndices=[];this.lineDistances=[];this.boundingBox=null;this.boundingSphere=null;// name
  3696. this.name=source.name;// vertices
  3697. var vertices=source.vertices;for(var _i178=0,il=vertices.length;_i178<il;_i178++){this.vertices.push(vertices[_i178].clone());}// colors
  3698. var colors=source.colors;for(var _i179=0,_il18=colors.length;_i179<_il18;_i179++){this.colors.push(colors[_i179].clone());}// faces
  3699. var faces=source.faces;for(var _i180=0,_il19=faces.length;_i180<_il19;_i180++){this.faces.push(faces[_i180].clone());}// face vertex uvs
  3700. for(var _i181=0,_il20=source.faceVertexUvs.length;_i181<_il20;_i181++){var faceVertexUvs=source.faceVertexUvs[_i181];if(this.faceVertexUvs[_i181]===undefined){this.faceVertexUvs[_i181]=[];}for(var j=0,jl=faceVertexUvs.length;j<jl;j++){var uvs=faceVertexUvs[j],uvsCopy=[];for(var k=0,kl=uvs.length;k<kl;k++){var uv=uvs[k];uvsCopy.push(uv.clone());}this.faceVertexUvs[_i181].push(uvsCopy);}}// morph targets
  3701. var morphTargets=source.morphTargets;for(var _i182=0,_il21=morphTargets.length;_i182<_il21;_i182++){var morphTarget={};morphTarget.name=morphTargets[_i182].name;// vertices
  3702. if(morphTargets[_i182].vertices!==undefined){morphTarget.vertices=[];for(var _j7=0,_jl4=morphTargets[_i182].vertices.length;_j7<_jl4;_j7++){morphTarget.vertices.push(morphTargets[_i182].vertices[_j7].clone());}}// normals
  3703. if(morphTargets[_i182].normals!==undefined){morphTarget.normals=[];for(var _j8=0,_jl5=morphTargets[_i182].normals.length;_j8<_jl5;_j8++){morphTarget.normals.push(morphTargets[_i182].normals[_j8].clone());}}this.morphTargets.push(morphTarget);}// morph normals
  3704. var morphNormals=source.morphNormals;for(var _i183=0,_il22=morphNormals.length;_i183<_il22;_i183++){var morphNormal={};// vertex normals
  3705. if(morphNormals[_i183].vertexNormals!==undefined){morphNormal.vertexNormals=[];for(var _j9=0,_jl6=morphNormals[_i183].vertexNormals.length;_j9<_jl6;_j9++){var srcVertexNormal=morphNormals[_i183].vertexNormals[_j9];var destVertexNormal={};destVertexNormal.a=srcVertexNormal.a.clone();destVertexNormal.b=srcVertexNormal.b.clone();destVertexNormal.c=srcVertexNormal.c.clone();morphNormal.vertexNormals.push(destVertexNormal);}}// face normals
  3706. if(morphNormals[_i183].faceNormals!==undefined){morphNormal.faceNormals=[];for(var _j10=0,_jl7=morphNormals[_i183].faceNormals.length;_j10<_jl7;_j10++){morphNormal.faceNormals.push(morphNormals[_i183].faceNormals[_j10].clone());}}this.morphNormals.push(morphNormal);}// skin weights
  3707. var skinWeights=source.skinWeights;for(var _i184=0,_il23=skinWeights.length;_i184<_il23;_i184++){this.skinWeights.push(skinWeights[_i184].clone());}// skin indices
  3708. var skinIndices=source.skinIndices;for(var _i185=0,_il24=skinIndices.length;_i185<_il24;_i185++){this.skinIndices.push(skinIndices[_i185].clone());}// line distances
  3709. var lineDistances=source.lineDistances;for(var _i186=0,_il25=lineDistances.length;_i186<_il25;_i186++){this.lineDistances.push(lineDistances[_i186]);}// bounding box
  3710. var boundingBox=source.boundingBox;if(boundingBox!==null){this.boundingBox=boundingBox.clone();}// bounding sphere
  3711. var boundingSphere=source.boundingSphere;if(boundingSphere!==null){this.boundingSphere=boundingSphere.clone();}// update flags
  3712. this.elementsNeedUpdate=source.elementsNeedUpdate;this.verticesNeedUpdate=source.verticesNeedUpdate;this.uvsNeedUpdate=source.uvsNeedUpdate;this.normalsNeedUpdate=source.normalsNeedUpdate;this.colorsNeedUpdate=source.colorsNeedUpdate;this.lineDistancesNeedUpdate=source.lineDistancesNeedUpdate;this.groupsNeedUpdate=source.groupsNeedUpdate;return this;},dispose:function dispose(){this.dispatchEvent({type:'dispose'});}});class BoxGeometry extends Geometry{constructor(width,height,depth,widthSegments,heightSegments,depthSegments){super();this.type='BoxGeometry';this.parameters={width:width,height:height,depth:depth,widthSegments:widthSegments,heightSegments:heightSegments,depthSegments:depthSegments};this.fromBufferGeometry(new BoxBufferGeometry(width,height,depth,widthSegments,heightSegments,depthSegments));this.mergeVertices();}}class CircleBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var segments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var thetaStart=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var thetaLength=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Math.PI*2;super();this.type='CircleBufferGeometry';this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};segments=Math.max(3,segments);// buffers
  3713. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  3714. var vertex=new Vector3();var uv=new Vector2();// center point
  3715. vertices.push(0,0,0);normals.push(0,0,1);uvs.push(0.5,0.5);for(var s=0,_i187=3;s<=segments;s++,_i187+=3){var segment=thetaStart+s/segments*thetaLength;// vertex
  3716. vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);// normal
  3717. normals.push(0,0,1);// uvs
  3718. uv.x=(vertices[_i187]/radius+1)/2;uv.y=(vertices[_i187+1]/radius+1)/2;uvs.push(uv.x,uv.y);}// indices
  3719. for(var _i188=1;_i188<=segments;_i188++){indices.push(_i188,_i188+1,0);}// build geometry
  3720. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class CircleGeometry extends Geometry{constructor(radius,segments,thetaStart,thetaLength){super();this.type='CircleGeometry';this.parameters={radius:radius,segments:segments,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new CircleBufferGeometry(radius,segments,thetaStart,thetaLength));this.mergeVertices();}}class CylinderBufferGeometry extends BufferGeometry{constructor(){var radiusTop=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var radiusBottom=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var height=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var heightSegments=arguments.length>4&&arguments[4]!==undefined?arguments[4]:1;var openEnded=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;var thetaStart=arguments.length>6&&arguments[6]!==undefined?arguments[6]:0;var thetaLength=arguments.length>7&&arguments[7]!==undefined?arguments[7]:Math.PI*2;super();this.type='CylinderBufferGeometry';this.parameters={radiusTop:radiusTop,radiusBottom:radiusBottom,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};var scope=this;radialSegments=Math.floor(radialSegments);heightSegments=Math.floor(heightSegments);// buffers
  3721. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  3722. var index=0;var indexArray=[];var halfHeight=height/2;var groupStart=0;// generate geometry
  3723. generateTorso();if(openEnded===false){if(radiusTop>0)generateCap(true);if(radiusBottom>0)generateCap(false);}// build geometry
  3724. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));function generateTorso(){var normal=new Vector3();var vertex=new Vector3();var groupCount=0;// this will be used to calculate the normal
  3725. var slope=(radiusBottom-radiusTop)/height;// generate vertices, normals and uvs
  3726. for(var y=0;y<=heightSegments;y++){var indexRow=[];var v=y/heightSegments;// calculate the radius of the current row
  3727. var radius=v*(radiusBottom-radiusTop)+radiusTop;for(var x=0;x<=radialSegments;x++){var u=x/radialSegments;var theta=u*thetaLength+thetaStart;var sinTheta=Math.sin(theta);var cosTheta=Math.cos(theta);// vertex
  3728. vertex.x=radius*sinTheta;vertex.y=-v*height+halfHeight;vertex.z=radius*cosTheta;vertices.push(vertex.x,vertex.y,vertex.z);// normal
  3729. normal.set(sinTheta,slope,cosTheta).normalize();normals.push(normal.x,normal.y,normal.z);// uv
  3730. uvs.push(u,1-v);// save index of vertex in respective row
  3731. indexRow.push(index++);}// now save vertices of the row in our index array
  3732. indexArray.push(indexRow);}// generate indices
  3733. for(var _x2=0;_x2<radialSegments;_x2++){for(var _y2=0;_y2<heightSegments;_y2++){// we use the index array to access the correct indices
  3734. var a=indexArray[_y2][_x2];var b=indexArray[_y2+1][_x2];var c=indexArray[_y2+1][_x2+1];var d=indexArray[_y2][_x2+1];// faces
  3735. indices.push(a,b,d);indices.push(b,c,d);// update group counter
  3736. groupCount+=6;}}// add a group to the geometry. this will ensure multi material support
  3737. scope.addGroup(groupStart,groupCount,0);// calculate new start value for groups
  3738. groupStart+=groupCount;}function generateCap(top){// save the index of the first center vertex
  3739. var centerIndexStart=index;var uv=new Vector2();var vertex=new Vector3();var groupCount=0;var radius=top===true?radiusTop:radiusBottom;var sign=top===true?1:-1;// first we generate the center vertex data of the cap.
  3740. // because the geometry needs one set of uvs per face,
  3741. // we must generate a center vertex per face/segment
  3742. for(var x=1;x<=radialSegments;x++){// vertex
  3743. vertices.push(0,halfHeight*sign,0);// normal
  3744. normals.push(0,sign,0);// uv
  3745. uvs.push(0.5,0.5);// increase index
  3746. index++;}// save the index of the last center vertex
  3747. var centerIndexEnd=index;// now we generate the surrounding vertices, normals and uvs
  3748. for(var _x3=0;_x3<=radialSegments;_x3++){var u=_x3/radialSegments;var theta=u*thetaLength+thetaStart;var cosTheta=Math.cos(theta);var sinTheta=Math.sin(theta);// vertex
  3749. vertex.x=radius*sinTheta;vertex.y=halfHeight*sign;vertex.z=radius*cosTheta;vertices.push(vertex.x,vertex.y,vertex.z);// normal
  3750. normals.push(0,sign,0);// uv
  3751. uv.x=cosTheta*0.5+0.5;uv.y=sinTheta*0.5*sign+0.5;uvs.push(uv.x,uv.y);// increase index
  3752. index++;}// generate indices
  3753. for(var _x4=0;_x4<radialSegments;_x4++){var c=centerIndexStart+_x4;var _i189=centerIndexEnd+_x4;if(top===true){// face top
  3754. indices.push(_i189,_i189+1,c);}else {// face bottom
  3755. indices.push(_i189+1,_i189,c);}groupCount+=3;}// add a group to the geometry. this will ensure multi material support
  3756. scope.addGroup(groupStart,groupCount,top===true?1:2);// calculate new start value for groups
  3757. groupStart+=groupCount;}}}class CylinderGeometry extends Geometry{constructor(radiusTop,radiusBottom,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){super();this.type='CylinderGeometry';this.parameters={radiusTop:radiusTop,radiusBottom:radiusBottom,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new CylinderBufferGeometry(radiusTop,radiusBottom,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength));this.mergeVertices();}}class ConeGeometry extends CylinderGeometry{constructor(radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength){super(0,radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength);this.type='ConeGeometry';this.parameters={radius:radius,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};}}class ConeBufferGeometry extends CylinderBufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var height=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var radialSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var heightSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var openEnded=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;var thetaStart=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;var thetaLength=arguments.length>6&&arguments[6]!==undefined?arguments[6]:Math.PI*2;super(0,radius,height,radialSegments,heightSegments,openEnded,thetaStart,thetaLength);this.type='ConeBufferGeometry';this.parameters={radius:radius,height:height,radialSegments:radialSegments,heightSegments:heightSegments,openEnded:openEnded,thetaStart:thetaStart,thetaLength:thetaLength};}}class PolyhedronBufferGeometry extends BufferGeometry{constructor(vertices,indices){var radius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var detail=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;super();this.type='PolyhedronBufferGeometry';this.parameters={vertices:vertices,indices:indices,radius:radius,detail:detail};// default buffer data
  3758. var vertexBuffer=[];var uvBuffer=[];// the subdivision creates the vertex buffer data
  3759. subdivide(detail);// all vertices should lie on a conceptual sphere with a given radius
  3760. applyRadius(radius);// finally, create the uv data
  3761. generateUVs();// build non-indexed geometry
  3762. this.setAttribute('position',new Float32BufferAttribute(vertexBuffer,3));this.setAttribute('normal',new Float32BufferAttribute(vertexBuffer.slice(),3));this.setAttribute('uv',new Float32BufferAttribute(uvBuffer,2));if(detail===0){this.computeVertexNormals();// flat normals
  3763. }else {this.normalizeNormals();// smooth normals
  3764. }// helper functions
  3765. function subdivide(detail){var a=new Vector3();var b=new Vector3();var c=new Vector3();// iterate over all faces and apply a subdivison with the given detail value
  3766. for(var _i190=0;_i190<indices.length;_i190+=3){// get the vertices of the face
  3767. getVertexByIndex(indices[_i190+0],a);getVertexByIndex(indices[_i190+1],b);getVertexByIndex(indices[_i190+2],c);// perform subdivision
  3768. subdivideFace(a,b,c,detail);}}function subdivideFace(a,b,c,detail){var cols=detail+1;// we use this multidimensional array as a data structure for creating the subdivision
  3769. var v=[];// construct all of the vertices for this subdivision
  3770. for(var _i191=0;_i191<=cols;_i191++){v[_i191]=[];var aj=a.clone().lerp(c,_i191/cols);var bj=b.clone().lerp(c,_i191/cols);var rows=cols-_i191;for(var j=0;j<=rows;j++){if(j===0&&_i191===cols){v[_i191][j]=aj;}else {v[_i191][j]=aj.clone().lerp(bj,j/rows);}}}// construct all of the faces
  3771. for(var _i192=0;_i192<cols;_i192++){for(var _j11=0;_j11<2*(cols-_i192)-1;_j11++){var k=Math.floor(_j11/2);if(_j11%2===0){pushVertex(v[_i192][k+1]);pushVertex(v[_i192+1][k]);pushVertex(v[_i192][k]);}else {pushVertex(v[_i192][k+1]);pushVertex(v[_i192+1][k+1]);pushVertex(v[_i192+1][k]);}}}}function applyRadius(radius){var vertex=new Vector3();// iterate over the entire buffer and apply the radius to each vertex
  3772. for(var _i193=0;_i193<vertexBuffer.length;_i193+=3){vertex.x=vertexBuffer[_i193+0];vertex.y=vertexBuffer[_i193+1];vertex.z=vertexBuffer[_i193+2];vertex.normalize().multiplyScalar(radius);vertexBuffer[_i193+0]=vertex.x;vertexBuffer[_i193+1]=vertex.y;vertexBuffer[_i193+2]=vertex.z;}}function generateUVs(){var vertex=new Vector3();for(var _i194=0;_i194<vertexBuffer.length;_i194+=3){vertex.x=vertexBuffer[_i194+0];vertex.y=vertexBuffer[_i194+1];vertex.z=vertexBuffer[_i194+2];var u=azimuth(vertex)/2/Math.PI+0.5;var v=inclination(vertex)/Math.PI+0.5;uvBuffer.push(u,1-v);}correctUVs();correctSeam();}function correctSeam(){// handle case when face straddles the seam, see #3269
  3773. for(var _i195=0;_i195<uvBuffer.length;_i195+=6){// uv data of a single face
  3774. var x0=uvBuffer[_i195+0];var x1=uvBuffer[_i195+2];var x2=uvBuffer[_i195+4];var max=Math.max(x0,x1,x2);var min=Math.min(x0,x1,x2);// 0.9 is somewhat arbitrary
  3775. if(max>0.9&&min<0.1){if(x0<0.2)uvBuffer[_i195+0]+=1;if(x1<0.2)uvBuffer[_i195+2]+=1;if(x2<0.2)uvBuffer[_i195+4]+=1;}}}function pushVertex(vertex){vertexBuffer.push(vertex.x,vertex.y,vertex.z);}function getVertexByIndex(index,vertex){var stride=index*3;vertex.x=vertices[stride+0];vertex.y=vertices[stride+1];vertex.z=vertices[stride+2];}function correctUVs(){var a=new Vector3();var b=new Vector3();var c=new Vector3();var centroid=new Vector3();var uvA=new Vector2();var uvB=new Vector2();var uvC=new Vector2();for(var _i196=0,j=0;_i196<vertexBuffer.length;_i196+=9,j+=6){a.set(vertexBuffer[_i196+0],vertexBuffer[_i196+1],vertexBuffer[_i196+2]);b.set(vertexBuffer[_i196+3],vertexBuffer[_i196+4],vertexBuffer[_i196+5]);c.set(vertexBuffer[_i196+6],vertexBuffer[_i196+7],vertexBuffer[_i196+8]);uvA.set(uvBuffer[j+0],uvBuffer[j+1]);uvB.set(uvBuffer[j+2],uvBuffer[j+3]);uvC.set(uvBuffer[j+4],uvBuffer[j+5]);centroid.copy(a).add(b).add(c).divideScalar(3);var azi=azimuth(centroid);correctUV(uvA,j+0,a,azi);correctUV(uvB,j+2,b,azi);correctUV(uvC,j+4,c,azi);}}function correctUV(uv,stride,vector,azimuth){if(azimuth<0&&uv.x===1){uvBuffer[stride]=uv.x-1;}if(vector.x===0&&vector.z===0){uvBuffer[stride]=azimuth/2/Math.PI+0.5;}}// Angle around the Y axis, counter-clockwise when looking from above.
  3776. function azimuth(vector){return Math.atan2(vector.z,-vector.x);}// Angle above the XZ plane.
  3777. function inclination(vector){return Math.atan2(-vector.y,Math.sqrt(vector.x*vector.x+vector.z*vector.z));}}}class DodecahedronBufferGeometry extends PolyhedronBufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var t=(1+Math.sqrt(5))/2;var r=1/t;var vertices=[// (±1, ±1, ±1)
  3778. -1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,// (0, ±1/φ, ±φ)
  3779. 0,-r,-t,0,-r,t,0,r,-t,0,r,t,// (±1/φ, ±φ, 0)
  3780. -r,-t,0,-r,t,0,r,-t,0,r,t,0,// (±φ, 0, ±1/φ)
  3781. -t,0,-r,t,0,-r,-t,0,r,t,0,r];var indices=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(vertices,indices,radius,detail);this.type='DodecahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class DodecahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='DodecahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new DodecahedronBufferGeometry(radius,detail));this.mergeVertices();}}var _v0$2=new Vector3();var _v1$5=new Vector3();var _normal$1=new Vector3();var _triangle=new Triangle();class EdgesGeometry extends BufferGeometry{constructor(geometry,thresholdAngle){super();this.type='EdgesGeometry';this.parameters={thresholdAngle:thresholdAngle};thresholdAngle=thresholdAngle!==undefined?thresholdAngle:1;if(geometry.isGeometry){geometry=new BufferGeometry().fromGeometry(geometry);}var precisionPoints=4;var precision=Math.pow(10,precisionPoints);var thresholdDot=Math.cos(MathUtils.DEG2RAD*thresholdAngle);var indexAttr=geometry.getIndex();var positionAttr=geometry.getAttribute('position');var indexCount=indexAttr?indexAttr.count:positionAttr.count;var indexArr=[0,0,0];var vertKeys=['a','b','c'];var hashes=new Array(3);var edgeData={};var vertices=[];for(var _i197=0;_i197<indexCount;_i197+=3){if(indexAttr){indexArr[0]=indexAttr.getX(_i197);indexArr[1]=indexAttr.getX(_i197+1);indexArr[2]=indexAttr.getX(_i197+2);}else {indexArr[0]=_i197;indexArr[1]=_i197+1;indexArr[2]=_i197+2;}var{a,b,c}=_triangle;a.fromBufferAttribute(positionAttr,indexArr[0]);b.fromBufferAttribute(positionAttr,indexArr[1]);c.fromBufferAttribute(positionAttr,indexArr[2]);_triangle.getNormal(_normal$1);// create hashes for the edge from the vertices
  3782. hashes[0]="".concat(Math.round(a.x*precision),",").concat(Math.round(a.y*precision),",").concat(Math.round(a.z*precision));hashes[1]="".concat(Math.round(b.x*precision),",").concat(Math.round(b.y*precision),",").concat(Math.round(b.z*precision));hashes[2]="".concat(Math.round(c.x*precision),",").concat(Math.round(c.y*precision),",").concat(Math.round(c.z*precision));// skip degenerate triangles
  3783. if(hashes[0]===hashes[1]||hashes[1]===hashes[2]||hashes[2]===hashes[0]){continue;}// iterate over every edge
  3784. for(var j=0;j<3;j++){// get the first and next vertex making up the edge
  3785. var jNext=(j+1)%3;var vecHash0=hashes[j];var vecHash1=hashes[jNext];var v0=_triangle[vertKeys[j]];var v1=_triangle[vertKeys[jNext]];var hash="".concat(vecHash0,"_").concat(vecHash1);var reverseHash="".concat(vecHash1,"_").concat(vecHash0);if(reverseHash in edgeData&&edgeData[reverseHash]){// if we found a sibling edge add it into the vertex array if
  3786. // it meets the angle threshold and delete the edge from the map.
  3787. if(_normal$1.dot(edgeData[reverseHash].normal)<=thresholdDot){vertices.push(v0.x,v0.y,v0.z);vertices.push(v1.x,v1.y,v1.z);}edgeData[reverseHash]=null;}else if(!(hash in edgeData)){// if we've already got an edge here then skip adding a new one
  3788. edgeData[hash]={index0:indexArr[j],index1:indexArr[jNext],normal:_normal$1.clone()};}}}// iterate over all remaining, unmatched edges and add them to the vertex array
  3789. for(var key in edgeData){if(edgeData[key]){var{index0,index1}=edgeData[key];_v0$2.fromBufferAttribute(positionAttr,index0);_v1$5.fromBufferAttribute(positionAttr,index1);vertices.push(_v0$2.x,_v0$2.y,_v0$2.z);vertices.push(_v1$5.x,_v1$5.y,_v1$5.z);}}this.setAttribute('position',new Float32BufferAttribute(vertices,3));}}/**
  3790. * Port from https://github.com/mapbox/earcut (v2.2.2)
  3791. */var Earcut={triangulate:function triangulate(data,holeIndices,dim){dim=dim||2;var hasHoles=holeIndices&&holeIndices.length;var outerLen=hasHoles?holeIndices[0]*dim:data.length;var outerNode=linkedList(data,0,outerLen,dim,true);var triangles=[];if(!outerNode||outerNode.next===outerNode.prev)return triangles;var minX,minY,maxX,maxY,x,y,invSize;if(hasHoles)outerNode=eliminateHoles(data,holeIndices,outerNode,dim);// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  3792. if(data.length>80*dim){minX=maxX=data[0];minY=maxY=data[1];for(var _i198=dim;_i198<outerLen;_i198+=dim){x=data[_i198];y=data[_i198+1];if(x<minX)minX=x;if(y<minY)minY=y;if(x>maxX)maxX=x;if(y>maxY)maxY=y;}// minX, minY and invSize are later used to transform coords into integers for z-order calculation
  3793. invSize=Math.max(maxX-minX,maxY-minY);invSize=invSize!==0?1/invSize:0;}earcutLinked(outerNode,triangles,dim,minX,minY,invSize);return triangles;}};// create a circular doubly linked list from polygon points in the specified winding order
  3794. function linkedList(data,start,end,dim,clockwise){var i,last;if(clockwise===signedArea(data,start,end,dim)>0){for(i=start;i<end;i+=dim)last=insertNode(i,data[i],data[i+1],last);}else {for(i=end-dim;i>=start;i-=dim)last=insertNode(i,data[i],data[i+1],last);}if(last&&equals(last,last.next)){removeNode(last);last=last.next;}return last;}// eliminate colinear or duplicate points
  3795. function filterPoints(start,end){if(!start)return start;if(!end)end=start;var p=start,again;do{again=false;if(!p.steiner&&(equals(p,p.next)||area(p.prev,p,p.next)===0)){removeNode(p);p=end=p.prev;if(p===p.next)break;again=true;}else {p=p.next;}}while(again||p!==end);return end;}// main ear slicing loop which triangulates a polygon (given as a linked list)
  3796. function earcutLinked(ear,triangles,dim,minX,minY,invSize,pass){if(!ear)return;// interlink polygon nodes in z-order
  3797. if(!pass&&invSize)indexCurve(ear,minX,minY,invSize);var stop=ear,prev,next;// iterate through ears, slicing them one by one
  3798. while(ear.prev!==ear.next){prev=ear.prev;next=ear.next;if(invSize?isEarHashed(ear,minX,minY,invSize):isEar(ear)){// cut off the triangle
  3799. triangles.push(prev.i/dim);triangles.push(ear.i/dim);triangles.push(next.i/dim);removeNode(ear);// skipping the next vertex leads to less sliver triangles
  3800. ear=next.next;stop=next.next;continue;}ear=next;// if we looped through the whole remaining polygon and can't find any more ears
  3801. if(ear===stop){// try filtering points and slicing again
  3802. if(!pass){earcutLinked(filterPoints(ear),triangles,dim,minX,minY,invSize,1);// if this didn't work, try curing all small self-intersections locally
  3803. }else if(pass===1){ear=cureLocalIntersections(filterPoints(ear),triangles,dim);earcutLinked(ear,triangles,dim,minX,minY,invSize,2);// as a last resort, try splitting the remaining polygon into two
  3804. }else if(pass===2){splitEarcut(ear,triangles,dim,minX,minY,invSize);}break;}}}// check whether a polygon node forms a valid ear with adjacent nodes
  3805. function isEar(ear){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear
  3806. // now make sure we don't have other points inside the potential ear
  3807. var p=ear.next.next;while(p!==ear.prev){if(pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.next;}return true;}function isEarHashed(ear,minX,minY,invSize){var a=ear.prev,b=ear,c=ear.next;if(area(a,b,c)>=0)return false;// reflex, can't be an ear
  3808. // triangle bbox; min & max are calculated like this for speed
  3809. var minTX=a.x<b.x?a.x<c.x?a.x:c.x:b.x<c.x?b.x:c.x,minTY=a.y<b.y?a.y<c.y?a.y:c.y:b.y<c.y?b.y:c.y,maxTX=a.x>b.x?a.x>c.x?a.x:c.x:b.x>c.x?b.x:c.x,maxTY=a.y>b.y?a.y>c.y?a.y:c.y:b.y>c.y?b.y:c.y;// z-order range for the current triangle bbox;
  3810. var minZ=zOrder(minTX,minTY,minX,minY,invSize),maxZ=zOrder(maxTX,maxTY,minX,minY,invSize);var p=ear.prevZ,n=ear.nextZ;// look for points inside the triangle in both directions
  3811. while(p&&p.z>=minZ&&n&&n.z<=maxZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}// look for remaining points in decreasing z-order
  3812. while(p&&p.z>=minZ){if(p!==ear.prev&&p!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,p.x,p.y)&&area(p.prev,p,p.next)>=0)return false;p=p.prevZ;}// look for remaining points in increasing z-order
  3813. while(n&&n.z<=maxZ){if(n!==ear.prev&&n!==ear.next&&pointInTriangle(a.x,a.y,b.x,b.y,c.x,c.y,n.x,n.y)&&area(n.prev,n,n.next)>=0)return false;n=n.nextZ;}return true;}// go through all polygon nodes and cure small local self-intersections
  3814. function cureLocalIntersections(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next;if(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)){triangles.push(a.i/dim);triangles.push(p.i/dim);triangles.push(b.i/dim);// remove two nodes involved
  3815. removeNode(p);removeNode(p.next);p=start=b;}p=p.next;}while(p!==start);return filterPoints(p);}// try splitting polygon into two and triangulate them independently
  3816. function splitEarcut(start,triangles,dim,minX,minY,invSize){// look for a valid diagonal that divides the polygon into two
  3817. var a=start;do{var b=a.next.next;while(b!==a.prev){if(a.i!==b.i&&isValidDiagonal(a,b)){// split the polygon in two by the diagonal
  3818. var c=splitPolygon(a,b);// filter colinear points around the cuts
  3819. a=filterPoints(a,a.next);c=filterPoints(c,c.next);// run earcut on each half
  3820. earcutLinked(a,triangles,dim,minX,minY,invSize);earcutLinked(c,triangles,dim,minX,minY,invSize);return;}b=b.next;}a=a.next;}while(a!==start);}// link every hole into the outer loop, producing a single-ring polygon without holes
  3821. function eliminateHoles(data,holeIndices,outerNode,dim){var queue=[];var i,len,start,end,list;for(i=0,len=holeIndices.length;i<len;i++){start=holeIndices[i]*dim;end=i<len-1?holeIndices[i+1]*dim:data.length;list=linkedList(data,start,end,dim,false);if(list===list.next)list.steiner=true;queue.push(getLeftmost(list));}queue.sort(compareX);// process holes from left to right
  3822. for(i=0;i<queue.length;i++){eliminateHole(queue[i],outerNode);outerNode=filterPoints(outerNode,outerNode.next);}return outerNode;}function compareX(a,b){return a.x-b.x;}// find a bridge between vertices that connects hole with an outer ring and and link it
  3823. function eliminateHole(hole,outerNode){outerNode=findHoleBridge(hole,outerNode);if(outerNode){var b=splitPolygon(outerNode,hole);// filter collinear points around the cuts
  3824. filterPoints(outerNode,outerNode.next);filterPoints(b,b.next);}}// David Eberly's algorithm for finding a bridge between hole and outer polygon
  3825. function findHoleBridge(hole,outerNode){var p=outerNode;var hx=hole.x;var hy=hole.y;var qx=-Infinity,m;// find a segment intersected by a ray from the hole's leftmost point to the left;
  3826. // segment's endpoint with lesser x will be potential connection point
  3827. do{if(hy<=p.y&&hy>=p.next.y&&p.next.y!==p.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&x>qx){qx=x;if(x===hx){if(hy===p.y)return p;if(hy===p.next.y)return p.next;}m=p.x<p.next.x?p:p.next;}}p=p.next;}while(p!==outerNode);if(!m)return null;if(hx===qx)return m;// hole touches outer segment; pick leftmost endpoint
  3828. // look for points inside the triangle of hole point, segment intersection and endpoint;
  3829. // if there are no points found, we have a valid connection;
  3830. // otherwise choose the point of the minimum angle with the ray as connection point
  3831. var stop=m,mx=m.x,my=m.y;var tanMin=Infinity,tan;p=m;do{if(hx>=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle(hy<my?hx:qx,hy,mx,my,hy<my?qx:hx,hy,p.x,p.y)){tan=Math.abs(hy-p.y)/(hx-p.x);// tangential
  3832. if(locallyInside(p,hole)&&(tan<tanMin||tan===tanMin&&(p.x>m.x||p.x===m.x&&sectorContainsSector(m,p)))){m=p;tanMin=tan;}}p=p.next;}while(p!==stop);return m;}// whether sector in vertex m contains sector in vertex p in the same coordinates
  3833. function sectorContainsSector(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0;}// interlink polygon nodes in z-order
  3834. function indexCurve(start,minX,minY,invSize){var p=start;do{if(p.z===null)p.z=zOrder(p.x,p.y,minX,minY,invSize);p.prevZ=p.prev;p.nextZ=p.next;p=p.next;}while(p!==start);p.prevZ.nextZ=null;p.prevZ=null;sortLinked(p);}// Simon Tatham's linked list merge sort algorithm
  3835. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  3836. function sortLinked(list){var i,p,q,e,tail,numMerges,pSize,qSize,inSize=1;do{p=list;list=null;tail=null;numMerges=0;while(p){numMerges++;q=p;pSize=0;for(i=0;i<inSize;i++){pSize++;q=q.nextZ;if(!q)break;}qSize=inSize;while(pSize>0||qSize>0&&q){if(pSize!==0&&(qSize===0||!q||p.z<=q.z)){e=p;p=p.nextZ;pSize--;}else {e=q;q=q.nextZ;qSize--;}if(tail)tail.nextZ=e;else list=e;e.prevZ=tail;tail=e;}p=q;}tail.nextZ=null;inSize*=2;}while(numMerges>1);return list;}// z-order of a point given coords and inverse of the longer side of data bbox
  3837. function zOrder(x,y,minX,minY,invSize){// coords are transformed into non-negative 15-bit integer range
  3838. x=32767*(x-minX)*invSize;y=32767*(y-minY)*invSize;x=(x|x<<8)&0x00FF00FF;x=(x|x<<4)&0x0F0F0F0F;x=(x|x<<2)&0x33333333;x=(x|x<<1)&0x55555555;y=(y|y<<8)&0x00FF00FF;y=(y|y<<4)&0x0F0F0F0F;y=(y|y<<2)&0x33333333;y=(y|y<<1)&0x55555555;return x|y<<1;}// find the leftmost node of a polygon ring
  3839. function getLeftmost(start){var p=start,leftmost=start;do{if(p.x<leftmost.x||p.x===leftmost.x&&p.y<leftmost.y)leftmost=p;p=p.next;}while(p!==start);return leftmost;}// check if a point lies within a convex triangle
  3840. function pointInTriangle(ax,ay,bx,by,cx,cy,px,py){return (cx-px)*(ay-py)-(ax-px)*(cy-py)>=0&&(ax-px)*(by-py)-(bx-px)*(ay-py)>=0&&(bx-px)*(cy-py)-(cx-px)*(by-py)>=0;}// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  3841. function isValidDiagonal(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!intersectsPolygon(a,b)&&(// dones't intersect other edges
  3842. locallyInside(a,b)&&locallyInside(b,a)&&middleInside(a,b)&&(// locally visible
  3843. area(a.prev,a,b.prev)||area(a,b.prev,b))||// does not create opposite-facing sectors
  3844. equals(a,b)&&area(a.prev,a,a.next)>0&&area(b.prev,b,b.next)>0);// special zero-length case
  3845. }// signed area of a triangle
  3846. function area(p,q,r){return (q.y-p.y)*(r.x-q.x)-(q.x-p.x)*(r.y-q.y);}// check if two points are equal
  3847. function equals(p1,p2){return p1.x===p2.x&&p1.y===p2.y;}// check if two segments intersect
  3848. function intersects(p1,q1,p2,q2){var o1=sign(area(p1,q1,p2));var o2=sign(area(p1,q1,q2));var o3=sign(area(p2,q2,p1));var o4=sign(area(p2,q2,q1));if(o1!==o2&&o3!==o4)return true;// general case
  3849. if(o1===0&&onSegment(p1,p2,q1))return true;// p1, q1 and p2 are collinear and p2 lies on p1q1
  3850. if(o2===0&&onSegment(p1,q2,q1))return true;// p1, q1 and q2 are collinear and q2 lies on p1q1
  3851. if(o3===0&&onSegment(p2,p1,q2))return true;// p2, q2 and p1 are collinear and p1 lies on p2q2
  3852. if(o4===0&&onSegment(p2,q1,q2))return true;// p2, q2 and q1 are collinear and q1 lies on p2q2
  3853. return false;}// for collinear points p, q, r, check if point q lies on segment pr
  3854. function onSegment(p,q,r){return q.x<=Math.max(p.x,r.x)&&q.x>=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y);}function sign(num){return num>0?1:num<0?-1:0;}// check if a polygon diagonal intersects any polygon segments
  3855. function intersectsPolygon(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return true;p=p.next;}while(p!==a);return false;}// check if a polygon diagonal is locally inside the polygon
  3856. function locallyInside(a,b){return area(a.prev,a,a.next)<0?area(a,b,a.next)>=0&&area(a,a.prev,b)>=0:area(a,b,a.prev)<0||area(a,a.next,b)<0;}// check if the middle point of a polygon diagonal is inside the polygon
  3857. function middleInside(a,b){var p=a,inside=false;var px=(a.x+b.x)/2,py=(a.y+b.y)/2;do{if(p.y>py!==p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x)inside=!inside;p=p.next;}while(p!==a);return inside;}// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  3858. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  3859. function splitPolygon(a,b){var a2=new Node(a.i,a.x,a.y),b2=new Node(b.i,b.x,b.y),an=a.next,bp=b.prev;a.next=b;b.prev=a;a2.next=an;an.prev=a2;b2.next=a2;a2.prev=b2;bp.next=b2;b2.prev=bp;return b2;}// create a node and optionally link it with previous one (in a circular doubly linked list)
  3860. function insertNode(i,x,y,last){var p=new Node(i,x,y);if(!last){p.prev=p;p.next=p;}else {p.next=last.next;p.prev=last;last.next.prev=p;last.next=p;}return p;}function removeNode(p){p.next.prev=p.prev;p.prev.next=p.next;if(p.prevZ)p.prevZ.nextZ=p.nextZ;if(p.nextZ)p.nextZ.prevZ=p.prevZ;}function Node(i,x,y){// vertex index in coordinates array
  3861. this.i=i;// vertex coordinates
  3862. this.x=x;this.y=y;// previous and next vertex nodes in a polygon ring
  3863. this.prev=null;this.next=null;// z-order curve value
  3864. this.z=null;// previous and next nodes in z-order
  3865. this.prevZ=null;this.nextZ=null;// indicates whether this is a steiner point
  3866. this.steiner=false;}function signedArea(data,start,end,dim){var sum=0;for(var _i199=start,j=end-dim;_i199<end;_i199+=dim){sum+=(data[j]-data[_i199])*(data[_i199+1]+data[j+1]);j=_i199;}return sum;}var ShapeUtils={// calculate area of the contour polygon
  3867. area:function area(contour){var n=contour.length;var a=0.0;for(var p=n-1,q=0;q<n;p=q++){a+=contour[p].x*contour[q].y-contour[q].x*contour[p].y;}return a*0.5;},isClockWise:function isClockWise(pts){return ShapeUtils.area(pts)<0;},triangulateShape:function triangulateShape(contour,holes){var vertices=[];// flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  3868. var holeIndices=[];// array of hole indices
  3869. var faces=[];// final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  3870. removeDupEndPts(contour);addContour(vertices,contour);//
  3871. var holeIndex=contour.length;holes.forEach(removeDupEndPts);for(var _i200=0;_i200<holes.length;_i200++){holeIndices.push(holeIndex);holeIndex+=holes[_i200].length;addContour(vertices,holes[_i200]);}//
  3872. var triangles=Earcut.triangulate(vertices,holeIndices);//
  3873. for(var _i201=0;_i201<triangles.length;_i201+=3){faces.push(triangles.slice(_i201,_i201+3));}return faces;}};function removeDupEndPts(points){var l=points.length;if(l>2&&points[l-1].equals(points[0])){points.pop();}}function addContour(vertices,contour){for(var _i202=0;_i202<contour.length;_i202++){vertices.push(contour[_i202].x);vertices.push(contour[_i202].y);}}/**
  3874. * Creates extruded geometry from a path shape.
  3875. *
  3876. * parameters = {
  3877. *
  3878. * curveSegments: <int>, // number of points on the curves
  3879. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  3880. * depth: <float>, // Depth to extrude the shape
  3881. *
  3882. * bevelEnabled: <bool>, // turn on bevel
  3883. * bevelThickness: <float>, // how deep into the original shape bevel goes
  3884. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  3885. * bevelOffset: <float>, // how far from shape outline does bevel start
  3886. * bevelSegments: <int>, // number of bevel layers
  3887. *
  3888. * extrudePath: <THREE.Curve> // curve to extrude shape along
  3889. *
  3890. * UVGenerator: <Object> // object that provides UV generator functions
  3891. *
  3892. * }
  3893. */class ExtrudeBufferGeometry extends BufferGeometry{constructor(shapes,options){super();this.type='ExtrudeBufferGeometry';this.parameters={shapes:shapes,options:options};shapes=Array.isArray(shapes)?shapes:[shapes];var scope=this;var verticesArray=[];var uvArray=[];for(var _i203=0,l=shapes.length;_i203<l;_i203++){var shape=shapes[_i203];addShape(shape);}// build geometry
  3894. this.setAttribute('position',new Float32BufferAttribute(verticesArray,3));this.setAttribute('uv',new Float32BufferAttribute(uvArray,2));this.computeVertexNormals();// functions
  3895. function addShape(shape){var placeholder=[];// options
  3896. var curveSegments=options.curveSegments!==undefined?options.curveSegments:12;var steps=options.steps!==undefined?options.steps:1;var depth=options.depth!==undefined?options.depth:100;var bevelEnabled=options.bevelEnabled!==undefined?options.bevelEnabled:true;var bevelThickness=options.bevelThickness!==undefined?options.bevelThickness:6;var bevelSize=options.bevelSize!==undefined?options.bevelSize:bevelThickness-2;var bevelOffset=options.bevelOffset!==undefined?options.bevelOffset:0;var bevelSegments=options.bevelSegments!==undefined?options.bevelSegments:3;var extrudePath=options.extrudePath;var uvgen=options.UVGenerator!==undefined?options.UVGenerator:WorldUVGenerator;// deprecated options
  3897. if(options.amount!==undefined){console.warn('THREE.ExtrudeBufferGeometry: amount has been renamed to depth.');depth=options.amount;}//
  3898. var extrudePts,extrudeByPath=false;var splineTube,binormal,normal,position2;if(extrudePath){extrudePts=extrudePath.getSpacedPoints(steps);extrudeByPath=true;bevelEnabled=false;// bevels not supported for path extrusion
  3899. // SETUP TNB variables
  3900. // TODO1 - have a .isClosed in spline?
  3901. splineTube=extrudePath.computeFrenetFrames(steps,false);// console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  3902. binormal=new Vector3();normal=new Vector3();position2=new Vector3();}// Safeguards if bevels are not enabled
  3903. if(!bevelEnabled){bevelSegments=0;bevelThickness=0;bevelSize=0;bevelOffset=0;}// Variables initialization
  3904. var shapePoints=shape.extractPoints(curveSegments);var vertices=shapePoints.shape;var holes=shapePoints.holes;var reverse=!ShapeUtils.isClockWise(vertices);if(reverse){vertices=vertices.reverse();// Maybe we should also check if holes are in the opposite direction, just to be safe ...
  3905. for(var h=0,hl=holes.length;h<hl;h++){var ahole=holes[h];if(ShapeUtils.isClockWise(ahole)){holes[h]=ahole.reverse();}}}var faces=ShapeUtils.triangulateShape(vertices,holes);/* Vertices */var contour=vertices;// vertices has all points but contour has only points of circumference
  3906. for(var _h=0,_hl=holes.length;_h<_hl;_h++){var _ahole=holes[_h];vertices=vertices.concat(_ahole);}function scalePt2(pt,vec,size){if(!vec)console.error('THREE.ExtrudeGeometry: vec does not exist');return vec.clone().multiplyScalar(size).add(pt);}var vlen=vertices.length,flen=faces.length;// Find directions for point movement
  3907. function getBevelVec(inPt,inPrev,inNext){// computes for inPt the corresponding point inPt' on a new contour
  3908. // shifted by 1 unit (length of normalized vector) to the left
  3909. // if we walk along contour clockwise, this new contour is outside the old one
  3910. //
  3911. // inPt' is the intersection of the two lines parallel to the two
  3912. // adjacent edges of inPt at a distance of 1 unit on the left side.
  3913. var v_trans_x,v_trans_y,shrink_by;// resulting translation vector for inPt
  3914. // good reading for geometry algorithms (here: line-line intersection)
  3915. // http://geomalgorithms.com/a05-_intersect-1.html
  3916. var v_prev_x=inPt.x-inPrev.x,v_prev_y=inPt.y-inPrev.y;var v_next_x=inNext.x-inPt.x,v_next_y=inNext.y-inPt.y;var v_prev_lensq=v_prev_x*v_prev_x+v_prev_y*v_prev_y;// check for collinear edges
  3917. var collinear0=v_prev_x*v_next_y-v_prev_y*v_next_x;if(Math.abs(collinear0)>Number.EPSILON){// not collinear
  3918. // length of vectors for normalizing
  3919. var v_prev_len=Math.sqrt(v_prev_lensq);var v_next_len=Math.sqrt(v_next_x*v_next_x+v_next_y*v_next_y);// shift adjacent points by unit vectors to the left
  3920. var ptPrevShift_x=inPrev.x-v_prev_y/v_prev_len;var ptPrevShift_y=inPrev.y+v_prev_x/v_prev_len;var ptNextShift_x=inNext.x-v_next_y/v_next_len;var ptNextShift_y=inNext.y+v_next_x/v_next_len;// scaling factor for v_prev to intersection point
  3921. var sf=((ptNextShift_x-ptPrevShift_x)*v_next_y-(ptNextShift_y-ptPrevShift_y)*v_next_x)/(v_prev_x*v_next_y-v_prev_y*v_next_x);// vector from inPt to intersection point
  3922. v_trans_x=ptPrevShift_x+v_prev_x*sf-inPt.x;v_trans_y=ptPrevShift_y+v_prev_y*sf-inPt.y;// Don't normalize!, otherwise sharp corners become ugly
  3923. // but prevent crazy spikes
  3924. var v_trans_lensq=v_trans_x*v_trans_x+v_trans_y*v_trans_y;if(v_trans_lensq<=2){return new Vector2(v_trans_x,v_trans_y);}else {shrink_by=Math.sqrt(v_trans_lensq/2);}}else {// handle special case of collinear edges
  3925. var direction_eq=false;// assumes: opposite
  3926. if(v_prev_x>Number.EPSILON){if(v_next_x>Number.EPSILON){direction_eq=true;}}else {if(v_prev_x<-Number.EPSILON){if(v_next_x<-Number.EPSILON){direction_eq=true;}}else {if(Math.sign(v_prev_y)===Math.sign(v_next_y)){direction_eq=true;}}}if(direction_eq){// console.log("Warning: lines are a straight sequence");
  3927. v_trans_x=-v_prev_y;v_trans_y=v_prev_x;shrink_by=Math.sqrt(v_prev_lensq);}else {// console.log("Warning: lines are a straight spike");
  3928. v_trans_x=v_prev_x;v_trans_y=v_prev_y;shrink_by=Math.sqrt(v_prev_lensq/2);}}return new Vector2(v_trans_x/shrink_by,v_trans_y/shrink_by);}var contourMovements=[];for(var _i204=0,il=contour.length,j=il-1,k=_i204+1;_i204<il;_i204++,j++,k++){if(j===il)j=0;if(k===il)k=0;// (j)---(i)---(k)
  3929. // console.log('i,j,k', i, j , k)
  3930. contourMovements[_i204]=getBevelVec(contour[_i204],contour[j],contour[k]);}var holesMovements=[];var oneHoleMovements,verticesMovements=contourMovements.concat();for(var _h2=0,_hl2=holes.length;_h2<_hl2;_h2++){var _ahole2=holes[_h2];oneHoleMovements=[];for(var _i205=0,_il26=_ahole2.length,_j12=_il26-1,_k=_i205+1;_i205<_il26;_i205++,_j12++,_k++){if(_j12===_il26)_j12=0;if(_k===_il26)_k=0;// (j)---(i)---(k)
  3931. oneHoleMovements[_i205]=getBevelVec(_ahole2[_i205],_ahole2[_j12],_ahole2[_k]);}holesMovements.push(oneHoleMovements);verticesMovements=verticesMovements.concat(oneHoleMovements);}// Loop bevelSegments, 1 for the front, 1 for the back
  3932. for(var b=0;b<bevelSegments;b++){//for ( b = bevelSegments; b > 0; b -- ) {
  3933. var t=b/bevelSegments;var z=bevelThickness*Math.cos(t*Math.PI/2);var _bs=bevelSize*Math.sin(t*Math.PI/2)+bevelOffset;// contract shape
  3934. for(var _i206=0,_il27=contour.length;_i206<_il27;_i206++){var vert=scalePt2(contour[_i206],contourMovements[_i206],_bs);v(vert.x,vert.y,-z);}// expand holes
  3935. for(var _h3=0,_hl3=holes.length;_h3<_hl3;_h3++){var _ahole3=holes[_h3];oneHoleMovements=holesMovements[_h3];for(var _i207=0,_il28=_ahole3.length;_i207<_il28;_i207++){var _vert=scalePt2(_ahole3[_i207],oneHoleMovements[_i207],_bs);v(_vert.x,_vert.y,-z);}}}var bs=bevelSize+bevelOffset;// Back facing vertices
  3936. for(var _i208=0;_i208<vlen;_i208++){var _vert2=bevelEnabled?scalePt2(vertices[_i208],verticesMovements[_i208],bs):vertices[_i208];if(!extrudeByPath){v(_vert2.x,_vert2.y,0);}else {// v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  3937. normal.copy(splineTube.normals[0]).multiplyScalar(_vert2.x);binormal.copy(splineTube.binormals[0]).multiplyScalar(_vert2.y);position2.copy(extrudePts[0]).add(normal).add(binormal);v(position2.x,position2.y,position2.z);}}// Add stepped vertices...
  3938. // Including front facing vertices
  3939. for(var s=1;s<=steps;s++){for(var _i209=0;_i209<vlen;_i209++){var _vert3=bevelEnabled?scalePt2(vertices[_i209],verticesMovements[_i209],bs):vertices[_i209];if(!extrudeByPath){v(_vert3.x,_vert3.y,depth/steps*s);}else {// v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  3940. normal.copy(splineTube.normals[s]).multiplyScalar(_vert3.x);binormal.copy(splineTube.binormals[s]).multiplyScalar(_vert3.y);position2.copy(extrudePts[s]).add(normal).add(binormal);v(position2.x,position2.y,position2.z);}}}// Add bevel segments planes
  3941. //for ( b = 1; b <= bevelSegments; b ++ ) {
  3942. for(var _b5=bevelSegments-1;_b5>=0;_b5--){var _t=_b5/bevelSegments;var _z2=bevelThickness*Math.cos(_t*Math.PI/2);var _bs2=bevelSize*Math.sin(_t*Math.PI/2)+bevelOffset;// contract shape
  3943. for(var _i210=0,_il29=contour.length;_i210<_il29;_i210++){var _vert4=scalePt2(contour[_i210],contourMovements[_i210],_bs2);v(_vert4.x,_vert4.y,depth+_z2);}// expand holes
  3944. for(var _h4=0,_hl4=holes.length;_h4<_hl4;_h4++){var _ahole4=holes[_h4];oneHoleMovements=holesMovements[_h4];for(var _i211=0,_il30=_ahole4.length;_i211<_il30;_i211++){var _vert5=scalePt2(_ahole4[_i211],oneHoleMovements[_i211],_bs2);if(!extrudeByPath){v(_vert5.x,_vert5.y,depth+_z2);}else {v(_vert5.x,_vert5.y+extrudePts[steps-1].y,extrudePts[steps-1].x+_z2);}}}}/* Faces */ // Top and bottom faces
  3945. if(!options.openEnded){//xzw add 可以选择开口,不创建Top and bottom faces
  3946. buildLidFaces();}// Sides faces
  3947. buildSideFaces();///// Internal functions
  3948. function buildLidFaces(){var start=verticesArray.length/3;if(bevelEnabled){var layer=0;// steps + 1
  3949. var offset=vlen*layer;// Bottom faces
  3950. for(var _i212=0;_i212<flen;_i212++){var face=faces[_i212];f3(face[2]+offset,face[1]+offset,face[0]+offset);}layer=steps+bevelSegments*2;offset=vlen*layer;// Top faces
  3951. for(var _i213=0;_i213<flen;_i213++){var _face5=faces[_i213];f3(_face5[0]+offset,_face5[1]+offset,_face5[2]+offset);}}else {// Bottom faces
  3952. for(var _i214=0;_i214<flen;_i214++){var _face6=faces[_i214];f3(_face6[2],_face6[1],_face6[0]);}// Top faces
  3953. for(var _i215=0;_i215<flen;_i215++){var _face7=faces[_i215];f3(_face7[0]+vlen*steps,_face7[1]+vlen*steps,_face7[2]+vlen*steps);}}scope.addGroup(start,verticesArray.length/3-start,0);}// Create faces for the z-sides of the shape
  3954. function buildSideFaces(){var start=verticesArray.length/3;var layeroffset=0;sidewalls(contour,layeroffset);layeroffset+=contour.length;for(var _h5=0,_hl5=holes.length;_h5<_hl5;_h5++){var _ahole5=holes[_h5];sidewalls(_ahole5,layeroffset);//, true
  3955. layeroffset+=_ahole5.length;}scope.addGroup(start,verticesArray.length/3-start,1);}function sidewalls(contour,layeroffset){var i=contour.length;var shapeDontClose=shape.dontClose;//xzw add不闭合
  3956. while(--i>=0){if(shapeDontClose&&i==0)break;//xzw add
  3957. var _j13=i;var _k2=i-1;if(_k2<0)_k2=contour.length-1;//console.log('b', i,j, i-1, k,vertices.length);
  3958. for(var _s4=0,sl=steps+bevelSegments*2;_s4<sl;_s4++){var slen1=vlen*_s4;var slen2=vlen*(_s4+1);var a=layeroffset+_j13+slen1,_b6=layeroffset+_k2+slen1,c=layeroffset+_k2+slen2,d=layeroffset+_j13+slen2;f4(a,_b6,c,d);}}}function v(x,y,z){placeholder.push(x);placeholder.push(y);placeholder.push(z);}function f3(a,b,c){addVertex(a);addVertex(b);addVertex(c);var nextIndex=verticesArray.length/3;var uvs=uvgen.generateTopUV(scope,verticesArray,nextIndex-3,nextIndex-2,nextIndex-1);addUV(uvs[0]);addUV(uvs[1]);addUV(uvs[2]);}function f4(a,b,c,d){addVertex(a);addVertex(b);addVertex(d);addVertex(b);addVertex(c);addVertex(d);var nextIndex=verticesArray.length/3;var uvs=uvgen.generateSideWallUV(scope,verticesArray,nextIndex-6,nextIndex-3,nextIndex-2,nextIndex-1);addUV(uvs[0]);addUV(uvs[1]);addUV(uvs[3]);addUV(uvs[1]);addUV(uvs[2]);addUV(uvs[3]);}function addVertex(index){verticesArray.push(placeholder[index*3+0]);verticesArray.push(placeholder[index*3+1]);verticesArray.push(placeholder[index*3+2]);}function addUV(vector2){uvArray.push(vector2.x);uvArray.push(vector2.y);}}}toJSON(){var data=BufferGeometry.prototype.toJSON.call(this);var shapes=this.parameters.shapes;var options=this.parameters.options;return toJSON(shapes,options,data);}}var WorldUVGenerator={generateTopUV:function generateTopUV(geometry,vertices,indexA,indexB,indexC){var a_x=vertices[indexA*3];var a_y=vertices[indexA*3+1];var b_x=vertices[indexB*3];var b_y=vertices[indexB*3+1];var c_x=vertices[indexC*3];var c_y=vertices[indexC*3+1];return [new Vector2(a_x,a_y),new Vector2(b_x,b_y),new Vector2(c_x,c_y)];},generateSideWallUV:function generateSideWallUV(geometry,vertices,indexA,indexB,indexC,indexD){var a_x=vertices[indexA*3];var a_y=vertices[indexA*3+1];var a_z=vertices[indexA*3+2];var b_x=vertices[indexB*3];var b_y=vertices[indexB*3+1];var b_z=vertices[indexB*3+2];var c_x=vertices[indexC*3];var c_y=vertices[indexC*3+1];var c_z=vertices[indexC*3+2];var d_x=vertices[indexD*3];var d_y=vertices[indexD*3+1];var d_z=vertices[indexD*3+2];if(Math.abs(a_y-b_y)<0.01){return [new Vector2(a_x,1-a_z),new Vector2(b_x,1-b_z),new Vector2(c_x,1-c_z),new Vector2(d_x,1-d_z)];}else {return [new Vector2(a_y,1-a_z),new Vector2(b_y,1-b_z),new Vector2(c_y,1-c_z),new Vector2(d_y,1-d_z)];}}};function toJSON(shapes,options,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i216=0,l=shapes.length;_i216<l;_i216++){var shape=shapes[_i216];data.shapes.push(shape.uuid);}}else {data.shapes.push(shapes.uuid);}if(options.extrudePath!==undefined)data.options.extrudePath=options.extrudePath.toJSON();return data;}/**
  3959. * Creates extruded geometry from a path shape.
  3960. *
  3961. * parameters = {
  3962. *
  3963. * curveSegments: <int>, // number of points on the curves
  3964. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  3965. * depth: <float>, // Depth to extrude the shape
  3966. *
  3967. * bevelEnabled: <bool>, // turn on bevel
  3968. * bevelThickness: <float>, // how deep into the original shape bevel goes
  3969. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  3970. * bevelOffset: <float>, // how far from shape outline does bevel start
  3971. * bevelSegments: <int>, // number of bevel layers
  3972. *
  3973. * extrudePath: <THREE.Curve> // curve to extrude shape along
  3974. *
  3975. * UVGenerator: <Object> // object that provides UV generator functions
  3976. *
  3977. * }
  3978. */class ExtrudeGeometry extends Geometry{constructor(shapes,options){super();this.type='ExtrudeGeometry';this.parameters={shapes:shapes,options:options};this.fromBufferGeometry(new ExtrudeBufferGeometry(shapes,options));this.mergeVertices();}toJSON(){var data=super.toJSON();var shapes=this.parameters.shapes;var options=this.parameters.options;return toJSON$1(shapes,options,data);}}function toJSON$1(shapes,options,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i217=0,l=shapes.length;_i217<l;_i217++){var shape=shapes[_i217];data.shapes.push(shape.uuid);}}else {data.shapes.push(shapes.uuid);}if(options.extrudePath!==undefined)data.options.extrudePath=options.extrudePath.toJSON();return data;}class IcosahedronBufferGeometry extends PolyhedronBufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var t=(1+Math.sqrt(5))/2;var vertices=[-1,t,0,1,t,0,-1,-t,0,1,-t,0,0,-1,t,0,1,t,0,-1,-t,0,1,-t,t,0,-1,t,0,1,-t,0,-1,-t,0,1];var indices=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(vertices,indices,radius,detail);this.type='IcosahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class IcosahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='IcosahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new IcosahedronBufferGeometry(radius,detail));this.mergeVertices();}}class LatheBufferGeometry extends BufferGeometry{constructor(points){var segments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:12;var phiStart=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var phiLength=arguments.length>3&&arguments[3]!==undefined?arguments[3]:Math.PI*2;super();this.type='LatheBufferGeometry';this.parameters={points:points,segments:segments,phiStart:phiStart,phiLength:phiLength};segments=Math.floor(segments);// clamp phiLength so it's in range of [ 0, 2PI ]
  3979. phiLength=MathUtils.clamp(phiLength,0,Math.PI*2);// buffers
  3980. var indices=[];var vertices=[];var uvs=[];// helper variables
  3981. var inverseSegments=1.0/segments;var vertex=new Vector3();var uv=new Vector2();// generate vertices and uvs
  3982. for(var _i218=0;_i218<=segments;_i218++){var phi=phiStart+_i218*inverseSegments*phiLength;var sin=Math.sin(phi);var cos=Math.cos(phi);for(var j=0;j<=points.length-1;j++){// vertex
  3983. vertex.x=points[j].x*sin;vertex.y=points[j].y;vertex.z=points[j].x*cos;vertices.push(vertex.x,vertex.y,vertex.z);// uv
  3984. uv.x=_i218/segments;uv.y=j/(points.length-1);uvs.push(uv.x,uv.y);}}// indices
  3985. for(var _i219=0;_i219<segments;_i219++){for(var _j14=0;_j14<points.length-1;_j14++){var base=_j14+_i219*points.length;var a=base;var b=base+points.length;var c=base+points.length+1;var d=base+1;// faces
  3986. indices.push(a,b,d);indices.push(b,c,d);}}// build geometry
  3987. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// generate normals
  3988. this.computeVertexNormals();// if the geometry is closed, we need to average the normals along the seam.
  3989. // because the corresponding vertices are identical (but still have different UVs).
  3990. if(phiLength===Math.PI*2){var normals=this.attributes.normal.array;var n1=new Vector3();var n2=new Vector3();var n=new Vector3();// this is the buffer offset for the last line of vertices
  3991. var _base=segments*points.length*3;for(var _i220=0,_j15=0;_i220<points.length;_i220++,_j15+=3){// select the normal of the vertex in the first line
  3992. n1.x=normals[_j15+0];n1.y=normals[_j15+1];n1.z=normals[_j15+2];// select the normal of the vertex in the last line
  3993. n2.x=normals[_base+_j15+0];n2.y=normals[_base+_j15+1];n2.z=normals[_base+_j15+2];// average normals
  3994. n.addVectors(n1,n2).normalize();// assign the new values to both normals
  3995. normals[_j15+0]=normals[_base+_j15+0]=n.x;normals[_j15+1]=normals[_base+_j15+1]=n.y;normals[_j15+2]=normals[_base+_j15+2]=n.z;}}}}class LatheGeometry extends Geometry{constructor(points,segments,phiStart,phiLength){super();this.type='LatheGeometry';this.parameters={points:points,segments:segments,phiStart:phiStart,phiLength:phiLength};this.fromBufferGeometry(new LatheBufferGeometry(points,segments,phiStart,phiLength));this.mergeVertices();}}class OctahedronBufferGeometry extends PolyhedronBufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var vertices=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1];var indices=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(vertices,indices,radius,detail);this.type='OctahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class OctahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='OctahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new OctahedronBufferGeometry(radius,detail));this.mergeVertices();}}/**
  3996. * Parametric Surfaces Geometry
  3997. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  3998. */function ParametricBufferGeometry(func,slices,stacks){BufferGeometry.call(this);this.type='ParametricBufferGeometry';this.parameters={func:func,slices:slices,stacks:stacks};// buffers
  3999. var indices=[];var vertices=[];var normals=[];var uvs=[];var EPS=0.00001;var normal=new Vector3();var p0=new Vector3(),p1=new Vector3();var pu=new Vector3(),pv=new Vector3();if(func.length<3){console.error('THREE.ParametricGeometry: Function must now modify a Vector3 as third parameter.');}// generate vertices, normals and uvs
  4000. var sliceCount=slices+1;for(var _i221=0;_i221<=stacks;_i221++){var v=_i221/stacks;for(var j=0;j<=slices;j++){var u=j/slices;// vertex
  4001. func(u,v,p0);vertices.push(p0.x,p0.y,p0.z);// normal
  4002. // approximate tangent vectors via finite differences
  4003. if(u-EPS>=0){func(u-EPS,v,p1);pu.subVectors(p0,p1);}else {func(u+EPS,v,p1);pu.subVectors(p1,p0);}if(v-EPS>=0){func(u,v-EPS,p1);pv.subVectors(p0,p1);}else {func(u,v+EPS,p1);pv.subVectors(p1,p0);}// cross product of tangent vectors returns surface normal
  4004. normal.crossVectors(pu,pv).normalize();normals.push(normal.x,normal.y,normal.z);// uv
  4005. uvs.push(u,v);}}// generate indices
  4006. for(var _i222=0;_i222<stacks;_i222++){for(var _j16=0;_j16<slices;_j16++){var a=_i222*sliceCount+_j16;var b=_i222*sliceCount+_j16+1;var c=(_i222+1)*sliceCount+_j16+1;var d=(_i222+1)*sliceCount+_j16;// faces one and two
  4007. indices.push(a,b,d);indices.push(b,c,d);}}// build geometry
  4008. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}ParametricBufferGeometry.prototype=Object.create(BufferGeometry.prototype);ParametricBufferGeometry.prototype.constructor=ParametricBufferGeometry;/**
  4009. * Parametric Surfaces Geometry
  4010. * based on the brilliant article by @prideout https://prideout.net/blog/old/blog/index.html@p=44.html
  4011. */function ParametricGeometry(func,slices,stacks){Geometry.call(this);this.type='ParametricGeometry';this.parameters={func:func,slices:slices,stacks:stacks};this.fromBufferGeometry(new ParametricBufferGeometry(func,slices,stacks));this.mergeVertices();}ParametricGeometry.prototype=Object.create(Geometry.prototype);ParametricGeometry.prototype.constructor=ParametricGeometry;class PlaneGeometry extends Geometry{constructor(width,height,widthSegments,heightSegments){super();this.type='PlaneGeometry';this.parameters={width:width,height:height,widthSegments:widthSegments,heightSegments:heightSegments};this.fromBufferGeometry(new PlaneBufferGeometry(width,height,widthSegments,heightSegments));this.mergeVertices();}}class PolyhedronGeometry extends Geometry{constructor(vertices,indices,radius,detail){super();this.type='PolyhedronGeometry';this.parameters={vertices:vertices,indices:indices,radius:radius,detail:detail};this.fromBufferGeometry(new PolyhedronBufferGeometry(vertices,indices,radius,detail));this.mergeVertices();}}class RingBufferGeometry extends BufferGeometry{constructor(){var innerRadius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0.5;var outerRadius=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var thetaSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var phiSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var thetaStart=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var thetaLength=arguments.length>5&&arguments[5]!==undefined?arguments[5]:Math.PI*2;super();this.type='RingBufferGeometry';this.parameters={innerRadius:innerRadius,outerRadius:outerRadius,thetaSegments:thetaSegments,phiSegments:phiSegments,thetaStart:thetaStart,thetaLength:thetaLength};thetaSegments=Math.max(3,thetaSegments);phiSegments=Math.max(1,phiSegments);// buffers
  4012. var indices=[];var vertices=[];var normals=[];var uvs=[];// some helper variables
  4013. var radius=innerRadius;var radiusStep=(outerRadius-innerRadius)/phiSegments;var vertex=new Vector3();var uv=new Vector2();// generate vertices, normals and uvs
  4014. for(var j=0;j<=phiSegments;j++){for(var _i223=0;_i223<=thetaSegments;_i223++){// values are generate from the inside of the ring to the outside
  4015. var segment=thetaStart+_i223/thetaSegments*thetaLength;// vertex
  4016. vertex.x=radius*Math.cos(segment);vertex.y=radius*Math.sin(segment);vertices.push(vertex.x,vertex.y,vertex.z);// normal
  4017. normals.push(0,0,1);// uv
  4018. uv.x=(vertex.x/outerRadius+1)/2;uv.y=(vertex.y/outerRadius+1)/2;uvs.push(uv.x,uv.y);}// increase the radius for next row of vertices
  4019. radius+=radiusStep;}// indices
  4020. for(var _j17=0;_j17<phiSegments;_j17++){var thetaSegmentLevel=_j17*(thetaSegments+1);for(var _i224=0;_i224<thetaSegments;_i224++){var _segment=_i224+thetaSegmentLevel;var a=_segment;var b=_segment+thetaSegments+1;var c=_segment+thetaSegments+2;var d=_segment+1;// faces
  4021. indices.push(a,b,d);indices.push(b,c,d);}}// build geometry
  4022. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class RingGeometry extends Geometry{constructor(innerRadius,outerRadius,thetaSegments,phiSegments,thetaStart,thetaLength){super();this.type='RingGeometry';this.parameters={innerRadius:innerRadius,outerRadius:outerRadius,thetaSegments:thetaSegments,phiSegments:phiSegments,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new RingBufferGeometry(innerRadius,outerRadius,thetaSegments,phiSegments,thetaStart,thetaLength));this.mergeVertices();}}class ShapeBufferGeometry extends BufferGeometry{constructor(shapes){var curveSegments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:12;super();this.type='ShapeBufferGeometry';this.parameters={shapes:shapes,curveSegments:curveSegments};// buffers
  4023. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  4024. var groupStart=0;var groupCount=0;// allow single and array values for "shapes" parameter
  4025. if(Array.isArray(shapes)===false){addShape(shapes);}else {for(var _i225=0;_i225<shapes.length;_i225++){addShape(shapes[_i225]);this.addGroup(groupStart,groupCount,_i225);// enables MultiMaterial support
  4026. groupStart+=groupCount;groupCount=0;}}// build geometry
  4027. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// helper functions
  4028. function addShape(shape){var indexOffset=vertices.length/3;var points=shape.extractPoints(curveSegments);var shapeVertices=points.shape;var shapeHoles=points.holes;// check direction of vertices
  4029. if(ShapeUtils.isClockWise(shapeVertices)===false){shapeVertices=shapeVertices.reverse();}for(var _i226=0,l=shapeHoles.length;_i226<l;_i226++){var shapeHole=shapeHoles[_i226];if(ShapeUtils.isClockWise(shapeHole)===true){shapeHoles[_i226]=shapeHole.reverse();}}var faces=ShapeUtils.triangulateShape(shapeVertices,shapeHoles);// join vertices of inner and outer paths to a single array
  4030. for(var _i227=0,_l10=shapeHoles.length;_i227<_l10;_i227++){var _shapeHole=shapeHoles[_i227];shapeVertices=shapeVertices.concat(_shapeHole);}// vertices, normals, uvs
  4031. for(var _i228=0,_l11=shapeVertices.length;_i228<_l11;_i228++){var vertex=shapeVertices[_i228];vertices.push(vertex.x,vertex.y,0);normals.push(0,0,1);uvs.push(vertex.x,vertex.y);// world uvs
  4032. }// incides
  4033. for(var _i229=0,_l12=faces.length;_i229<_l12;_i229++){var face=faces[_i229];var a=face[0]+indexOffset;var b=face[1]+indexOffset;var c=face[2]+indexOffset;indices.push(a,b,c);groupCount+=3;}}}toJSON(){var data=BufferGeometry.prototype.toJSON.call(this);var shapes=this.parameters.shapes;return toJSON$2(shapes,data);}}function toJSON$2(shapes,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i230=0,l=shapes.length;_i230<l;_i230++){var shape=shapes[_i230];data.shapes.push(shape.uuid);}}else {data.shapes.push(shapes.uuid);}return data;}class ShapeGeometry extends Geometry{constructor(shapes,curveSegments){super();this.type='ShapeGeometry';if(typeof curveSegments==='object'){console.warn('THREE.ShapeGeometry: Options parameter has been removed.');curveSegments=curveSegments.curveSegments;}this.parameters={shapes:shapes,curveSegments:curveSegments};this.fromBufferGeometry(new ShapeBufferGeometry(shapes,curveSegments));this.mergeVertices();}toJSON(){var data=Geometry.prototype.toJSON.call(this);var shapes=this.parameters.shapes;return toJSON$3(shapes,data);}}function toJSON$3(shapes,data){data.shapes=[];if(Array.isArray(shapes)){for(var _i231=0,l=shapes.length;_i231<l;_i231++){var shape=shapes[_i231];data.shapes.push(shape.uuid);}}else {data.shapes.push(shapes.uuid);}return data;}class SphereBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var widthSegments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var heightSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:6;var phiStart=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var phiLength=arguments.length>4&&arguments[4]!==undefined?arguments[4]:Math.PI*2;var thetaStart=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0;var thetaLength=arguments.length>6&&arguments[6]!==undefined?arguments[6]:Math.PI;super();this.type='SphereBufferGeometry';this.parameters={radius:radius,widthSegments:widthSegments,heightSegments:heightSegments,phiStart:phiStart,phiLength:phiLength,thetaStart:thetaStart,thetaLength:thetaLength};widthSegments=Math.max(3,Math.floor(widthSegments));heightSegments=Math.max(2,Math.floor(heightSegments));var thetaEnd=Math.min(thetaStart+thetaLength,Math.PI);var index=0;var grid=[];var vertex=new Vector3();var normal=new Vector3();// buffers
  4034. var indices=[];var vertices=[];var normals=[];var uvs=[];// generate vertices, normals and uvs
  4035. for(var iy=0;iy<=heightSegments;iy++){var verticesRow=[];var v=iy/heightSegments;// special case for the poles
  4036. var uOffset=0;if(iy==0&&thetaStart==0){uOffset=0.5/widthSegments;}else if(iy==heightSegments&&thetaEnd==Math.PI){uOffset=-0.5/widthSegments;}for(var ix=0;ix<=widthSegments;ix++){var u=ix/widthSegments;// vertex
  4037. vertex.x=-radius*Math.cos(phiStart+u*phiLength)*Math.sin(thetaStart+v*thetaLength);vertex.y=radius*Math.cos(thetaStart+v*thetaLength);vertex.z=radius*Math.sin(phiStart+u*phiLength)*Math.sin(thetaStart+v*thetaLength);vertices.push(vertex.x,vertex.y,vertex.z);// normal
  4038. normal.copy(vertex).normalize();normals.push(normal.x,normal.y,normal.z);// uv
  4039. uvs.push(u+uOffset,1-v);verticesRow.push(index++);}grid.push(verticesRow);}// indices
  4040. for(var _iy3=0;_iy3<heightSegments;_iy3++){for(var _ix3=0;_ix3<widthSegments;_ix3++){var a=grid[_iy3][_ix3+1];var b=grid[_iy3][_ix3];var c=grid[_iy3+1][_ix3];var d=grid[_iy3+1][_ix3+1];if(_iy3!==0||thetaStart>0)indices.push(a,b,d);if(_iy3!==heightSegments-1||thetaEnd<Math.PI)indices.push(b,c,d);}}// build geometry
  4041. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class SphereGeometry extends Geometry{constructor(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength){super();this.type='SphereGeometry';this.parameters={radius:radius,widthSegments:widthSegments,heightSegments:heightSegments,phiStart:phiStart,phiLength:phiLength,thetaStart:thetaStart,thetaLength:thetaLength};this.fromBufferGeometry(new SphereBufferGeometry(radius,widthSegments,heightSegments,phiStart,phiLength,thetaStart,thetaLength));this.mergeVertices();}}class TetrahedronBufferGeometry extends PolyhedronBufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var detail=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var vertices=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1];var indices=[2,1,0,0,3,2,1,3,0,2,3,1];super(vertices,indices,radius,detail);this.type='TetrahedronBufferGeometry';this.parameters={radius:radius,detail:detail};}}class TetrahedronGeometry extends Geometry{constructor(radius,detail){super();this.type='TetrahedronGeometry';this.parameters={radius:radius,detail:detail};this.fromBufferGeometry(new TetrahedronBufferGeometry(radius,detail));this.mergeVertices();}}/**
  4042. * Text = 3D Text
  4043. *
  4044. * parameters = {
  4045. * font: <THREE.Font>, // font
  4046. *
  4047. * size: <float>, // size of the text
  4048. * height: <float>, // thickness to extrude text
  4049. * curveSegments: <int>, // number of points on the curves
  4050. *
  4051. * bevelEnabled: <bool>, // turn on bevel
  4052. * bevelThickness: <float>, // how deep into text bevel goes
  4053. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  4054. * bevelOffset: <float> // how far from text outline does bevel start
  4055. * }
  4056. */class TextBufferGeometry extends ExtrudeBufferGeometry{constructor(text){var parameters=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var font=parameters.font;if(!(font&&font.isFont)){console.error('THREE.TextGeometry: font parameter is not an instance of THREE.Font.');return new BufferGeometry();}var shapes=font.generateShapes(text,parameters.size);// translate parameters to ExtrudeGeometry API
  4057. parameters.depth=parameters.height!==undefined?parameters.height:50;// defaults
  4058. if(parameters.bevelThickness===undefined)parameters.bevelThickness=10;if(parameters.bevelSize===undefined)parameters.bevelSize=8;if(parameters.bevelEnabled===undefined)parameters.bevelEnabled=false;super(shapes,parameters);this.type='TextBufferGeometry';}}/**
  4059. * Text = 3D Text
  4060. *
  4061. * parameters = {
  4062. * font: <THREE.Font>, // font
  4063. *
  4064. * size: <float>, // size of the text
  4065. * height: <float>, // thickness to extrude text
  4066. * curveSegments: <int>, // number of points on the curves
  4067. *
  4068. * bevelEnabled: <bool>, // turn on bevel
  4069. * bevelThickness: <float>, // how deep into text bevel goes
  4070. * bevelSize: <float>, // how far from text outline (including bevelOffset) is bevel
  4071. * bevelOffset: <float> // how far from text outline does bevel start
  4072. * }
  4073. */class TextGeometry extends Geometry{constructor(text,parameters){super();this.type='TextGeometry';this.parameters={text:text,parameters:parameters};this.fromBufferGeometry(new TextBufferGeometry(text,parameters));this.mergeVertices();}}class TorusBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var tube=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.4;var radialSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var tubularSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:6;var arc=arguments.length>4&&arguments[4]!==undefined?arguments[4]:Math.PI*2;super();this.type='TorusBufferGeometry';this.parameters={radius:radius,tube:tube,radialSegments:radialSegments,tubularSegments:tubularSegments,arc:arc};radialSegments=Math.floor(radialSegments);tubularSegments=Math.floor(tubularSegments);// buffers
  4074. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  4075. var center=new Vector3();var vertex=new Vector3();var normal=new Vector3();// generate vertices, normals and uvs
  4076. for(var j=0;j<=radialSegments;j++){for(var _i232=0;_i232<=tubularSegments;_i232++){var u=_i232/tubularSegments*arc;var v=j/radialSegments*Math.PI*2;// vertex
  4077. vertex.x=(radius+tube*Math.cos(v))*Math.cos(u);vertex.y=(radius+tube*Math.cos(v))*Math.sin(u);vertex.z=tube*Math.sin(v);vertices.push(vertex.x,vertex.y,vertex.z);// normal
  4078. center.x=radius*Math.cos(u);center.y=radius*Math.sin(u);normal.subVectors(vertex,center).normalize();normals.push(normal.x,normal.y,normal.z);// uv
  4079. uvs.push(_i232/tubularSegments);uvs.push(j/radialSegments);}}// generate indices
  4080. for(var _j18=1;_j18<=radialSegments;_j18++){for(var _i233=1;_i233<=tubularSegments;_i233++){// indices
  4081. var a=(tubularSegments+1)*_j18+_i233-1;var b=(tubularSegments+1)*(_j18-1)+_i233-1;var c=(tubularSegments+1)*(_j18-1)+_i233;var d=(tubularSegments+1)*_j18+_i233;// faces
  4082. indices.push(a,b,d);indices.push(b,c,d);}}// build geometry
  4083. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));}}class TorusGeometry extends Geometry{constructor(radius,tube,radialSegments,tubularSegments,arc){super();this.type='TorusGeometry';this.parameters={radius:radius,tube:tube,radialSegments:radialSegments,tubularSegments:tubularSegments,arc:arc};this.fromBufferGeometry(new TorusBufferGeometry(radius,tube,radialSegments,tubularSegments,arc));this.mergeVertices();}}class TorusKnotBufferGeometry extends BufferGeometry{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var tube=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.4;var tubularSegments=arguments.length>2&&arguments[2]!==undefined?arguments[2]:64;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var p=arguments.length>4&&arguments[4]!==undefined?arguments[4]:2;var q=arguments.length>5&&arguments[5]!==undefined?arguments[5]:3;super();this.type='TorusKnotBufferGeometry';this.parameters={radius:radius,tube:tube,tubularSegments:tubularSegments,radialSegments:radialSegments,p:p,q:q};tubularSegments=Math.floor(tubularSegments);radialSegments=Math.floor(radialSegments);// buffers
  4084. var indices=[];var vertices=[];var normals=[];var uvs=[];// helper variables
  4085. var vertex=new Vector3();var normal=new Vector3();var P1=new Vector3();var P2=new Vector3();var B=new Vector3();var T=new Vector3();var N=new Vector3();// generate vertices, normals and uvs
  4086. for(var _i234=0;_i234<=tubularSegments;++_i234){// the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  4087. var u=_i234/tubularSegments*p*Math.PI*2;// now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  4088. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  4089. calculatePositionOnCurve(u,p,q,radius,P1);calculatePositionOnCurve(u+0.01,p,q,radius,P2);// calculate orthonormal basis
  4090. T.subVectors(P2,P1);N.addVectors(P2,P1);B.crossVectors(T,N);N.crossVectors(B,T);// normalize B, N. T can be ignored, we don't use it
  4091. B.normalize();N.normalize();for(var j=0;j<=radialSegments;++j){// now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  4092. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  4093. var v=j/radialSegments*Math.PI*2;var cx=-tube*Math.cos(v);var cy=tube*Math.sin(v);// now calculate the final vertex position.
  4094. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  4095. vertex.x=P1.x+(cx*N.x+cy*B.x);vertex.y=P1.y+(cx*N.y+cy*B.y);vertex.z=P1.z+(cx*N.z+cy*B.z);vertices.push(vertex.x,vertex.y,vertex.z);// normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  4096. normal.subVectors(vertex,P1).normalize();normals.push(normal.x,normal.y,normal.z);// uv
  4097. uvs.push(_i234/tubularSegments);uvs.push(j/radialSegments);}}// generate indices
  4098. for(var _j19=1;_j19<=tubularSegments;_j19++){for(var _i235=1;_i235<=radialSegments;_i235++){// indices
  4099. var a=(radialSegments+1)*(_j19-1)+(_i235-1);var b=(radialSegments+1)*_j19+(_i235-1);var c=(radialSegments+1)*_j19+_i235;var d=(radialSegments+1)*(_j19-1)+_i235;// faces
  4100. indices.push(a,b,d);indices.push(b,c,d);}}// build geometry
  4101. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// this function calculates the current position on the torus curve
  4102. function calculatePositionOnCurve(u,p,q,radius,position){var cu=Math.cos(u);var su=Math.sin(u);var quOverP=q/p*u;var cs=Math.cos(quOverP);position.x=radius*(2+cs)*0.5*cu;position.y=radius*(2+cs)*su*0.5;position.z=radius*Math.sin(quOverP)*0.5;}}}class TorusKnotGeometry extends Geometry{constructor(radius,tube,tubularSegments,radialSegments,p,q,heightScale){super();this.type='TorusKnotGeometry';this.parameters={radius:radius,tube:tube,tubularSegments:tubularSegments,radialSegments:radialSegments,p:p,q:q};if(heightScale!==undefined)console.warn('THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.');this.fromBufferGeometry(new TorusKnotBufferGeometry(radius,tube,tubularSegments,radialSegments,p,q));this.mergeVertices();}}class TubeBufferGeometry extends BufferGeometry{constructor(path){var tubularSegments=arguments.length>1&&arguments[1]!==undefined?arguments[1]:64;var radius=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var radialSegments=arguments.length>3&&arguments[3]!==undefined?arguments[3]:8;var closed=arguments.length>4&&arguments[4]!==undefined?arguments[4]:false;super();this.type='TubeBufferGeometry';this.parameters={path:path,tubularSegments:tubularSegments,radius:radius,radialSegments:radialSegments,closed:closed};var frames=path.computeFrenetFrames(tubularSegments,closed);// expose internals
  4103. this.tangents=frames.tangents;this.normals=frames.normals;this.binormals=frames.binormals;// helper variables
  4104. var vertex=new Vector3();var normal=new Vector3();var uv=new Vector2();var P=new Vector3();// buffer
  4105. var vertices=[];var normals=[];var uvs=[];var indices=[];// create buffer data
  4106. generateBufferData();// build geometry
  4107. this.setIndex(indices);this.setAttribute('position',new Float32BufferAttribute(vertices,3));this.setAttribute('normal',new Float32BufferAttribute(normals,3));this.setAttribute('uv',new Float32BufferAttribute(uvs,2));// functions
  4108. function generateBufferData(){for(var _i236=0;_i236<tubularSegments;_i236++){generateSegment(_i236);}// if the geometry is not closed, generate the last row of vertices and normals
  4109. // at the regular position on the given path
  4110. //
  4111. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  4112. generateSegment(closed===false?tubularSegments:0);// uvs are generated in a separate function.
  4113. // this makes it easy compute correct values for closed geometries
  4114. generateUVs();// finally create faces
  4115. generateIndices();}function generateSegment(i){// we use getPointAt to sample evenly distributed points from the given path
  4116. P=path.getPointAt(i/tubularSegments,P);// retrieve corresponding normal and binormal
  4117. var N=frames.normals[i];var B=frames.binormals[i];// generate normals and vertices for the current segment
  4118. for(var j=0;j<=radialSegments;j++){var v=j/radialSegments*Math.PI*2;var sin=Math.sin(v);var cos=-Math.cos(v);// normal
  4119. normal.x=cos*N.x+sin*B.x;normal.y=cos*N.y+sin*B.y;normal.z=cos*N.z+sin*B.z;normal.normalize();normals.push(normal.x,normal.y,normal.z);// vertex
  4120. vertex.x=P.x+radius*normal.x;vertex.y=P.y+radius*normal.y;vertex.z=P.z+radius*normal.z;vertices.push(vertex.x,vertex.y,vertex.z);}}function generateIndices(){for(var j=1;j<=tubularSegments;j++){for(var _i237=1;_i237<=radialSegments;_i237++){var a=(radialSegments+1)*(j-1)+(_i237-1);var b=(radialSegments+1)*j+(_i237-1);var c=(radialSegments+1)*j+_i237;var d=(radialSegments+1)*(j-1)+_i237;// faces
  4121. indices.push(a,b,d);indices.push(b,c,d);}}}function generateUVs(){for(var _i238=0;_i238<=tubularSegments;_i238++){for(var j=0;j<=radialSegments;j++){uv.x=_i238/tubularSegments;uv.y=j/radialSegments;uvs.push(uv.x,uv.y);}}}}toJSON(){var data=BufferGeometry.prototype.toJSON.call(this);data.path=this.parameters.path.toJSON();return data;}}class TubeGeometry extends Geometry{constructor(path,tubularSegments,radius,radialSegments,closed,taper){super();this.type='TubeGeometry';this.parameters={path:path,tubularSegments:tubularSegments,radius:radius,radialSegments:radialSegments,closed:closed};if(taper!==undefined)console.warn('THREE.TubeGeometry: taper has been removed.');var bufferGeometry=new TubeBufferGeometry(path,tubularSegments,radius,radialSegments,closed);// expose internals
  4122. this.tangents=bufferGeometry.tangents;this.normals=bufferGeometry.normals;this.binormals=bufferGeometry.binormals;// create geometry
  4123. this.fromBufferGeometry(bufferGeometry);this.mergeVertices();}}class WireframeGeometry extends BufferGeometry{constructor(geometry){super();this.type='WireframeGeometry';// buffer
  4124. var vertices=[];// helper variables
  4125. var edge=[0,0],edges={};var keys=['a','b','c'];// different logic for Geometry and BufferGeometry
  4126. if(geometry&&geometry.isGeometry){// create a data structure that contains all edges without duplicates
  4127. var faces=geometry.faces;for(var _i239=0,l=faces.length;_i239<l;_i239++){var face=faces[_i239];for(var j=0;j<3;j++){var edge1=face[keys[j]];var edge2=face[keys[(j+1)%3]];edge[0]=Math.min(edge1,edge2);// sorting prevents duplicates
  4128. edge[1]=Math.max(edge1,edge2);var key=edge[0]+','+edge[1];if(edges[key]===undefined){edges[key]={index1:edge[0],index2:edge[1]};}}}// generate vertices
  4129. for(var _key3 in edges){var e=edges[_key3];var vertex=geometry.vertices[e.index1];vertices.push(vertex.x,vertex.y,vertex.z);vertex=geometry.vertices[e.index2];vertices.push(vertex.x,vertex.y,vertex.z);}}else if(geometry&&geometry.isBufferGeometry){var _vertex=new Vector3();if(geometry.index!==null){// indexed BufferGeometry
  4130. var position=geometry.attributes.position;var indices=geometry.index;var groups=geometry.groups;if(groups.length===0){groups=[{start:0,count:indices.count,materialIndex:0}];}// create a data structure that contains all eges without duplicates
  4131. for(var o=0,ol=groups.length;o<ol;++o){var group=groups[o];var start=group.start;var count=group.count;for(var _i240=start,_l13=start+count;_i240<_l13;_i240+=3){for(var _j20=0;_j20<3;_j20++){var _edge=indices.getX(_i240+_j20);var _edge3=indices.getX(_i240+(_j20+1)%3);edge[0]=Math.min(_edge,_edge3);// sorting prevents duplicates
  4132. edge[1]=Math.max(_edge,_edge3);var _key4=edge[0]+','+edge[1];if(edges[_key4]===undefined){edges[_key4]={index1:edge[0],index2:edge[1]};}}}}// generate vertices
  4133. for(var _key5 in edges){var _e=edges[_key5];_vertex.fromBufferAttribute(position,_e.index1);vertices.push(_vertex.x,_vertex.y,_vertex.z);_vertex.fromBufferAttribute(position,_e.index2);vertices.push(_vertex.x,_vertex.y,_vertex.z);}}else {// non-indexed BufferGeometry
  4134. var _position2=geometry.attributes.position;for(var _i241=0,_l14=_position2.count/3;_i241<_l14;_i241++){for(var _j21=0;_j21<3;_j21++){// three edges per triangle, an edge is represented as (index1, index2)
  4135. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  4136. var index1=3*_i241+_j21;_vertex.fromBufferAttribute(_position2,index1);vertices.push(_vertex.x,_vertex.y,_vertex.z);var index2=3*_i241+(_j21+1)%3;_vertex.fromBufferAttribute(_position2,index2);vertices.push(_vertex.x,_vertex.y,_vertex.z);}}}}// build geometry
  4137. this.setAttribute('position',new Float32BufferAttribute(vertices,3));}}var Geometries=/*#__PURE__*/Object.freeze({__proto__:null,BoxGeometry:BoxGeometry,BoxBufferGeometry:BoxBufferGeometry,CircleGeometry:CircleGeometry,CircleBufferGeometry:CircleBufferGeometry,ConeGeometry:ConeGeometry,ConeBufferGeometry:ConeBufferGeometry,CylinderGeometry:CylinderGeometry,CylinderBufferGeometry:CylinderBufferGeometry,DodecahedronGeometry:DodecahedronGeometry,DodecahedronBufferGeometry:DodecahedronBufferGeometry,EdgesGeometry:EdgesGeometry,ExtrudeGeometry:ExtrudeGeometry,ExtrudeBufferGeometry:ExtrudeBufferGeometry,IcosahedronGeometry:IcosahedronGeometry,IcosahedronBufferGeometry:IcosahedronBufferGeometry,LatheGeometry:LatheGeometry,LatheBufferGeometry:LatheBufferGeometry,OctahedronGeometry:OctahedronGeometry,OctahedronBufferGeometry:OctahedronBufferGeometry,ParametricGeometry:ParametricGeometry,ParametricBufferGeometry:ParametricBufferGeometry,PlaneGeometry:PlaneGeometry,PlaneBufferGeometry:PlaneBufferGeometry,PolyhedronGeometry:PolyhedronGeometry,PolyhedronBufferGeometry:PolyhedronBufferGeometry,RingGeometry:RingGeometry,RingBufferGeometry:RingBufferGeometry,ShapeGeometry:ShapeGeometry,ShapeBufferGeometry:ShapeBufferGeometry,SphereGeometry:SphereGeometry,SphereBufferGeometry:SphereBufferGeometry,TetrahedronGeometry:TetrahedronGeometry,TetrahedronBufferGeometry:TetrahedronBufferGeometry,TextGeometry:TextGeometry,TextBufferGeometry:TextBufferGeometry,TorusGeometry:TorusGeometry,TorusBufferGeometry:TorusBufferGeometry,TorusKnotGeometry:TorusKnotGeometry,TorusKnotBufferGeometry:TorusKnotBufferGeometry,TubeGeometry:TubeGeometry,TubeBufferGeometry:TubeBufferGeometry,WireframeGeometry:WireframeGeometry});/**
  4138. * parameters = {
  4139. * color: <THREE.Color>
  4140. * }
  4141. */function ShadowMaterial(parameters){Material.call(this);this.type='ShadowMaterial';this.color=new Color(0x000000);this.transparent=true;this.setValues(parameters);}ShadowMaterial.prototype=Object.create(Material.prototype);ShadowMaterial.prototype.constructor=ShadowMaterial;ShadowMaterial.prototype.isShadowMaterial=true;ShadowMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);return this;};function RawShaderMaterial(parameters){ShaderMaterial.call(this,parameters);this.type='RawShaderMaterial';}RawShaderMaterial.prototype=Object.create(ShaderMaterial.prototype);RawShaderMaterial.prototype.constructor=RawShaderMaterial;RawShaderMaterial.prototype.isRawShaderMaterial=true;/**
  4142. * parameters = {
  4143. * color: <hex>,
  4144. * roughness: <float>,
  4145. * metalness: <float>,
  4146. * opacity: <float>,
  4147. *
  4148. * map: new THREE.Texture( <Image> ),
  4149. *
  4150. * lightMap: new THREE.Texture( <Image> ),
  4151. * lightMapIntensity: <float>
  4152. *
  4153. * aoMap: new THREE.Texture( <Image> ),
  4154. * aoMapIntensity: <float>
  4155. *
  4156. * emissive: <hex>,
  4157. * emissiveIntensity: <float>
  4158. * emissiveMap: new THREE.Texture( <Image> ),
  4159. *
  4160. * bumpMap: new THREE.Texture( <Image> ),
  4161. * bumpScale: <float>,
  4162. *
  4163. * normalMap: new THREE.Texture( <Image> ),
  4164. * normalMapType: THREE.TangentSpaceNormalMap,
  4165. * normalScale: <Vector2>,
  4166. *
  4167. * displacementMap: new THREE.Texture( <Image> ),
  4168. * displacementScale: <float>,
  4169. * displacementBias: <float>,
  4170. *
  4171. * roughnessMap: new THREE.Texture( <Image> ),
  4172. *
  4173. * metalnessMap: new THREE.Texture( <Image> ),
  4174. *
  4175. * alphaMap: new THREE.Texture( <Image> ),
  4176. *
  4177. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  4178. * envMapIntensity: <float>
  4179. *
  4180. * refractionRatio: <float>,
  4181. *
  4182. * wireframe: <boolean>,
  4183. * wireframeLinewidth: <float>,
  4184. *
  4185. * skinning: <bool>,
  4186. * morphTargets: <bool>,
  4187. * morphNormals: <bool>
  4188. * }
  4189. */function MeshStandardMaterial(parameters){Material.call(this);this.defines={'STANDARD':''};this.type='MeshStandardMaterial';this.color=new Color(0xffffff);// diffuse
  4190. this.roughness=1.0;this.metalness=0.0;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.roughnessMap=null;this.metalnessMap=null;this.alphaMap=null;this.envMap=null;this.envMapIntensity=1.0;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.vertexTangents=false;this.setValues(parameters);}MeshStandardMaterial.prototype=Object.create(Material.prototype);MeshStandardMaterial.prototype.constructor=MeshStandardMaterial;MeshStandardMaterial.prototype.isMeshStandardMaterial=true;MeshStandardMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={'STANDARD':''};this.color.copy(source.color);this.roughness=source.roughness;this.metalness=source.metalness;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.roughnessMap=source.roughnessMap;this.metalnessMap=source.metalnessMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.envMapIntensity=source.envMapIntensity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;this.vertexTangents=source.vertexTangents;return this;};/**
  4191. * parameters = {
  4192. * clearcoat: <float>,
  4193. * clearcoatMap: new THREE.Texture( <Image> ),
  4194. * clearcoatRoughness: <float>,
  4195. * clearcoatRoughnessMap: new THREE.Texture( <Image> ),
  4196. * clearcoatNormalScale: <Vector2>,
  4197. * clearcoatNormalMap: new THREE.Texture( <Image> ),
  4198. *
  4199. * reflectivity: <float>,
  4200. * ior: <float>,
  4201. *
  4202. * sheen: <Color>,
  4203. *
  4204. * transmission: <float>,
  4205. * transmissionMap: new THREE.Texture( <Image> )
  4206. * }
  4207. */function MeshPhysicalMaterial(parameters){MeshStandardMaterial.call(this);this.defines={'STANDARD':'','PHYSICAL':''};this.type='MeshPhysicalMaterial';this.clearcoat=0.0;this.clearcoatMap=null;this.clearcoatRoughness=0.0;this.clearcoatRoughnessMap=null;this.clearcoatNormalScale=new Vector2(1,1);this.clearcoatNormalMap=null;this.reflectivity=0.5;// maps to F0 = 0.04
  4208. Object.defineProperty(this,'ior',{get:function get(){return (1+0.4*this.reflectivity)/(1-0.4*this.reflectivity);},set:function set(ior){this.reflectivity=MathUtils.clamp(2.5*(ior-1)/(ior+1),0,1);}});this.sheen=null;// null will disable sheen bsdf
  4209. this.transmission=0.0;this.transmissionMap=null;this.setValues(parameters);}MeshPhysicalMaterial.prototype=Object.create(MeshStandardMaterial.prototype);MeshPhysicalMaterial.prototype.constructor=MeshPhysicalMaterial;MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial=true;MeshPhysicalMaterial.prototype.copy=function(source){MeshStandardMaterial.prototype.copy.call(this,source);this.defines={'STANDARD':'','PHYSICAL':''};this.clearcoat=source.clearcoat;this.clearcoatMap=source.clearcoatMap;this.clearcoatRoughness=source.clearcoatRoughness;this.clearcoatRoughnessMap=source.clearcoatRoughnessMap;this.clearcoatNormalMap=source.clearcoatNormalMap;this.clearcoatNormalScale.copy(source.clearcoatNormalScale);this.reflectivity=source.reflectivity;if(source.sheen){this.sheen=(this.sheen||new Color()).copy(source.sheen);}else {this.sheen=null;}this.transmission=source.transmission;this.transmissionMap=source.transmissionMap;return this;};/**
  4210. * parameters = {
  4211. * color: <hex>,
  4212. * specular: <hex>,
  4213. * shininess: <float>,
  4214. * opacity: <float>,
  4215. *
  4216. * map: new THREE.Texture( <Image> ),
  4217. *
  4218. * lightMap: new THREE.Texture( <Image> ),
  4219. * lightMapIntensity: <float>
  4220. *
  4221. * aoMap: new THREE.Texture( <Image> ),
  4222. * aoMapIntensity: <float>
  4223. *
  4224. * emissive: <hex>,
  4225. * emissiveIntensity: <float>
  4226. * emissiveMap: new THREE.Texture( <Image> ),
  4227. *
  4228. * bumpMap: new THREE.Texture( <Image> ),
  4229. * bumpScale: <float>,
  4230. *
  4231. * normalMap: new THREE.Texture( <Image> ),
  4232. * normalMapType: THREE.TangentSpaceNormalMap,
  4233. * normalScale: <Vector2>,
  4234. *
  4235. * displacementMap: new THREE.Texture( <Image> ),
  4236. * displacementScale: <float>,
  4237. * displacementBias: <float>,
  4238. *
  4239. * specularMap: new THREE.Texture( <Image> ),
  4240. *
  4241. * alphaMap: new THREE.Texture( <Image> ),
  4242. *
  4243. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  4244. * combine: THREE.MultiplyOperation,
  4245. * reflectivity: <float>,
  4246. * refractionRatio: <float>,
  4247. *
  4248. * wireframe: <boolean>,
  4249. * wireframeLinewidth: <float>,
  4250. *
  4251. * skinning: <bool>,
  4252. * morphTargets: <bool>,
  4253. * morphNormals: <bool>
  4254. * }
  4255. */function MeshPhongMaterial(parameters){Material.call(this);this.type='MeshPhongMaterial';this.color=new Color(0xffffff);// diffuse
  4256. this.specular=new Color(0x111111);this.shininess=30;this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshPhongMaterial.prototype=Object.create(Material.prototype);MeshPhongMaterial.prototype.constructor=MeshPhongMaterial;MeshPhongMaterial.prototype.isMeshPhongMaterial=true;MeshPhongMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.specular.copy(source.specular);this.shininess=source.shininess;this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/**
  4257. * parameters = {
  4258. * color: <hex>,
  4259. *
  4260. * map: new THREE.Texture( <Image> ),
  4261. * gradientMap: new THREE.Texture( <Image> ),
  4262. *
  4263. * lightMap: new THREE.Texture( <Image> ),
  4264. * lightMapIntensity: <float>
  4265. *
  4266. * aoMap: new THREE.Texture( <Image> ),
  4267. * aoMapIntensity: <float>
  4268. *
  4269. * emissive: <hex>,
  4270. * emissiveIntensity: <float>
  4271. * emissiveMap: new THREE.Texture( <Image> ),
  4272. *
  4273. * bumpMap: new THREE.Texture( <Image> ),
  4274. * bumpScale: <float>,
  4275. *
  4276. * normalMap: new THREE.Texture( <Image> ),
  4277. * normalMapType: THREE.TangentSpaceNormalMap,
  4278. * normalScale: <Vector2>,
  4279. *
  4280. * displacementMap: new THREE.Texture( <Image> ),
  4281. * displacementScale: <float>,
  4282. * displacementBias: <float>,
  4283. *
  4284. * alphaMap: new THREE.Texture( <Image> ),
  4285. *
  4286. * wireframe: <boolean>,
  4287. * wireframeLinewidth: <float>,
  4288. *
  4289. * skinning: <bool>,
  4290. * morphTargets: <bool>,
  4291. * morphNormals: <bool>
  4292. * }
  4293. */function MeshToonMaterial(parameters){Material.call(this);this.defines={'TOON':''};this.type='MeshToonMaterial';this.color=new Color(0xffffff);this.map=null;this.gradientMap=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshToonMaterial.prototype=Object.create(Material.prototype);MeshToonMaterial.prototype.constructor=MeshToonMaterial;MeshToonMaterial.prototype.isMeshToonMaterial=true;MeshToonMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.gradientMap=source.gradientMap;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/**
  4294. * parameters = {
  4295. * opacity: <float>,
  4296. *
  4297. * bumpMap: new THREE.Texture( <Image> ),
  4298. * bumpScale: <float>,
  4299. *
  4300. * normalMap: new THREE.Texture( <Image> ),
  4301. * normalMapType: THREE.TangentSpaceNormalMap,
  4302. * normalScale: <Vector2>,
  4303. *
  4304. * displacementMap: new THREE.Texture( <Image> ),
  4305. * displacementScale: <float>,
  4306. * displacementBias: <float>,
  4307. *
  4308. * wireframe: <boolean>,
  4309. * wireframeLinewidth: <float>
  4310. *
  4311. * skinning: <bool>,
  4312. * morphTargets: <bool>,
  4313. * morphNormals: <bool>
  4314. * }
  4315. */function MeshNormalMaterial(parameters){Material.call(this);this.type='MeshNormalMaterial';this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.wireframe=false;this.wireframeLinewidth=1;this.fog=false;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshNormalMaterial.prototype=Object.create(Material.prototype);MeshNormalMaterial.prototype.constructor=MeshNormalMaterial;MeshNormalMaterial.prototype.isMeshNormalMaterial=true;MeshNormalMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/**
  4316. * parameters = {
  4317. * color: <hex>,
  4318. * opacity: <float>,
  4319. *
  4320. * map: new THREE.Texture( <Image> ),
  4321. *
  4322. * lightMap: new THREE.Texture( <Image> ),
  4323. * lightMapIntensity: <float>
  4324. *
  4325. * aoMap: new THREE.Texture( <Image> ),
  4326. * aoMapIntensity: <float>
  4327. *
  4328. * emissive: <hex>,
  4329. * emissiveIntensity: <float>
  4330. * emissiveMap: new THREE.Texture( <Image> ),
  4331. *
  4332. * specularMap: new THREE.Texture( <Image> ),
  4333. *
  4334. * alphaMap: new THREE.Texture( <Image> ),
  4335. *
  4336. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  4337. * combine: THREE.Multiply,
  4338. * reflectivity: <float>,
  4339. * refractionRatio: <float>,
  4340. *
  4341. * wireframe: <boolean>,
  4342. * wireframeLinewidth: <float>,
  4343. *
  4344. * skinning: <bool>,
  4345. * morphTargets: <bool>,
  4346. * morphNormals: <bool>
  4347. * }
  4348. */function MeshLambertMaterial(parameters){Material.call(this);this.type='MeshLambertMaterial';this.color=new Color(0xffffff);// diffuse
  4349. this.map=null;this.lightMap=null;this.lightMapIntensity=1.0;this.aoMap=null;this.aoMapIntensity=1.0;this.emissive=new Color(0x000000);this.emissiveIntensity=1.0;this.emissiveMap=null;this.specularMap=null;this.alphaMap=null;this.envMap=null;this.combine=MultiplyOperation;this.reflectivity=1;this.refractionRatio=0.98;this.wireframe=false;this.wireframeLinewidth=1;this.wireframeLinecap='round';this.wireframeLinejoin='round';this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshLambertMaterial.prototype=Object.create(Material.prototype);MeshLambertMaterial.prototype.constructor=MeshLambertMaterial;MeshLambertMaterial.prototype.isMeshLambertMaterial=true;MeshLambertMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.color.copy(source.color);this.map=source.map;this.lightMap=source.lightMap;this.lightMapIntensity=source.lightMapIntensity;this.aoMap=source.aoMap;this.aoMapIntensity=source.aoMapIntensity;this.emissive.copy(source.emissive);this.emissiveMap=source.emissiveMap;this.emissiveIntensity=source.emissiveIntensity;this.specularMap=source.specularMap;this.alphaMap=source.alphaMap;this.envMap=source.envMap;this.combine=source.combine;this.reflectivity=source.reflectivity;this.refractionRatio=source.refractionRatio;this.wireframe=source.wireframe;this.wireframeLinewidth=source.wireframeLinewidth;this.wireframeLinecap=source.wireframeLinecap;this.wireframeLinejoin=source.wireframeLinejoin;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/**
  4350. * parameters = {
  4351. * color: <hex>,
  4352. * opacity: <float>,
  4353. *
  4354. * matcap: new THREE.Texture( <Image> ),
  4355. *
  4356. * map: new THREE.Texture( <Image> ),
  4357. *
  4358. * bumpMap: new THREE.Texture( <Image> ),
  4359. * bumpScale: <float>,
  4360. *
  4361. * normalMap: new THREE.Texture( <Image> ),
  4362. * normalMapType: THREE.TangentSpaceNormalMap,
  4363. * normalScale: <Vector2>,
  4364. *
  4365. * displacementMap: new THREE.Texture( <Image> ),
  4366. * displacementScale: <float>,
  4367. * displacementBias: <float>,
  4368. *
  4369. * alphaMap: new THREE.Texture( <Image> ),
  4370. *
  4371. * skinning: <bool>,
  4372. * morphTargets: <bool>,
  4373. * morphNormals: <bool>
  4374. * }
  4375. */function MeshMatcapMaterial(parameters){Material.call(this);this.defines={'MATCAP':''};this.type='MeshMatcapMaterial';this.color=new Color(0xffffff);// diffuse
  4376. this.matcap=null;this.map=null;this.bumpMap=null;this.bumpScale=1;this.normalMap=null;this.normalMapType=TangentSpaceNormalMap;this.normalScale=new Vector2(1,1);this.displacementMap=null;this.displacementScale=1;this.displacementBias=0;this.alphaMap=null;this.skinning=false;this.morphTargets=false;this.morphNormals=false;this.setValues(parameters);}MeshMatcapMaterial.prototype=Object.create(Material.prototype);MeshMatcapMaterial.prototype.constructor=MeshMatcapMaterial;MeshMatcapMaterial.prototype.isMeshMatcapMaterial=true;MeshMatcapMaterial.prototype.copy=function(source){Material.prototype.copy.call(this,source);this.defines={'MATCAP':''};this.color.copy(source.color);this.matcap=source.matcap;this.map=source.map;this.bumpMap=source.bumpMap;this.bumpScale=source.bumpScale;this.normalMap=source.normalMap;this.normalMapType=source.normalMapType;this.normalScale.copy(source.normalScale);this.displacementMap=source.displacementMap;this.displacementScale=source.displacementScale;this.displacementBias=source.displacementBias;this.alphaMap=source.alphaMap;this.skinning=source.skinning;this.morphTargets=source.morphTargets;this.morphNormals=source.morphNormals;return this;};/**
  4377. * parameters = {
  4378. * color: <hex>,
  4379. * opacity: <float>,
  4380. *
  4381. * linewidth: <float>,
  4382. *
  4383. * scale: <float>,
  4384. * dashSize: <float>,
  4385. * gapSize: <float>
  4386. * }
  4387. */function LineDashedMaterial(parameters){LineBasicMaterial.call(this);this.type='LineDashedMaterial';this.scale=1;this.dashSize=3;this.gapSize=1;this.setValues(parameters);}LineDashedMaterial.prototype=Object.create(LineBasicMaterial.prototype);LineDashedMaterial.prototype.constructor=LineDashedMaterial;LineDashedMaterial.prototype.isLineDashedMaterial=true;LineDashedMaterial.prototype.copy=function(source){LineBasicMaterial.prototype.copy.call(this,source);this.scale=source.scale;this.dashSize=source.dashSize;this.gapSize=source.gapSize;return this;};var Materials=/*#__PURE__*/Object.freeze({__proto__:null,ShadowMaterial:ShadowMaterial,SpriteMaterial:SpriteMaterial,RawShaderMaterial:RawShaderMaterial,ShaderMaterial:ShaderMaterial,PointsMaterial:PointsMaterial,MeshPhysicalMaterial:MeshPhysicalMaterial,MeshStandardMaterial:MeshStandardMaterial,MeshPhongMaterial:MeshPhongMaterial,MeshToonMaterial:MeshToonMaterial,MeshNormalMaterial:MeshNormalMaterial,MeshLambertMaterial:MeshLambertMaterial,MeshDepthMaterial:MeshDepthMaterial,MeshDistanceMaterial:MeshDistanceMaterial,MeshBasicMaterial:MeshBasicMaterial,MeshMatcapMaterial:MeshMatcapMaterial,LineDashedMaterial:LineDashedMaterial,LineBasicMaterial:LineBasicMaterial,Material:Material});var AnimationUtils={// same as Array.prototype.slice, but also works on typed arrays
  4388. arraySlice:function arraySlice(array,from,to){if(AnimationUtils.isTypedArray(array)){// in ios9 array.subarray(from, undefined) will return empty array
  4389. // but array.subarray(from) or array.subarray(from, len) is correct
  4390. return new array.constructor(array.subarray(from,to!==undefined?to:array.length));}return array.slice(from,to);},// converts an array to a specific type
  4391. convertArray:function convertArray(array,type,forceClone){if(!array||// let 'undefined' and 'null' pass
  4392. !forceClone&&array.constructor===type)return array;if(typeof type.BYTES_PER_ELEMENT==='number'){return new type(array);// create typed array
  4393. }return Array.prototype.slice.call(array);// create Array
  4394. },isTypedArray:function isTypedArray(object){return ArrayBuffer.isView(object)&&!(object instanceof DataView);},// returns an array by which times and values can be sorted
  4395. getKeyframeOrder:function getKeyframeOrder(times){function compareTime(i,j){return times[i]-times[j];}var n=times.length;var result=new Array(n);for(var _i242=0;_i242!==n;++_i242)result[_i242]=_i242;result.sort(compareTime);return result;},// uses the array previously returned by 'getKeyframeOrder' to sort data
  4396. sortedArray:function sortedArray(values,stride,order){var nValues=values.length;var result=new values.constructor(nValues);for(var _i243=0,dstOffset=0;dstOffset!==nValues;++_i243){var srcOffset=order[_i243]*stride;for(var j=0;j!==stride;++j){result[dstOffset++]=values[srcOffset+j];}}return result;},// function for parsing AOS keyframe formats
  4397. flattenJSON:function flattenJSON(jsonKeys,times,values,valuePropertyName){var i=1,key=jsonKeys[0];while(key!==undefined&&key[valuePropertyName]===undefined){key=jsonKeys[i++];}if(key===undefined)return;// no data
  4398. var value=key[valuePropertyName];if(value===undefined)return;// no data
  4399. if(Array.isArray(value)){do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push.apply(values,value);// push all elements
  4400. }key=jsonKeys[i++];}while(key!==undefined);}else if(value.toArray!==undefined){// ...assume THREE.Math-ish
  4401. do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);value.toArray(values,values.length);}key=jsonKeys[i++];}while(key!==undefined);}else {// otherwise push as-is
  4402. do{value=key[valuePropertyName];if(value!==undefined){times.push(key.time);values.push(value);}key=jsonKeys[i++];}while(key!==undefined);}},subclip:function subclip(sourceClip,name,startFrame,endFrame){var fps=arguments.length>4&&arguments[4]!==undefined?arguments[4]:30;var clip=sourceClip.clone();clip.name=name;var tracks=[];for(var _i244=0;_i244<clip.tracks.length;++_i244){var track=clip.tracks[_i244];var valueSize=track.getValueSize();var times=[];var values=[];for(var j=0;j<track.times.length;++j){var frame=track.times[j]*fps;if(frame<startFrame||frame>=endFrame)continue;times.push(track.times[j]);for(var k=0;k<valueSize;++k){values.push(track.values[j*valueSize+k]);}}if(times.length===0)continue;track.times=AnimationUtils.convertArray(times,track.times.constructor);track.values=AnimationUtils.convertArray(values,track.values.constructor);tracks.push(track);}clip.tracks=tracks;// find minimum .times value across all tracks in the trimmed clip
  4403. var minStartTime=Infinity;for(var _i245=0;_i245<clip.tracks.length;++_i245){if(minStartTime>clip.tracks[_i245].times[0]){minStartTime=clip.tracks[_i245].times[0];}}// shift all tracks such that clip begins at t=0
  4404. for(var _i246=0;_i246<clip.tracks.length;++_i246){clip.tracks[_i246].shift(-1*minStartTime);}clip.resetDuration();return clip;},makeClipAdditive:function makeClipAdditive(targetClip){var referenceFrame=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var referenceClip=arguments.length>2&&arguments[2]!==undefined?arguments[2]:targetClip;var fps=arguments.length>3&&arguments[3]!==undefined?arguments[3]:30;if(fps<=0)fps=30;var numTracks=referenceClip.tracks.length;var referenceTime=referenceFrame/fps;// Make each track's values relative to the values at the reference frame
  4405. var _loop=function _loop(){var referenceTrack=referenceClip.tracks[_i247];var referenceTrackType=referenceTrack.ValueTypeName;// Skip this track if it's non-numeric
  4406. if(referenceTrackType==='bool'||referenceTrackType==='string')return 0;// continue
  4407. // Find the track in the target clip whose name and type matches the reference track
  4408. var targetTrack=targetClip.tracks.find(function(track){return track.name===referenceTrack.name&&track.ValueTypeName===referenceTrackType;});if(targetTrack===undefined)return 0;// continue
  4409. var referenceOffset=0;var referenceValueSize=referenceTrack.getValueSize();if(referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline){referenceOffset=referenceValueSize/3;}var targetOffset=0;var targetValueSize=targetTrack.getValueSize();if(targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline){targetOffset=targetValueSize/3;}var lastIndex=referenceTrack.times.length-1;var referenceValue;// Find the value to subtract out of the track
  4410. if(referenceTime<=referenceTrack.times[0]){// Reference frame is earlier than the first keyframe, so just use the first keyframe
  4411. var startIndex=referenceOffset;var endIndex=referenceValueSize-referenceOffset;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,startIndex,endIndex);}else if(referenceTime>=referenceTrack.times[lastIndex]){// Reference frame is after the last keyframe, so just use the last keyframe
  4412. var _startIndex=lastIndex*referenceValueSize+referenceOffset;var _endIndex=_startIndex+referenceValueSize-referenceOffset;referenceValue=AnimationUtils.arraySlice(referenceTrack.values,_startIndex,_endIndex);}else {// Interpolate to the reference value
  4413. var interpolant=referenceTrack.createInterpolant();var _startIndex2=referenceOffset;var _endIndex2=referenceValueSize-referenceOffset;interpolant.evaluate(referenceTime);referenceValue=AnimationUtils.arraySlice(interpolant.resultBuffer,_startIndex2,_endIndex2);}// Conjugate the quaternion
  4414. if(referenceTrackType==='quaternion'){var referenceQuat=new Quaternion().fromArray(referenceValue).normalize().conjugate();referenceQuat.toArray(referenceValue);}// Subtract the reference value from all of the track values
  4415. var numTimes=targetTrack.times.length;for(var j=0;j<numTimes;++j){var valueStart=j*targetValueSize+targetOffset;if(referenceTrackType==='quaternion'){// Multiply the conjugate for quaternion track types
  4416. Quaternion.multiplyQuaternionsFlat(targetTrack.values,valueStart,referenceValue,0,targetTrack.values,valueStart);}else {var valueEnd=targetValueSize-targetOffset*2;// Subtract each value for all other numeric track types
  4417. for(var k=0;k<valueEnd;++k){targetTrack.values[valueStart+k]-=referenceValue[k];}}}},_ret;for(var _i247=0;_i247<numTracks;++_i247){_ret=_loop();if(_ret===0)continue;}targetClip.blendMode=AdditiveAnimationBlendMode;return targetClip;}};/**
  4418. * Abstract base class of interpolants over parametric samples.
  4419. *
  4420. * The parameter domain is one dimensional, typically the time or a path
  4421. * along a curve defined by the data.
  4422. *
  4423. * The sample values can have any dimensionality and derived classes may
  4424. * apply special interpretations to the data.
  4425. *
  4426. * This class provides the interval seek in a Template Method, deferring
  4427. * the actual interpolation to derived classes.
  4428. *
  4429. * Time complexity is O(1) for linear access crossing at most two points
  4430. * and O(log N) for random access, where N is the number of positions.
  4431. *
  4432. * References:
  4433. *
  4434. * http://www.oodesign.com/template-method-pattern.html
  4435. *
  4436. */function Interpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){this.parameterPositions=parameterPositions;this._cachedIndex=0;this.resultBuffer=resultBuffer!==undefined?resultBuffer:new sampleValues.constructor(sampleSize);this.sampleValues=sampleValues;this.valueSize=sampleSize;}Object.assign(Interpolant.prototype,{evaluate:function evaluate(t){var pp=this.parameterPositions;var i1=this._cachedIndex,t1=pp[i1],t0=pp[i1-1];validate_interval:{seek:{var right;linear_scan:{//- See http://jsperf.com/comparison-to-undefined/3
  4437. //- slower code:
  4438. //-
  4439. //- if ( t >= t1 || t1 === undefined ) {
  4440. forward_scan:if(!(t<t1)){for(var giveUpAt=i1+2;;){if(t1===undefined){if(t<t0)break forward_scan;// after end
  4441. i1=pp.length;this._cachedIndex=i1;return this.afterEnd_(i1-1,t,t0);}if(i1===giveUpAt)break;// this loop
  4442. t0=t1;t1=pp[++i1];if(t<t1){// we have arrived at the sought interval
  4443. break seek;}}// prepare binary search on the right side of the index
  4444. right=pp.length;break linear_scan;}//- slower code:
  4445. //- if ( t < t0 || t0 === undefined ) {
  4446. if(!(t>=t0)){// looping?
  4447. var t1global=pp[1];if(t<t1global){i1=2;// + 1, using the scan for the details
  4448. t0=t1global;}// linear reverse scan
  4449. for(var _giveUpAt=i1-2;;){if(t0===undefined){// before start
  4450. this._cachedIndex=0;return this.beforeStart_(0,t,t1);}if(i1===_giveUpAt)break;// this loop
  4451. t1=t0;t0=pp[--i1-1];if(t>=t0){// we have arrived at the sought interval
  4452. break seek;}}// prepare binary search on the left side of the index
  4453. right=i1;i1=0;break linear_scan;}// the interval is valid
  4454. break validate_interval;}// linear scan
  4455. // binary search
  4456. while(i1<right){var mid=i1+right>>>1;if(t<pp[mid]){right=mid;}else {i1=mid+1;}}t1=pp[i1];t0=pp[i1-1];// check boundary cases, again
  4457. if(t0===undefined){this._cachedIndex=0;return this.beforeStart_(0,t,t1);}if(t1===undefined){i1=pp.length;this._cachedIndex=i1;return this.afterEnd_(i1-1,t0,t);}}// seek
  4458. this._cachedIndex=i1;this.intervalChanged_(i1,t0,t1);}// validate_interval
  4459. return this.interpolate_(i1,t0,t,t1);},settings:null,// optional, subclass-specific settings structure
  4460. // Note: The indirection allows central control of many interpolants.
  4461. // --- Protected interface
  4462. DefaultSettings_:{},getSettings_:function getSettings_(){return this.settings||this.DefaultSettings_;},copySampleValue_:function copySampleValue_(index){// copies a sample value to the result buffer
  4463. var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset=index*stride;for(var _i248=0;_i248!==stride;++_i248){result[_i248]=values[offset+_i248];}return result;},// Template methods for derived classes:
  4464. interpolate_:function interpolate_(/* i1, t0, t, t1 */){throw new Error('call to abstract method');// implementations shall return this.resultBuffer
  4465. },intervalChanged_:function intervalChanged_(/* i1, t0, t1 */){// empty
  4466. }});// DECLARE ALIAS AFTER assign prototype
  4467. Object.assign(Interpolant.prototype,{//( 0, t, t0 ), returns this.resultBuffer
  4468. beforeStart_:Interpolant.prototype.copySampleValue_,//( N-1, tN-1, t ), returns this.resultBuffer
  4469. afterEnd_:Interpolant.prototype.copySampleValue_});/**
  4470. * Fast and simple cubic spline interpolant.
  4471. *
  4472. * It was derived from a Hermitian construction setting the first derivative
  4473. * at each sample position to the linear slope between neighboring positions
  4474. * over their parameter interval.
  4475. */function CubicInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);this._weightPrev=-0;this._offsetPrev=-0;this._weightNext=-0;this._offsetNext=-0;}CubicInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:CubicInterpolant,DefaultSettings_:{endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding},intervalChanged_:function intervalChanged_(i1,t0,t1){var pp=this.parameterPositions;var iPrev=i1-2,iNext=i1+1,tPrev=pp[iPrev],tNext=pp[iNext];if(tPrev===undefined){switch(this.getSettings_().endingStart){case ZeroSlopeEnding:// f'(t0) = 0
  4476. iPrev=i1;tPrev=2*t0-t1;break;case WrapAroundEnding:// use the other end of the curve
  4477. iPrev=pp.length-2;tPrev=t0+pp[iPrev]-pp[iPrev+1];break;default:// ZeroCurvatureEnding
  4478. // f''(t0) = 0 a.k.a. Natural Spline
  4479. iPrev=i1;tPrev=t1;}}if(tNext===undefined){switch(this.getSettings_().endingEnd){case ZeroSlopeEnding:// f'(tN) = 0
  4480. iNext=i1;tNext=2*t1-t0;break;case WrapAroundEnding:// use the other end of the curve
  4481. iNext=1;tNext=t1+pp[1]-pp[0];break;default:// ZeroCurvatureEnding
  4482. // f''(tN) = 0, a.k.a. Natural Spline
  4483. iNext=i1-1;tNext=t0;}}var halfDt=(t1-t0)*0.5,stride=this.valueSize;this._weightPrev=halfDt/(t0-tPrev);this._weightNext=halfDt/(tNext-t1);this._offsetPrev=iPrev*stride;this._offsetNext=iNext*stride;},interpolate_:function interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,o1=i1*stride,o0=o1-stride,oP=this._offsetPrev,oN=this._offsetNext,wP=this._weightPrev,wN=this._weightNext,p=(t-t0)/(t1-t0),pp=p*p,ppp=pp*p;// evaluate polynomials
  4484. var sP=-wP*ppp+2*wP*pp-wP*p;var s0=(1+wP)*ppp+(-1.5-2*wP)*pp+(-0.5+wP)*p+1;var s1=(-1-wN)*ppp+(1.5+wN)*pp+0.5*p;var sN=wN*ppp-wN*pp;// combine data linearly
  4485. for(var _i249=0;_i249!==stride;++_i249){result[_i249]=sP*values[oP+_i249]+s0*values[o0+_i249]+s1*values[o1+_i249]+sN*values[oN+_i249];}return result;}});function LinearInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}LinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:LinearInterpolant,interpolate_:function interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,offset1=i1*stride,offset0=offset1-stride,weight1=(t-t0)/(t1-t0),weight0=1-weight1;for(var _i250=0;_i250!==stride;++_i250){result[_i250]=values[offset0+_i250]*weight0+values[offset1+_i250]*weight1;}return result;}});/**
  4486. *
  4487. * Interpolant that evaluates to the sample value at the position preceeding
  4488. * the parameter.
  4489. */function DiscreteInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}DiscreteInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:DiscreteInterpolant,interpolate_:function interpolate_(i1/*, t0, t, t1 */){return this.copySampleValue_(i1-1);}});function KeyframeTrack(name,times,values,interpolation){if(name===undefined)throw new Error('THREE.KeyframeTrack: track name is undefined');if(times===undefined||times.length===0)throw new Error('THREE.KeyframeTrack: no keyframes in track named '+name);this.name=name;this.times=AnimationUtils.convertArray(times,this.TimeBufferType);this.values=AnimationUtils.convertArray(values,this.ValueBufferType);this.setInterpolation(interpolation||this.DefaultInterpolation);}// Static methods
  4490. Object.assign(KeyframeTrack,{// Serialization (in static context, because of constructor invocation
  4491. // and automatic invocation of .toJSON):
  4492. toJSON:function toJSON(track){var trackType=track.constructor;var json;// derived classes can define a static toJSON method
  4493. if(trackType.toJSON!==undefined){json=trackType.toJSON(track);}else {// by default, we assume the data can be serialized as-is
  4494. json={'name':track.name,'times':AnimationUtils.convertArray(track.times,Array),'values':AnimationUtils.convertArray(track.values,Array)};var interpolation=track.getInterpolation();if(interpolation!==track.DefaultInterpolation){json.interpolation=interpolation;}}json.type=track.ValueTypeName;// mandatory
  4495. return json;}});Object.assign(KeyframeTrack.prototype,{constructor:KeyframeTrack,TimeBufferType:Float32Array,ValueBufferType:Float32Array,DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodDiscrete:function InterpolantFactoryMethodDiscrete(result){return new DiscreteInterpolant(this.times,this.values,this.getValueSize(),result);},InterpolantFactoryMethodLinear:function InterpolantFactoryMethodLinear(result){return new LinearInterpolant(this.times,this.values,this.getValueSize(),result);},InterpolantFactoryMethodSmooth:function InterpolantFactoryMethodSmooth(result){return new CubicInterpolant(this.times,this.values,this.getValueSize(),result);},setInterpolation:function setInterpolation(interpolation){var factoryMethod;switch(interpolation){case InterpolateDiscrete:factoryMethod=this.InterpolantFactoryMethodDiscrete;break;case InterpolateLinear:factoryMethod=this.InterpolantFactoryMethodLinear;break;case InterpolateSmooth:factoryMethod=this.InterpolantFactoryMethodSmooth;break;}if(factoryMethod===undefined){var message='unsupported interpolation for '+this.ValueTypeName+' keyframe track named '+this.name;if(this.createInterpolant===undefined){// fall back to default, unless the default itself is messed up
  4496. if(interpolation!==this.DefaultInterpolation){this.setInterpolation(this.DefaultInterpolation);}else {throw new Error(message);// fatal, in this case
  4497. }}console.warn('THREE.KeyframeTrack:',message);return this;}this.createInterpolant=factoryMethod;return this;},getInterpolation:function getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return InterpolateDiscrete;case this.InterpolantFactoryMethodLinear:return InterpolateLinear;case this.InterpolantFactoryMethodSmooth:return InterpolateSmooth;}},getValueSize:function getValueSize(){return this.values.length/this.times.length;},// move all keyframes either forwards or backwards in time
  4498. shift:function shift(timeOffset){if(timeOffset!==0.0){var times=this.times;for(var _i251=0,n=times.length;_i251!==n;++_i251){times[_i251]+=timeOffset;}}return this;},// scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  4499. scale:function scale(timeScale){if(timeScale!==1.0){var times=this.times;for(var _i252=0,n=times.length;_i252!==n;++_i252){times[_i252]*=timeScale;}}return this;},// removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  4500. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  4501. trim:function trim(startTime,endTime){var times=this.times,nKeys=times.length;var from=0,to=nKeys-1;while(from!==nKeys&&times[from]<startTime){++from;}while(to!==-1&&times[to]>endTime){--to;}++to;// inclusive -> exclusive bound
  4502. if(from!==0||to!==nKeys){// empty tracks are forbidden, so keep at least one keyframe
  4503. if(from>=to){to=Math.max(to,1);from=to-1;}var stride=this.getValueSize();this.times=AnimationUtils.arraySlice(times,from,to);this.values=AnimationUtils.arraySlice(this.values,from*stride,to*stride);}return this;},// ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  4504. validate:function validate(){var valid=true;var valueSize=this.getValueSize();if(valueSize-Math.floor(valueSize)!==0){console.error('THREE.KeyframeTrack: Invalid value size in track.',this);valid=false;}var times=this.times,values=this.values,nKeys=times.length;if(nKeys===0){console.error('THREE.KeyframeTrack: Track is empty.',this);valid=false;}var prevTime=null;for(var _i253=0;_i253!==nKeys;_i253++){var currTime=times[_i253];if(typeof currTime==='number'&&isNaN(currTime)){console.error('THREE.KeyframeTrack: Time is not a valid number.',this,_i253,currTime);valid=false;break;}if(prevTime!==null&&prevTime>currTime){console.error('THREE.KeyframeTrack: Out of order keys.',this,_i253,currTime,prevTime);valid=false;break;}prevTime=currTime;}if(values!==undefined){if(AnimationUtils.isTypedArray(values)){for(var _i254=0,n=values.length;_i254!==n;++_i254){var value=values[_i254];if(isNaN(value)){console.error('THREE.KeyframeTrack: Value is not a valid number.',this,_i254,value);valid=false;break;}}}}return valid;},// removes equivalent sequential keys as common in morph target sequences
  4505. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  4506. optimize:function optimize(){// times or values may be shared with other tracks, so overwriting is unsafe
  4507. var times=AnimationUtils.arraySlice(this.times),values=AnimationUtils.arraySlice(this.values),stride=this.getValueSize(),smoothInterpolation=this.getInterpolation()===InterpolateSmooth,lastIndex=times.length-1;var writeIndex=1;for(var _i255=1;_i255<lastIndex;++_i255){var keep=false;var time=times[_i255];var timeNext=times[_i255+1];// remove adjacent keyframes scheduled at the same time
  4508. if(time!==timeNext&&(_i255!==1||time!==time[0])){if(!smoothInterpolation){// remove unnecessary keyframes same as their neighbors
  4509. var offset=_i255*stride,offsetP=offset-stride,offsetN=offset+stride;for(var j=0;j!==stride;++j){var value=values[offset+j];if(value!==values[offsetP+j]||value!==values[offsetN+j]){keep=true;break;}}}else {keep=true;}}// in-place compaction
  4510. if(keep){if(_i255!==writeIndex){times[writeIndex]=times[_i255];var readOffset=_i255*stride,writeOffset=writeIndex*stride;for(var _j22=0;_j22!==stride;++_j22){values[writeOffset+_j22]=values[readOffset+_j22];}}++writeIndex;}}// flush last keyframe (compaction looks ahead)
  4511. if(lastIndex>0){times[writeIndex]=times[lastIndex];for(var _readOffset=lastIndex*stride,_writeOffset=writeIndex*stride,_j23=0;_j23!==stride;++_j23){values[_writeOffset+_j23]=values[_readOffset+_j23];}++writeIndex;}if(writeIndex!==times.length){this.times=AnimationUtils.arraySlice(times,0,writeIndex);this.values=AnimationUtils.arraySlice(values,0,writeIndex*stride);}else {this.times=times;this.values=values;}return this;},clone:function clone(){var times=AnimationUtils.arraySlice(this.times,0);var values=AnimationUtils.arraySlice(this.values,0);var TypedKeyframeTrack=this.constructor;var track=new TypedKeyframeTrack(this.name,times,values);// Interpolant argument to constructor is not saved, so copy the factory method directly.
  4512. track.createInterpolant=this.createInterpolant;return track;}});/**
  4513. * A Track of Boolean keyframe values.
  4514. */function BooleanKeyframeTrack(name,times,values){KeyframeTrack.call(this,name,times,values);}BooleanKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:BooleanKeyframeTrack,ValueTypeName:'bool',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined// Note: Actually this track could have a optimized / compressed
  4515. // representation of a single value and a custom interpolant that
  4516. // computes "firstValue ^ isOdd( index )".
  4517. });/**
  4518. * A Track of keyframe values that represent color.
  4519. */function ColorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}ColorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:ColorKeyframeTrack,ValueTypeName:'color'// ValueBufferType is inherited
  4520. // DefaultInterpolation is inherited
  4521. // Note: Very basic implementation and nothing special yet.
  4522. // However, this is the place for color space parameterization.
  4523. });/**
  4524. * A Track of numeric keyframe values.
  4525. */function NumberKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}NumberKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:NumberKeyframeTrack,ValueTypeName:'number'// ValueBufferType is inherited
  4526. // DefaultInterpolation is inherited
  4527. });/**
  4528. * Spherical linear unit quaternion interpolant.
  4529. */function QuaternionLinearInterpolant(parameterPositions,sampleValues,sampleSize,resultBuffer){Interpolant.call(this,parameterPositions,sampleValues,sampleSize,resultBuffer);}QuaternionLinearInterpolant.prototype=Object.assign(Object.create(Interpolant.prototype),{constructor:QuaternionLinearInterpolant,interpolate_:function interpolate_(i1,t0,t,t1){var result=this.resultBuffer,values=this.sampleValues,stride=this.valueSize,alpha=(t-t0)/(t1-t0);var offset=i1*stride;for(var end=offset+stride;offset!==end;offset+=4){Quaternion.slerpFlat(result,0,values,offset-stride,values,offset,alpha);}return result;}});/**
  4530. * A Track of quaternion keyframe values.
  4531. */function QuaternionKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}QuaternionKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:QuaternionKeyframeTrack,ValueTypeName:'quaternion',// ValueBufferType is inherited
  4532. DefaultInterpolation:InterpolateLinear,InterpolantFactoryMethodLinear:function InterpolantFactoryMethodLinear(result){return new QuaternionLinearInterpolant(this.times,this.values,this.getValueSize(),result);},InterpolantFactoryMethodSmooth:undefined// not yet implemented
  4533. });/**
  4534. * A Track that interpolates Strings
  4535. */function StringKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}StringKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:StringKeyframeTrack,ValueTypeName:'string',ValueBufferType:Array,DefaultInterpolation:InterpolateDiscrete,InterpolantFactoryMethodLinear:undefined,InterpolantFactoryMethodSmooth:undefined});/**
  4536. * A Track of vectored keyframe values.
  4537. */function VectorKeyframeTrack(name,times,values,interpolation){KeyframeTrack.call(this,name,times,values,interpolation);}VectorKeyframeTrack.prototype=Object.assign(Object.create(KeyframeTrack.prototype),{constructor:VectorKeyframeTrack,ValueTypeName:'vector'// ValueBufferType is inherited
  4538. // DefaultInterpolation is inherited
  4539. });function AnimationClip(name){var duration=arguments.length>1&&arguments[1]!==undefined?arguments[1]:-1;var tracks=arguments.length>2?arguments[2]:undefined;var blendMode=arguments.length>3&&arguments[3]!==undefined?arguments[3]:NormalAnimationBlendMode;this.name=name;this.tracks=tracks;this.duration=duration;this.blendMode=blendMode;this.uuid=MathUtils.generateUUID();// this means it should figure out its duration by scanning the tracks
  4540. if(this.duration<0){this.resetDuration();}}function getTrackTypeForValueTypeName(typeName){switch(typeName.toLowerCase()){case'scalar':case'double':case'float':case'number':case'integer':return NumberKeyframeTrack;case'vector':case'vector2':case'vector3':case'vector4':return VectorKeyframeTrack;case'color':return ColorKeyframeTrack;case'quaternion':return QuaternionKeyframeTrack;case'bool':case'boolean':return BooleanKeyframeTrack;case'string':return StringKeyframeTrack;}throw new Error('THREE.KeyframeTrack: Unsupported typeName: '+typeName);}function parseKeyframeTrack(json){if(json.type===undefined){throw new Error('THREE.KeyframeTrack: track type undefined, can not parse');}var trackType=getTrackTypeForValueTypeName(json.type);if(json.times===undefined){var times=[],values=[];AnimationUtils.flattenJSON(json.keys,times,values,'value');json.times=times;json.values=values;}// derived classes can define a static parse method
  4541. if(trackType.parse!==undefined){return trackType.parse(json);}else {// by default, we assume a constructor compatible with the base
  4542. return new trackType(json.name,json.times,json.values,json.interpolation);}}Object.assign(AnimationClip,{parse:function parse(json){var tracks=[],jsonTracks=json.tracks,frameTime=1.0/(json.fps||1.0);for(var _i256=0,n=jsonTracks.length;_i256!==n;++_i256){tracks.push(parseKeyframeTrack(jsonTracks[_i256]).scale(frameTime));}var clip=new AnimationClip(json.name,json.duration,tracks,json.blendMode);clip.uuid=json.uuid;return clip;},toJSON:function toJSON(clip){var tracks=[],clipTracks=clip.tracks;var json={'name':clip.name,'duration':clip.duration,'tracks':tracks,'uuid':clip.uuid,'blendMode':clip.blendMode};for(var _i257=0,n=clipTracks.length;_i257!==n;++_i257){tracks.push(KeyframeTrack.toJSON(clipTracks[_i257]));}return json;},CreateFromMorphTargetSequence:function CreateFromMorphTargetSequence(name,morphTargetSequence,fps,noLoop){var numMorphTargets=morphTargetSequence.length;var tracks=[];for(var _i258=0;_i258<numMorphTargets;_i258++){var times=[];var values=[];times.push((_i258+numMorphTargets-1)%numMorphTargets,_i258,(_i258+1)%numMorphTargets);values.push(0,1,0);var order=AnimationUtils.getKeyframeOrder(times);times=AnimationUtils.sortedArray(times,1,order);values=AnimationUtils.sortedArray(values,1,order);// if there is a key at the first frame, duplicate it as the
  4543. // last frame as well for perfect loop.
  4544. if(!noLoop&&times[0]===0){times.push(numMorphTargets);values.push(values[0]);}tracks.push(new NumberKeyframeTrack('.morphTargetInfluences['+morphTargetSequence[_i258].name+']',times,values).scale(1.0/fps));}return new AnimationClip(name,-1,tracks);},findByName:function findByName(objectOrClipArray,name){var clipArray=objectOrClipArray;if(!Array.isArray(objectOrClipArray)){var o=objectOrClipArray;clipArray=o.geometry&&o.geometry.animations||o.animations;}for(var _i259=0;_i259<clipArray.length;_i259++){if(clipArray[_i259].name===name){return clipArray[_i259];}}return null;},CreateClipsFromMorphTargetSequences:function CreateClipsFromMorphTargetSequences(morphTargets,fps,noLoop){var animationToMorphTargets={};// tested with https://regex101.com/ on trick sequences
  4545. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  4546. var pattern=/^([\w-]*?)([\d]+)$/;// sort morph target names into animation groups based
  4547. // patterns like Walk_001, Walk_002, Run_001, Run_002
  4548. for(var _i260=0,il=morphTargets.length;_i260<il;_i260++){var morphTarget=morphTargets[_i260];var parts=morphTarget.name.match(pattern);if(parts&&parts.length>1){var name=parts[1];var animationMorphTargets=animationToMorphTargets[name];if(!animationMorphTargets){animationToMorphTargets[name]=animationMorphTargets=[];}animationMorphTargets.push(morphTarget);}}var clips=[];for(var _name4 in animationToMorphTargets){clips.push(AnimationClip.CreateFromMorphTargetSequence(_name4,animationToMorphTargets[_name4],fps,noLoop));}return clips;},// parse the animation.hierarchy format
  4549. parseAnimation:function parseAnimation(animation,bones){if(!animation){console.error('THREE.AnimationClip: No animation in JSONLoader data.');return null;}var addNonemptyTrack=function addNonemptyTrack(trackType,trackName,animationKeys,propertyName,destTracks){// only return track if there are actually keys.
  4550. if(animationKeys.length!==0){var times=[];var values=[];AnimationUtils.flattenJSON(animationKeys,times,values,propertyName);// empty keys are filtered out, so check again
  4551. if(times.length!==0){destTracks.push(new trackType(trackName,times,values));}}};var tracks=[];var clipName=animation.name||'default';var fps=animation.fps||30;var blendMode=animation.blendMode;// automatic length determination in AnimationClip.
  4552. var duration=animation.length||-1;var hierarchyTracks=animation.hierarchy||[];for(var h=0;h<hierarchyTracks.length;h++){var animationKeys=hierarchyTracks[h].keys;// skip empty tracks
  4553. if(!animationKeys||animationKeys.length===0)continue;// process morph targets
  4554. if(animationKeys[0].morphTargets){// figure out all morph targets used in this track
  4555. var morphTargetNames={};var k=void 0;for(k=0;k<animationKeys.length;k++){if(animationKeys[k].morphTargets){for(var m=0;m<animationKeys[k].morphTargets.length;m++){morphTargetNames[animationKeys[k].morphTargets[m]]=-1;}}}// create a track for each morph target with all zero
  4556. // morphTargetInfluences except for the keys in which
  4557. // the morphTarget is named.
  4558. for(var morphTargetName in morphTargetNames){var times=[];var values=[];for(var _m=0;_m!==animationKeys[k].morphTargets.length;++_m){var animationKey=animationKeys[k];times.push(animationKey.time);values.push(animationKey.morphTarget===morphTargetName?1:0);}tracks.push(new NumberKeyframeTrack('.morphTargetInfluence['+morphTargetName+']',times,values));}duration=morphTargetNames.length*(fps||1.0);}else {// ...assume skeletal animation
  4559. var boneName='.bones['+bones[h].name+']';addNonemptyTrack(VectorKeyframeTrack,boneName+'.position',animationKeys,'pos',tracks);addNonemptyTrack(QuaternionKeyframeTrack,boneName+'.quaternion',animationKeys,'rot',tracks);addNonemptyTrack(VectorKeyframeTrack,boneName+'.scale',animationKeys,'scl',tracks);}}if(tracks.length===0){return null;}var clip=new AnimationClip(clipName,duration,tracks,blendMode);return clip;}});Object.assign(AnimationClip.prototype,{resetDuration:function resetDuration(){var tracks=this.tracks;var duration=0;for(var _i261=0,n=tracks.length;_i261!==n;++_i261){var track=this.tracks[_i261];duration=Math.max(duration,track.times[track.times.length-1]);}this.duration=duration;return this;},trim:function trim(){for(var _i262=0;_i262<this.tracks.length;_i262++){this.tracks[_i262].trim(0,this.duration);}return this;},validate:function validate(){var valid=true;for(var _i263=0;_i263<this.tracks.length;_i263++){valid=valid&&this.tracks[_i263].validate();}return valid;},optimize:function optimize(){for(var _i264=0;_i264<this.tracks.length;_i264++){this.tracks[_i264].optimize();}return this;},clone:function clone(){var tracks=[];for(var _i265=0;_i265<this.tracks.length;_i265++){tracks.push(this.tracks[_i265].clone());}return new AnimationClip(this.name,this.duration,tracks,this.blendMode);},toJSON:function toJSON(){return AnimationClip.toJSON(this);}});var Cache={enabled:false,files:{},add:function add(key,file){if(this.enabled===false)return;// console.log( 'THREE.Cache', 'Adding key:', key );
  4560. this.files[key]=file;},get:function get(key){if(this.enabled===false)return;// console.log( 'THREE.Cache', 'Checking key:', key );
  4561. return this.files[key];},remove:function remove(key){delete this.files[key];},clear:function clear(){this.files={};}};function LoadingManager(onLoad,onProgress,onError){var scope=this;var isLoading=false;var itemsLoaded=0;var itemsTotal=0;var urlModifier=undefined;var handlers=[];// Refer to #5689 for the reason why we don't set .onStart
  4562. // in the constructor
  4563. this.onStart=undefined;this.onLoad=onLoad;this.onProgress=onProgress;this.onError=onError;this.itemStart=function(url){itemsTotal++;if(isLoading===false){if(scope.onStart!==undefined){scope.onStart(url,itemsLoaded,itemsTotal);}}isLoading=true;};this.itemEnd=function(url){itemsLoaded++;if(scope.onProgress!==undefined){scope.onProgress(url,itemsLoaded,itemsTotal);}if(itemsLoaded===itemsTotal){isLoading=false;if(scope.onLoad!==undefined){scope.onLoad();}}};this.itemError=function(url){if(scope.onError!==undefined){scope.onError(url);}};this.resolveURL=function(url){if(urlModifier){return urlModifier(url);}return url;};this.setURLModifier=function(transform){urlModifier=transform;return this;};this.addHandler=function(regex,loader){handlers.push(regex,loader);return this;};this.removeHandler=function(regex){var index=handlers.indexOf(regex);if(index!==-1){handlers.splice(index,2);}return this;};this.getHandler=function(file){for(var _i266=0,l=handlers.length;_i266<l;_i266+=2){var regex=handlers[_i266];var loader=handlers[_i266+1];if(regex.global)regex.lastIndex=0;// see #17920
  4564. if(regex.test(file)){return loader;}}return null;};}var DefaultLoadingManager=new LoadingManager();function Loader(manager){this.manager=manager!==undefined?manager:DefaultLoadingManager;this.crossOrigin='anonymous';this.withCredentials=false;this.path='';this.resourcePath='';this.requestHeader={};}Object.assign(Loader.prototype,{load:function load(/* url, onLoad, onProgress, onError */){},loadAsync:function loadAsync(url,onProgress){var scope=this;return new Promise(function(resolve,reject){scope.load(url,resolve,onProgress,reject);});},parse:function parse(/* data */){},setCrossOrigin:function setCrossOrigin(crossOrigin){this.crossOrigin=crossOrigin;return this;},setWithCredentials:function setWithCredentials(value){this.withCredentials=value;return this;},setPath:function setPath(path){this.path=path;return this;},setResourcePath:function setResourcePath(resourcePath){this.resourcePath=resourcePath;return this;},setRequestHeader:function setRequestHeader(requestHeader){this.requestHeader=requestHeader;return this;}});var loading={};function FileLoader(manager){Loader.call(this,manager);}FileLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:FileLoader,load:function load(url,onLoad,onProgress,onError){if(url===undefined)url='';if(this.path!==undefined)url=this.path+url;url=this.manager.resolveURL(url);var scope=this;var cached=Cache.get(url);if(cached!==undefined){scope.manager.itemStart(url);setTimeout(function(){if(onLoad)onLoad(cached);scope.manager.itemEnd(url);},0);return cached;}// Check if request is duplicate
  4565. if(loading[url]!==undefined){loading[url].push({onLoad:onLoad,onProgress:onProgress,onError:onError});return;}// Check for data: URI
  4566. var dataUriRegex=/^data:(.*?)(;base64)?,(.*)$/;var dataUriRegexResult=url.match(dataUriRegex);var request;// Safari can not handle Data URIs through XMLHttpRequest so process manually
  4567. if(dataUriRegexResult){var mimeType=dataUriRegexResult[1];var isBase64=!!dataUriRegexResult[2];var data=dataUriRegexResult[3];data=decodeURIComponent(data);if(isBase64)data=atob(data);try{var response;var responseType=(this.responseType||'').toLowerCase();switch(responseType){case'arraybuffer':case'blob':var view=new Uint8Array(data.length);for(var _i267=0;_i267<data.length;_i267++){view[_i267]=data.charCodeAt(_i267);}if(responseType==='blob'){response=new Blob([view.buffer],{type:mimeType});}else {response=view.buffer;}break;case'document':var parser=new DOMParser();response=parser.parseFromString(data,mimeType);break;case'json':response=JSON.parse(data);break;default:// 'text' or other
  4568. response=data;break;}// Wait for next browser tick like standard XMLHttpRequest event dispatching does
  4569. setTimeout(function(){if(onLoad)onLoad(response);scope.manager.itemEnd(url);},0);}catch(error){// Wait for next browser tick like standard XMLHttpRequest event dispatching does
  4570. setTimeout(function(){if(onError)onError(error);scope.manager.itemError(url);scope.manager.itemEnd(url);},0);}}else {// Initialise array for duplicate requests
  4571. loading[url]=[];loading[url].push({onLoad:onLoad,onProgress:onProgress,onError:onError});request=new XMLHttpRequest();request.open('GET',url,true);request.addEventListener('load',function(event){var response=this.response;var callbacks=loading[url];delete loading[url];if(this.status===200||this.status===0){// Some browsers return HTTP Status 0 when using non-http protocol
  4572. // e.g. 'file://' or 'data://'. Handle as success.
  4573. if(this.status===0)console.warn('THREE.FileLoader: HTTP Status 0 received.');// Add to cache only on HTTP success, so that we do not cache
  4574. // error response bodies as proper responses to requests.
  4575. Cache.add(url,response);for(var _i268=0,il=callbacks.length;_i268<il;_i268++){var callback=callbacks[_i268];if(callback.onLoad)callback.onLoad(response);}scope.manager.itemEnd(url);}else {for(var _i269=0,_il31=callbacks.length;_i269<_il31;_i269++){var _callback=callbacks[_i269];if(_callback.onError)_callback.onError(event);}scope.manager.itemError(url);scope.manager.itemEnd(url);}},false);request.addEventListener('progress',function(event){var callbacks=loading[url];for(var _i270=0,il=callbacks.length;_i270<il;_i270++){var callback=callbacks[_i270];if(callback.onProgress)callback.onProgress(event);}},false);request.addEventListener('error',function(event){var callbacks=loading[url];delete loading[url];for(var _i271=0,il=callbacks.length;_i271<il;_i271++){var callback=callbacks[_i271];if(callback.onError)callback.onError(event);}scope.manager.itemError(url);scope.manager.itemEnd(url);},false);request.addEventListener('abort',function(event){var callbacks=loading[url];delete loading[url];for(var _i272=0,il=callbacks.length;_i272<il;_i272++){var callback=callbacks[_i272];if(callback.onError)callback.onError(event);}scope.manager.itemError(url);scope.manager.itemEnd(url);},false);if(this.responseType!==undefined)request.responseType=this.responseType;if(this.withCredentials!==undefined)request.withCredentials=this.withCredentials;if(request.overrideMimeType)request.overrideMimeType(this.mimeType!==undefined?this.mimeType:'text/plain');for(var header in this.requestHeader){request.setRequestHeader(header,this.requestHeader[header]);}request.send(null);}scope.manager.itemStart(url);return request;},setResponseType:function setResponseType(value){this.responseType=value;return this;},setMimeType:function setMimeType(value){this.mimeType=value;return this;}});function AnimationLoader(manager){Loader.call(this,manager);}AnimationLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:AnimationLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.setPath(scope.path);loader.setRequestHeader(scope.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)));}catch(e){if(onError){onError(e);}else {console.error(e);}scope.manager.itemError(url);}},onProgress,onError);},parse:function parse(json){var animations=[];for(var _i273=0;_i273<json.length;_i273++){var clip=AnimationClip.parse(json[_i273]);animations.push(clip);}return animations;}});/**
  4576. * Abstract Base class to block based textures loader (dds, pvr, ...)
  4577. *
  4578. * Sub classes have to implement the parse() method which will be used in load().
  4579. */function CompressedTextureLoader(manager){Loader.call(this,manager);}CompressedTextureLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:CompressedTextureLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var images=[];var texture=new CompressedTexture();var loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setResponseType('arraybuffer');loader.setRequestHeader(this.requestHeader);loader.setWithCredentials(scope.withCredentials);var loaded=0;function loadTexture(i){loader.load(url[i],function(buffer){var texDatas=scope.parse(buffer,true);images[i]={width:texDatas.width,height:texDatas.height,format:texDatas.format,mipmaps:texDatas.mipmaps};loaded+=1;if(loaded===6){if(texDatas.mipmapCount===1)texture.minFilter=LinearFilter;texture.image=images;texture.format=texDatas.format;texture.needsUpdate=true;if(onLoad)onLoad(texture);}},onProgress,onError);}if(Array.isArray(url)){for(var _i274=0,il=url.length;_i274<il;++_i274){loadTexture(_i274);}}else {// compressed cubemap texture stored in a single DDS file
  4580. loader.load(url,function(buffer){var texDatas=scope.parse(buffer,true);if(texDatas.isCubemap){var faces=texDatas.mipmaps.length/texDatas.mipmapCount;for(var f=0;f<faces;f++){images[f]={mipmaps:[]};for(var _i275=0;_i275<texDatas.mipmapCount;_i275++){images[f].mipmaps.push(texDatas.mipmaps[f*texDatas.mipmapCount+_i275]);images[f].format=texDatas.format;images[f].width=texDatas.width;images[f].height=texDatas.height;}}texture.image=images;}else {texture.image.width=texDatas.width;texture.image.height=texDatas.height;texture.mipmaps=texDatas.mipmaps;}if(texDatas.mipmapCount===1){texture.minFilter=LinearFilter;}texture.format=texDatas.format;texture.needsUpdate=true;if(onLoad)onLoad(texture);},onProgress,onError);}return texture;}});function ImageLoader(manager){Loader.call(this,manager);}ImageLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:ImageLoader,load:function load(url,onLoad,onProgress,onError){if(this.path!==undefined)url=this.path+url;url=this.manager.resolveURL(url);var scope=this;var cached=Cache.get(url);if(cached!==undefined){scope.manager.itemStart(url);setTimeout(function(){if(onLoad)onLoad(cached);scope.manager.itemEnd(url);},0);return cached;}var image=document.createElementNS('http://www.w3.org/1999/xhtml','img');function onImageLoad(){image.removeEventListener('load',onImageLoad,false);image.removeEventListener('error',onImageError,false);Cache.add(url,this);if(onLoad)onLoad(this);scope.manager.itemEnd(url);}function onImageError(event){image.removeEventListener('load',onImageLoad,false);image.removeEventListener('error',onImageError,false);if(onError)onError(event);scope.manager.itemError(url);scope.manager.itemEnd(url);}image.addEventListener('load',onImageLoad,false);image.addEventListener('error',onImageError,false);if(url.substr(0,5)!=='data:'){if(this.crossOrigin!==undefined)image.crossOrigin=this.crossOrigin;}scope.manager.itemStart(url);image.src=url;return image;}});function CubeTextureLoader(manager){Loader.call(this,manager);}CubeTextureLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:CubeTextureLoader,load:function load(urls,onLoad,onProgress,onError){var texture=new CubeTexture();var loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);loader.setPath(this.path);var loaded=0;function loadTexture(i){loader.load(urls[i],function(image){texture.images[i]=image;loaded++;if(loaded===6){texture.needsUpdate=true;if(onLoad)onLoad(texture);}},undefined,onError);}for(var _i276=0;_i276<urls.length;++_i276){loadTexture(_i276);}return texture;}});/**
  4581. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  4582. *
  4583. * Sub classes have to implement the parse() method which will be used in load().
  4584. */function DataTextureLoader(manager){Loader.call(this,manager);}DataTextureLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:DataTextureLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var texture=new DataTexture();var loader=new FileLoader(this.manager);loader.setResponseType('arraybuffer');loader.setRequestHeader(this.requestHeader);loader.setPath(this.path);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(buffer){var texData=scope.parse(buffer);if(!texData)return;if(texData.image!==undefined){texture.image=texData.image;}else if(texData.data!==undefined){texture.image.width=texData.width;texture.image.height=texData.height;texture.image.data=texData.data;}texture.wrapS=texData.wrapS!==undefined?texData.wrapS:ClampToEdgeWrapping;texture.wrapT=texData.wrapT!==undefined?texData.wrapT:ClampToEdgeWrapping;texture.magFilter=texData.magFilter!==undefined?texData.magFilter:LinearFilter;texture.minFilter=texData.minFilter!==undefined?texData.minFilter:LinearFilter;texture.anisotropy=texData.anisotropy!==undefined?texData.anisotropy:1;if(texData.format!==undefined){texture.format=texData.format;}if(texData.type!==undefined){texture.type=texData.type;}if(texData.mipmaps!==undefined){texture.mipmaps=texData.mipmaps;texture.minFilter=LinearMipmapLinearFilter;// presumably...
  4585. }if(texData.mipmapCount===1){texture.minFilter=LinearFilter;}texture.needsUpdate=true;if(onLoad)onLoad(texture,texData);},onProgress,onError);return texture;}});function TextureLoader(manager){Loader.call(this,manager);}TextureLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:TextureLoader,load:function load(url,onLoad,onProgress,onError){var texture=new Texture();var loader=new ImageLoader(this.manager);loader.setCrossOrigin(this.crossOrigin);loader.setPath(this.path);loader.load(url,function(image){texture.image=image;// JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  4586. var isJPEG=url.search(/\.jpe?g($|\?)/i)>0||url.search(/^data\:image\/jpeg/)===0;texture.format=isJPEG?RGBFormat:RGBAFormat;texture.needsUpdate=true;if(onLoad!==undefined){onLoad(texture);}},onProgress,onError);return texture;}});/**
  4587. * Extensible curve object.
  4588. *
  4589. * Some common of curve methods:
  4590. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  4591. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  4592. * .getPoints(), .getSpacedPoints()
  4593. * .getLength()
  4594. * .updateArcLengths()
  4595. *
  4596. * This following curves inherit from THREE.Curve:
  4597. *
  4598. * -- 2D curves --
  4599. * THREE.ArcCurve
  4600. * THREE.CubicBezierCurve
  4601. * THREE.EllipseCurve
  4602. * THREE.LineCurve
  4603. * THREE.QuadraticBezierCurve
  4604. * THREE.SplineCurve
  4605. *
  4606. * -- 3D curves --
  4607. * THREE.CatmullRomCurve3
  4608. * THREE.CubicBezierCurve3
  4609. * THREE.LineCurve3
  4610. * THREE.QuadraticBezierCurve3
  4611. *
  4612. * A series of curves can be represented as a THREE.CurvePath.
  4613. *
  4614. **/function Curve(){this.type='Curve';this.arcLengthDivisions=200;}Object.assign(Curve.prototype,{// Virtual base class method to overwrite and implement in subclasses
  4615. // - t [0 .. 1]
  4616. getPoint:function getPoint(/* t, optionalTarget */){console.warn('THREE.Curve: .getPoint() not implemented.');return null;},// Get point at relative position in curve according to arc length
  4617. // - u [0 .. 1]
  4618. getPointAt:function getPointAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getPoint(t,optionalTarget);},// Get sequence of points using getPoint( t )
  4619. getPoints:function getPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPoint(d/divisions));}return points;},// Get sequence of points using getPointAt( u )
  4620. getSpacedPoints:function getSpacedPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:5;var points=[];for(var d=0;d<=divisions;d++){points.push(this.getPointAt(d/divisions));}return points;},// Get total curve arc length
  4621. getLength:function getLength(){var lengths=this.getLengths();return lengths[lengths.length-1];},// Get list of cumulative segment lengths
  4622. getLengths:function getLengths(divisions){if(divisions===undefined)divisions=this.arcLengthDivisions;if(this.cacheArcLengths&&this.cacheArcLengths.length===divisions+1&&!this.needsUpdate){return this.cacheArcLengths;}this.needsUpdate=false;var cache=[];var current,last=this.getPoint(0);var sum=0;cache.push(0);for(var p=1;p<=divisions;p++){current=this.getPoint(p/divisions);sum+=current.distanceTo(last);cache.push(sum);last=current;}this.cacheArcLengths=cache;return cache;// { sums: cache, sum: sum }; Sum is in the last element.
  4623. },updateArcLengths:function updateArcLengths(){this.needsUpdate=true;this.getLengths();},// Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  4624. getUtoTmapping:function getUtoTmapping(u,distance){var arcLengths=this.getLengths();var i=0;var il=arcLengths.length;var targetArcLength;// The targeted u distance value to get
  4625. if(distance){targetArcLength=distance;}else {targetArcLength=u*arcLengths[il-1];}// binary search for the index with largest value smaller than target u distance
  4626. var low=0,high=il-1,comparison;while(low<=high){i=Math.floor(low+(high-low)/2);// less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  4627. comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1;}else if(comparison>0){high=i-1;}else {high=i;break;// DONE
  4628. }}i=high;if(arcLengths[i]===targetArcLength){return i/(il-1);}// we could get finer grain at lengths, or use simple interpolation between two points
  4629. var lengthBefore=arcLengths[i];var lengthAfter=arcLengths[i+1];var segmentLength=lengthAfter-lengthBefore;// determine where we are between the 'before' and 'after' points
  4630. var segmentFraction=(targetArcLength-lengthBefore)/segmentLength;// add that fractional amount to t
  4631. var t=(i+segmentFraction)/(il-1);return t;},// Returns a unit vector tangent at t
  4632. // In case any sub curve does not implement its tangent derivation,
  4633. // 2 points a small delta apart will be used to find its gradient
  4634. // which seems to give a reasonable approximation
  4635. getTangent:function getTangent(t,optionalTarget){var delta=0.0001;var t1=t-delta;var t2=t+delta;// Capping in case of danger
  4636. if(t1<0)t1=0;if(t2>1)t2=1;var pt1=this.getPoint(t1);var pt2=this.getPoint(t2);var tangent=optionalTarget||(pt1.isVector2?new Vector2():new Vector3());tangent.copy(pt2).sub(pt1).normalize();return tangent;},getTangentAt:function getTangentAt(u,optionalTarget){var t=this.getUtoTmapping(u);return this.getTangent(t,optionalTarget);},computeFrenetFrames:function computeFrenetFrames(segments,closed){// see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  4637. var normal=new Vector3();var tangents=[];var normals=[];var binormals=[];var vec=new Vector3();var mat=new Matrix4();// compute the tangent vectors for each segment on the curve
  4638. for(var _i277=0;_i277<=segments;_i277++){var u=_i277/segments;tangents[_i277]=this.getTangentAt(u,new Vector3());tangents[_i277].normalize();}// select an initial normal vector perpendicular to the first tangent vector,
  4639. // and in the direction of the minimum tangent xyz component
  4640. normals[0]=new Vector3();binormals[0]=new Vector3();var min=Number.MAX_VALUE;var tx=Math.abs(tangents[0].x);var ty=Math.abs(tangents[0].y);var tz=Math.abs(tangents[0].z);if(tx<=min){min=tx;normal.set(1,0,0);}if(ty<=min){min=ty;normal.set(0,1,0);}if(tz<=min){normal.set(0,0,1);}vec.crossVectors(tangents[0],normal).normalize();normals[0].crossVectors(tangents[0],vec);binormals[0].crossVectors(tangents[0],normals[0]);// compute the slowly-varying normal and binormal vectors for each segment on the curve
  4641. for(var _i278=1;_i278<=segments;_i278++){normals[_i278]=normals[_i278-1].clone();binormals[_i278]=binormals[_i278-1].clone();vec.crossVectors(tangents[_i278-1],tangents[_i278]);if(vec.length()>Number.EPSILON){vec.normalize();var theta=Math.acos(MathUtils.clamp(tangents[_i278-1].dot(tangents[_i278]),-1,1));// clamp for floating pt errors
  4642. normals[_i278].applyMatrix4(mat.makeRotationAxis(vec,theta));}binormals[_i278].crossVectors(tangents[_i278],normals[_i278]);}// if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  4643. if(closed===true){var _theta=Math.acos(MathUtils.clamp(normals[0].dot(normals[segments]),-1,1));_theta/=segments;if(tangents[0].dot(vec.crossVectors(normals[0],normals[segments]))>0){_theta=-_theta;}for(var _i279=1;_i279<=segments;_i279++){// twist a little...
  4644. normals[_i279].applyMatrix4(mat.makeRotationAxis(tangents[_i279],_theta*_i279));binormals[_i279].crossVectors(tangents[_i279],normals[_i279]);}}return {tangents:tangents,normals:normals,binormals:binormals};},clone:function clone(){return new this.constructor().copy(this);},copy:function copy(source){this.arcLengthDivisions=source.arcLengthDivisions;return this;},toJSON:function toJSON(){var data={metadata:{version:4.5,type:'Curve',generator:'Curve.toJSON'}};data.arcLengthDivisions=this.arcLengthDivisions;data.type=this.type;return data;},fromJSON:function fromJSON(json){this.arcLengthDivisions=json.arcLengthDivisions;return this;}});function EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){Curve.call(this);this.type='EllipseCurve';this.aX=aX||0;this.aY=aY||0;this.xRadius=xRadius||1;this.yRadius=yRadius||1;this.aStartAngle=aStartAngle||0;this.aEndAngle=aEndAngle||2*Math.PI;this.aClockwise=aClockwise||false;this.aRotation=aRotation||0;}EllipseCurve.prototype=Object.create(Curve.prototype);EllipseCurve.prototype.constructor=EllipseCurve;EllipseCurve.prototype.isEllipseCurve=true;EllipseCurve.prototype.getPoint=function(t,optionalTarget){var point=optionalTarget||new Vector2();var twoPi=Math.PI*2;var deltaAngle=this.aEndAngle-this.aStartAngle;var samePoints=Math.abs(deltaAngle)<Number.EPSILON;// ensures that deltaAngle is 0 .. 2 PI
  4645. while(deltaAngle<0)deltaAngle+=twoPi;while(deltaAngle>twoPi)deltaAngle-=twoPi;if(deltaAngle<Number.EPSILON){if(samePoints){deltaAngle=0;}else {deltaAngle=twoPi;}}if(this.aClockwise===true&&!samePoints){if(deltaAngle===twoPi){deltaAngle=-twoPi;}else {deltaAngle=deltaAngle-twoPi;}}var angle=this.aStartAngle+t*deltaAngle;var x=this.aX+this.xRadius*Math.cos(angle);var y=this.aY+this.yRadius*Math.sin(angle);if(this.aRotation!==0){var cos=Math.cos(this.aRotation);var sin=Math.sin(this.aRotation);var tx=x-this.aX;var ty=y-this.aY;// Rotate the point about the center of the ellipse.
  4646. x=tx*cos-ty*sin+this.aX;y=tx*sin+ty*cos+this.aY;}return point.set(x,y);};EllipseCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.aX=source.aX;this.aY=source.aY;this.xRadius=source.xRadius;this.yRadius=source.yRadius;this.aStartAngle=source.aStartAngle;this.aEndAngle=source.aEndAngle;this.aClockwise=source.aClockwise;this.aRotation=source.aRotation;return this;};EllipseCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.aX=this.aX;data.aY=this.aY;data.xRadius=this.xRadius;data.yRadius=this.yRadius;data.aStartAngle=this.aStartAngle;data.aEndAngle=this.aEndAngle;data.aClockwise=this.aClockwise;data.aRotation=this.aRotation;return data;};EllipseCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.aX=json.aX;this.aY=json.aY;this.xRadius=json.xRadius;this.yRadius=json.yRadius;this.aStartAngle=json.aStartAngle;this.aEndAngle=json.aEndAngle;this.aClockwise=json.aClockwise;this.aRotation=json.aRotation;return this;};function ArcCurve(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){EllipseCurve.call(this,aX,aY,aRadius,aRadius,aStartAngle,aEndAngle,aClockwise);this.type='ArcCurve';}ArcCurve.prototype=Object.create(EllipseCurve.prototype);ArcCurve.prototype.constructor=ArcCurve;ArcCurve.prototype.isArcCurve=true;/**
  4647. * Centripetal CatmullRom Curve - which is useful for avoiding
  4648. * cusps and self-intersections in non-uniform catmull rom curves.
  4649. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  4650. *
  4651. * curve.type accepts centripetal(default), chordal and catmullrom
  4652. * curve.tension is used for catmullrom which defaults to 0.5
  4653. */ /*
  4654. Based on an optimized c++ solution in
  4655. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  4656. - http://ideone.com/NoEbVM
  4657. This CubicPoly class could be used for reusing some variables and calculations,
  4658. but for three.js curve use, it could be possible inlined and flatten into a single function call
  4659. which can be placed in CurveUtils.
  4660. */function CubicPoly(){var c0=0,c1=0,c2=0,c3=0;/*
  4661. * Compute coefficients for a cubic polynomial
  4662. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  4663. * such that
  4664. * p(0) = x0, p(1) = x1
  4665. * and
  4666. * p'(0) = t0, p'(1) = t1.
  4667. */function init(x0,x1,t0,t1){c0=x0;c1=t0;c2=-3*x0+3*x1-2*t0-t1;c3=2*x0-2*x1+t0+t1;}return {initCatmullRom:function initCatmullRom(x0,x1,x2,x3,tension){init(x1,x2,tension*(x2-x0),tension*(x3-x1));},initNonuniformCatmullRom:function initNonuniformCatmullRom(x0,x1,x2,x3,dt0,dt1,dt2){// compute tangents when parameterized in [t1,t2]
  4668. var t1=(x1-x0)/dt0-(x2-x0)/(dt0+dt1)+(x2-x1)/dt1;var t2=(x2-x1)/dt1-(x3-x1)/(dt1+dt2)+(x3-x2)/dt2;// rescale tangents for parametrization in [0,1]
  4669. t1*=dt1;t2*=dt1;init(x1,x2,t1,t2);},calc:function calc(t){var t2=t*t;var t3=t2*t;return c0+c1*t+c2*t2+c3*t3;}};}//
  4670. var tmp=new Vector3();var px=new CubicPoly(),py=new CubicPoly(),pz=new CubicPoly();function CatmullRomCurve3(){var points=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var closed=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var curveType=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'centripetal';var tension=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0.5;Curve.call(this);this.type='CatmullRomCurve3';this.points=points;this.closed=closed;this.curveType=curveType;this.tension=tension;}CatmullRomCurve3.prototype=Object.create(Curve.prototype);CatmullRomCurve3.prototype.constructor=CatmullRomCurve3;CatmullRomCurve3.prototype.isCatmullRomCurve3=true;CatmullRomCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var points=this.points;var l=points.length;var p=(l-(this.closed?0:1))*t;var intPoint=Math.floor(p);var weight=p-intPoint;if(this.closed){intPoint+=intPoint>0?0:(Math.floor(Math.abs(intPoint)/l)+1)*l;}else if(weight===0&&intPoint===l-1){intPoint=l-2;weight=1;}var p0,p3;// 4 points (p1 & p2 defined below)
  4671. if(this.closed||intPoint>0){p0=points[(intPoint-1)%l];}else {// extrapolate first point
  4672. tmp.subVectors(points[0],points[1]).add(points[0]);p0=tmp;}var p1=points[intPoint%l];var p2=points[(intPoint+1)%l];if(this.closed||intPoint+2<l){p3=points[(intPoint+2)%l];}else {// extrapolate last point
  4673. tmp.subVectors(points[l-1],points[l-2]).add(points[l-1]);p3=tmp;}if(this.curveType==='centripetal'||this.curveType==='chordal'){// init Centripetal / Chordal Catmull-Rom
  4674. var pow=this.curveType==='chordal'?0.5:0.25;var dt0=Math.pow(p0.distanceToSquared(p1),pow);var dt1=Math.pow(p1.distanceToSquared(p2),pow);var dt2=Math.pow(p2.distanceToSquared(p3),pow);// safety check for repeated points
  4675. if(dt1<1e-4)dt1=1.0;if(dt0<1e-4)dt0=dt1;if(dt2<1e-4)dt2=dt1;px.initNonuniformCatmullRom(p0.x,p1.x,p2.x,p3.x,dt0,dt1,dt2);py.initNonuniformCatmullRom(p0.y,p1.y,p2.y,p3.y,dt0,dt1,dt2);pz.initNonuniformCatmullRom(p0.z,p1.z,p2.z,p3.z,dt0,dt1,dt2);}else if(this.curveType==='catmullrom'){px.initCatmullRom(p0.x,p1.x,p2.x,p3.x,this.tension);py.initCatmullRom(p0.y,p1.y,p2.y,p3.y,this.tension);pz.initCatmullRom(p0.z,p1.z,p2.z,p3.z,this.tension);}point.set(px.calc(weight),py.calc(weight),pz.calc(weight));return point;};CatmullRomCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.points=[];for(var _i280=0,l=source.points.length;_i280<l;_i280++){var point=source.points[_i280];this.points.push(point.clone());}this.closed=source.closed;this.curveType=source.curveType;this.tension=source.tension;return this;};CatmullRomCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.points=[];for(var _i281=0,l=this.points.length;_i281<l;_i281++){var point=this.points[_i281];data.points.push(point.toArray());}data.closed=this.closed;data.curveType=this.curveType;data.tension=this.tension;return data;};CatmullRomCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.points=[];for(var _i282=0,l=json.points.length;_i282<l;_i282++){var point=json.points[_i282];this.points.push(new Vector3().fromArray(point));}this.closed=json.closed;this.curveType=json.curveType;this.tension=json.tension;return this;};/**
  4676. * Bezier Curves formulas obtained from
  4677. * http://en.wikipedia.org/wiki/Bézier_curve
  4678. */function CatmullRom(t,p0,p1,p2,p3){var v0=(p2-p0)*0.5;var v1=(p3-p1)*0.5;var t2=t*t;var t3=t*t2;return (2*p1-2*p2+v0+v1)*t3+(-3*p1+3*p2-2*v0-v1)*t2+v0*t+p1;}//
  4679. function QuadraticBezierP0(t,p){var k=1-t;return k*k*p;}function QuadraticBezierP1(t,p){return 2*(1-t)*t*p;}function QuadraticBezierP2(t,p){return t*t*p;}function QuadraticBezier(t,p0,p1,p2){return QuadraticBezierP0(t,p0)+QuadraticBezierP1(t,p1)+QuadraticBezierP2(t,p2);}//
  4680. function CubicBezierP0(t,p){var k=1-t;return k*k*k*p;}function CubicBezierP1(t,p){var k=1-t;return 3*k*k*t*p;}function CubicBezierP2(t,p){return 3*(1-t)*t*t*p;}function CubicBezierP3(t,p){return t*t*t*p;}function CubicBezier(t,p0,p1,p2,p3){return CubicBezierP0(t,p0)+CubicBezierP1(t,p1)+CubicBezierP2(t,p2)+CubicBezierP3(t,p3);}function CubicBezierCurve(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector2();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector2();var v3=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Vector2();Curve.call(this);this.type='CubicBezierCurve';this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3;}CubicBezierCurve.prototype=Object.create(Curve.prototype);CubicBezierCurve.prototype.constructor=CubicBezierCurve;CubicBezierCurve.prototype.isCubicBezierCurve=true;CubicBezierCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;point.set(CubicBezier(t,v0.x,v1.x,v2.x,v3.x),CubicBezier(t,v0.y,v1.y,v2.y,v3.y));return point;};CubicBezierCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);this.v3.copy(source.v3);return this;};CubicBezierCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();data.v3=this.v3.toArray();return data;};CubicBezierCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);this.v3.fromArray(json.v3);return this;};function CubicBezierCurve3(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3();var v3=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Vector3();Curve.call(this);this.type='CubicBezierCurve3';this.v0=v0;this.v1=v1;this.v2=v2;this.v3=v3;}CubicBezierCurve3.prototype=Object.create(Curve.prototype);CubicBezierCurve3.prototype.constructor=CubicBezierCurve3;CubicBezierCurve3.prototype.isCubicBezierCurve3=true;CubicBezierCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2,v3=this.v3;point.set(CubicBezier(t,v0.x,v1.x,v2.x,v3.x),CubicBezier(t,v0.y,v1.y,v2.y,v3.y),CubicBezier(t,v0.z,v1.z,v2.z,v3.z));return point;};CubicBezierCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);this.v3.copy(source.v3);return this;};CubicBezierCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();data.v3=this.v3.toArray();return data;};CubicBezierCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);this.v3.fromArray(json.v3);return this;};function LineCurve(){var v1=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector2();var v2=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();Curve.call(this);this.type='LineCurve';this.v1=v1;this.v2=v2;}LineCurve.prototype=Object.create(Curve.prototype);LineCurve.prototype.constructor=LineCurve;LineCurve.prototype.isLineCurve=true;LineCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;if(t===1){point.copy(this.v2);}else {point.copy(this.v2).sub(this.v1);point.multiplyScalar(t).add(this.v1);}return point;};// Line curve is linear, so we can overwrite default getPointAt
  4681. LineCurve.prototype.getPointAt=function(u,optionalTarget){return this.getPoint(u,optionalTarget);};LineCurve.prototype.getTangent=function(t,optionalTarget){var tangent=optionalTarget||new Vector2();tangent.copy(this.v2).sub(this.v1).normalize();return tangent;};LineCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};LineCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};LineCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function LineCurve3(){var v1=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v2=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();Curve.call(this);this.type='LineCurve3';this.v1=v1;this.v2=v2;}LineCurve3.prototype=Object.create(Curve.prototype);LineCurve3.prototype.constructor=LineCurve3;LineCurve3.prototype.isLineCurve3=true;LineCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;if(t===1){point.copy(this.v2);}else {point.copy(this.v2).sub(this.v1);point.multiplyScalar(t).add(this.v1);}return point;};// Line curve is linear, so we can overwrite default getPointAt
  4682. LineCurve3.prototype.getPointAt=function(u,optionalTarget){return this.getPoint(u,optionalTarget);};LineCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};LineCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};LineCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function QuadraticBezierCurve(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector2();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector2();Curve.call(this);this.type='QuadraticBezierCurve';this.v0=v0;this.v1=v1;this.v2=v2;}QuadraticBezierCurve.prototype=Object.create(Curve.prototype);QuadraticBezierCurve.prototype.constructor=QuadraticBezierCurve;QuadraticBezierCurve.prototype.isQuadraticBezierCurve=true;QuadraticBezierCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2;point.set(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y));return point;};QuadraticBezierCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};QuadraticBezierCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};QuadraticBezierCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function QuadraticBezierCurve3(){var v0=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Vector3();var v1=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var v2=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3();Curve.call(this);this.type='QuadraticBezierCurve3';this.v0=v0;this.v1=v1;this.v2=v2;}QuadraticBezierCurve3.prototype=Object.create(Curve.prototype);QuadraticBezierCurve3.prototype.constructor=QuadraticBezierCurve3;QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3=true;QuadraticBezierCurve3.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector3();var point=optionalTarget;var v0=this.v0,v1=this.v1,v2=this.v2;point.set(QuadraticBezier(t,v0.x,v1.x,v2.x),QuadraticBezier(t,v0.y,v1.y,v2.y),QuadraticBezier(t,v0.z,v1.z,v2.z));return point;};QuadraticBezierCurve3.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.v0.copy(source.v0);this.v1.copy(source.v1);this.v2.copy(source.v2);return this;};QuadraticBezierCurve3.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.v0=this.v0.toArray();data.v1=this.v1.toArray();data.v2=this.v2.toArray();return data;};QuadraticBezierCurve3.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.v0.fromArray(json.v0);this.v1.fromArray(json.v1);this.v2.fromArray(json.v2);return this;};function SplineCurve(){var points=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];Curve.call(this);this.type='SplineCurve';this.points=points;}SplineCurve.prototype=Object.create(Curve.prototype);SplineCurve.prototype.constructor=SplineCurve;SplineCurve.prototype.isSplineCurve=true;SplineCurve.prototype.getPoint=function(t){var optionalTarget=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Vector2();var point=optionalTarget;var points=this.points;var p=(points.length-1)*t;var intPoint=Math.floor(p);var weight=p-intPoint;var p0=points[intPoint===0?intPoint:intPoint-1];var p1=points[intPoint];var p2=points[intPoint>points.length-2?points.length-1:intPoint+1];var p3=points[intPoint>points.length-3?points.length-1:intPoint+2];point.set(CatmullRom(weight,p0.x,p1.x,p2.x,p3.x),CatmullRom(weight,p0.y,p1.y,p2.y,p3.y));return point;};SplineCurve.prototype.copy=function(source){Curve.prototype.copy.call(this,source);this.points=[];for(var _i283=0,l=source.points.length;_i283<l;_i283++){var point=source.points[_i283];this.points.push(point.clone());}return this;};SplineCurve.prototype.toJSON=function(){var data=Curve.prototype.toJSON.call(this);data.points=[];for(var _i284=0,l=this.points.length;_i284<l;_i284++){var point=this.points[_i284];data.points.push(point.toArray());}return data;};SplineCurve.prototype.fromJSON=function(json){Curve.prototype.fromJSON.call(this,json);this.points=[];for(var _i285=0,l=json.points.length;_i285<l;_i285++){var point=json.points[_i285];this.points.push(new Vector2().fromArray(point));}return this;};var Curves=/*#__PURE__*/Object.freeze({__proto__:null,ArcCurve:ArcCurve,CatmullRomCurve3:CatmullRomCurve3,CubicBezierCurve:CubicBezierCurve,CubicBezierCurve3:CubicBezierCurve3,EllipseCurve:EllipseCurve,LineCurve:LineCurve,LineCurve3:LineCurve3,QuadraticBezierCurve:QuadraticBezierCurve,QuadraticBezierCurve3:QuadraticBezierCurve3,SplineCurve:SplineCurve});/**************************************************************
  4683. * Curved Path - a curve path is simply a array of connected
  4684. * curves, but retains the api of a curve
  4685. **************************************************************/function CurvePath(){Curve.call(this);this.type='CurvePath';this.curves=[];this.autoClose=false;// Automatically closes the path
  4686. }CurvePath.prototype=Object.assign(Object.create(Curve.prototype),{constructor:CurvePath,add:function add(curve){this.curves.push(curve);},closePath:function closePath(){// Add a line curve if start and end of lines are not connected
  4687. var startPoint=this.curves[0].getPoint(0);var endPoint=this.curves[this.curves.length-1].getPoint(1);if(!startPoint.equals(endPoint)){this.curves.push(new LineCurve(endPoint,startPoint));}},// To get accurate point with reference to
  4688. // entire path distance at time t,
  4689. // following has to be done:
  4690. // 1. Length of each sub path have to be known
  4691. // 2. Locate and identify type of curve
  4692. // 3. Get t for the curve
  4693. // 4. Return curve.getPointAt(t')
  4694. getPoint:function getPoint(t){var d=t*this.getLength();var curveLengths=this.getCurveLengths();var i=0;// To think about boundaries points.
  4695. while(i<curveLengths.length){if(curveLengths[i]>=d){var diff=curveLengths[i]-d;var curve=this.curves[i];var segmentLength=curve.getLength();var u=segmentLength===0?0:1-diff/segmentLength;return curve.getPointAt(u);}i++;}return null;// loop where sum != 0, sum > d , sum+1 <d
  4696. },// We cannot use the default THREE.Curve getPoint() with getLength() because in
  4697. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  4698. // getPoint() depends on getLength
  4699. getLength:function getLength(){var lens=this.getCurveLengths();return lens[lens.length-1];},// cacheLengths must be recalculated.
  4700. updateArcLengths:function updateArcLengths(){this.needsUpdate=true;this.cacheLengths=null;this.getCurveLengths();},// Compute lengths and cache them
  4701. // We cannot overwrite getLengths() because UtoT mapping uses it.
  4702. getCurveLengths:function getCurveLengths(){// We use cache values if curves and cache array are same length
  4703. if(this.cacheLengths&&this.cacheLengths.length===this.curves.length){return this.cacheLengths;}// Get length of sub-curve
  4704. // Push sums into cached array
  4705. var lengths=[];var sums=0;for(var _i286=0,l=this.curves.length;_i286<l;_i286++){sums+=this.curves[_i286].getLength();lengths.push(sums);}this.cacheLengths=lengths;return lengths;},getSpacedPoints:function getSpacedPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:40;var points=[];for(var _i287=0;_i287<=divisions;_i287++){points.push(this.getPoint(_i287/divisions));}if(this.autoClose){points.push(points[0]);}return points;},getPoints:function getPoints(){var divisions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:12;var points=[];var last;for(var _i288=0,curves=this.curves;_i288<curves.length;_i288++){var curve=curves[_i288];var resolution=curve&&curve.isEllipseCurve?divisions*2:curve&&(curve.isLineCurve||curve.isLineCurve3)?1:curve&&curve.isSplineCurve?divisions*curve.points.length:divisions;var pts=curve.getPoints(resolution);for(var j=0;j<pts.length;j++){var point=pts[j];if(last&&last.equals(point))continue;// ensures no consecutive points are duplicates
  4706. points.push(point);last=point;}}if(this.autoClose&&points.length>1&&!points[points.length-1].equals(points[0])){points.push(points[0]);}return points;},copy:function copy(source){Curve.prototype.copy.call(this,source);this.curves=[];for(var _i289=0,l=source.curves.length;_i289<l;_i289++){var curve=source.curves[_i289];this.curves.push(curve.clone());}this.autoClose=source.autoClose;return this;},toJSON:function toJSON(){var data=Curve.prototype.toJSON.call(this);data.autoClose=this.autoClose;data.curves=[];for(var _i290=0,l=this.curves.length;_i290<l;_i290++){var curve=this.curves[_i290];data.curves.push(curve.toJSON());}return data;},fromJSON:function fromJSON(json){Curve.prototype.fromJSON.call(this,json);this.autoClose=json.autoClose;this.curves=[];for(var _i291=0,l=json.curves.length;_i291<l;_i291++){var curve=json.curves[_i291];this.curves.push(new Curves[curve.type]().fromJSON(curve));}return this;}});function Path(points){CurvePath.call(this);this.type='Path';this.currentPoint=new Vector2();if(points){this.setFromPoints(points);}}Path.prototype=Object.assign(Object.create(CurvePath.prototype),{constructor:Path,setFromPoints:function setFromPoints(points){this.moveTo(points[0].x,points[0].y);for(var _i292=1,l=points.length;_i292<l;_i292++){this.lineTo(points[_i292].x,points[_i292].y);}return this;},moveTo:function moveTo(x,y){this.currentPoint.set(x,y);// TODO consider referencing vectors instead of copying?
  4707. return this;},lineTo:function lineTo(x,y){var curve=new LineCurve(this.currentPoint.clone(),new Vector2(x,y));this.curves.push(curve);this.currentPoint.set(x,y);return this;},quadraticCurveTo:function quadraticCurveTo(aCPx,aCPy,aX,aY){var curve=new QuadraticBezierCurve(this.currentPoint.clone(),new Vector2(aCPx,aCPy),new Vector2(aX,aY));this.curves.push(curve);this.currentPoint.set(aX,aY);return this;},bezierCurveTo:function bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){var curve=new CubicBezierCurve(this.currentPoint.clone(),new Vector2(aCP1x,aCP1y),new Vector2(aCP2x,aCP2y),new Vector2(aX,aY));this.curves.push(curve);this.currentPoint.set(aX,aY);return this;},splineThru:function splineThru(pts/*Array of Vector*/){var npts=[this.currentPoint.clone()].concat(pts);var curve=new SplineCurve(npts);this.curves.push(curve);this.currentPoint.copy(pts[pts.length-1]);return this;},arc:function arc(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){var x0=this.currentPoint.x;var y0=this.currentPoint.y;this.absarc(aX+x0,aY+y0,aRadius,aStartAngle,aEndAngle,aClockwise);return this;},absarc:function absarc(aX,aY,aRadius,aStartAngle,aEndAngle,aClockwise){this.absellipse(aX,aY,aRadius,aRadius,aStartAngle,aEndAngle,aClockwise);return this;},ellipse:function ellipse(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){var x0=this.currentPoint.x;var y0=this.currentPoint.y;this.absellipse(aX+x0,aY+y0,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation);return this;},absellipse:function absellipse(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation){var curve=new EllipseCurve(aX,aY,xRadius,yRadius,aStartAngle,aEndAngle,aClockwise,aRotation);if(this.curves.length>0){// if a previous curve is present, attempt to join
  4708. var firstPoint=curve.getPoint(0);if(!firstPoint.equals(this.currentPoint)){this.lineTo(firstPoint.x,firstPoint.y);}}this.curves.push(curve);var lastPoint=curve.getPoint(1);this.currentPoint.copy(lastPoint);return this;},copy:function copy(source){CurvePath.prototype.copy.call(this,source);this.currentPoint.copy(source.currentPoint);return this;},toJSON:function toJSON(){var data=CurvePath.prototype.toJSON.call(this);data.currentPoint=this.currentPoint.toArray();return data;},fromJSON:function fromJSON(json){CurvePath.prototype.fromJSON.call(this,json);this.currentPoint.fromArray(json.currentPoint);return this;}});function Shape(points){Path.call(this,points);this.uuid=MathUtils.generateUUID();this.type='Shape';this.holes=[];}Shape.prototype=Object.assign(Object.create(Path.prototype),{constructor:Shape,getPointsHoles:function getPointsHoles(divisions){var holesPts=[];for(var _i293=0,l=this.holes.length;_i293<l;_i293++){holesPts[_i293]=this.holes[_i293].getPoints(divisions);}return holesPts;},// get points of shape and holes (keypoints based on segments parameter)
  4709. extractPoints:function extractPoints(divisions){return {shape:this.getPoints(divisions),holes:this.getPointsHoles(divisions)};},copy:function copy(source){Path.prototype.copy.call(this,source);this.holes=[];for(var _i294=0,l=source.holes.length;_i294<l;_i294++){var hole=source.holes[_i294];this.holes.push(hole.clone());}return this;},toJSON:function toJSON(){var data=Path.prototype.toJSON.call(this);data.uuid=this.uuid;data.holes=[];for(var _i295=0,l=this.holes.length;_i295<l;_i295++){var hole=this.holes[_i295];data.holes.push(hole.toJSON());}return data;},fromJSON:function fromJSON(json){Path.prototype.fromJSON.call(this,json);this.uuid=json.uuid;this.holes=[];for(var _i296=0,l=json.holes.length;_i296<l;_i296++){var hole=json.holes[_i296];this.holes.push(new Path().fromJSON(hole));}return this;}});function Light(color){var intensity=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;Object3D.call(this);this.type='Light';this.color=new Color(color);this.intensity=intensity;}Light.prototype=Object.assign(Object.create(Object3D.prototype),{constructor:Light,isLight:true,copy:function copy(source){Object3D.prototype.copy.call(this,source);this.color.copy(source.color);this.intensity=source.intensity;return this;},toJSON:function toJSON(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.color=this.color.getHex();data.object.intensity=this.intensity;if(this.groundColor!==undefined)data.object.groundColor=this.groundColor.getHex();if(this.distance!==undefined)data.object.distance=this.distance;if(this.angle!==undefined)data.object.angle=this.angle;if(this.decay!==undefined)data.object.decay=this.decay;if(this.penumbra!==undefined)data.object.penumbra=this.penumbra;if(this.shadow!==undefined)data.object.shadow=this.shadow.toJSON();return data;}});function HemisphereLight(skyColor,groundColor,intensity){Light.call(this,skyColor,intensity);this.type='HemisphereLight';this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.groundColor=new Color(groundColor);}HemisphereLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:HemisphereLight,isHemisphereLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.groundColor.copy(source.groundColor);return this;}});function LightShadow(camera){this.camera=camera;this.bias=0;this.normalBias=0;this.radius=1;this.mapSize=new Vector2(512,512);this.map=null;this.mapPass=null;this.matrix=new Matrix4();this.autoUpdate=true;this.needsUpdate=false;this._frustum=new Frustum();this._frameExtents=new Vector2(1,1);this._viewportCount=1;this._viewports=[new Vector4(0,0,1,1)];}Object.assign(LightShadow.prototype,{_projScreenMatrix:new Matrix4(),_lightPositionWorld:new Vector3(),_lookTarget:new Vector3(),getViewportCount:function getViewportCount(){return this._viewportCount;},getFrustum:function getFrustum(){return this._frustum;},updateMatrices:function updateMatrices(light){var shadowCamera=this.camera,shadowMatrix=this.matrix,projScreenMatrix=this._projScreenMatrix,lookTarget=this._lookTarget,lightPositionWorld=this._lightPositionWorld;lightPositionWorld.setFromMatrixPosition(light.matrixWorld);shadowCamera.position.copy(lightPositionWorld);lookTarget.setFromMatrixPosition(light.target.matrixWorld);shadowCamera.lookAt(lookTarget);shadowCamera.updateMatrixWorld();projScreenMatrix.multiplyMatrices(shadowCamera.projectionMatrix,shadowCamera.matrixWorldInverse);this._frustum.setFromProjectionMatrix(projScreenMatrix);shadowMatrix.set(0.5,0.0,0.0,0.5,0.0,0.5,0.0,0.5,0.0,0.0,0.5,0.5,0.0,0.0,0.0,1.0);shadowMatrix.multiply(shadowCamera.projectionMatrix);shadowMatrix.multiply(shadowCamera.matrixWorldInverse);},getViewport:function getViewport(viewportIndex){return this._viewports[viewportIndex];},getFrameExtents:function getFrameExtents(){return this._frameExtents;},copy:function copy(source){this.camera=source.camera.clone();this.bias=source.bias;this.radius=source.radius;this.mapSize.copy(source.mapSize);return this;},clone:function clone(){return new this.constructor().copy(this);},toJSON:function toJSON(){var object={};if(this.bias!==0)object.bias=this.bias;if(this.normalBias!==0)object.normalBias=this.normalBias;if(this.radius!==1)object.radius=this.radius;if(this.mapSize.x!==512||this.mapSize.y!==512)object.mapSize=this.mapSize.toArray();object.camera=this.camera.toJSON(false).object;delete object.camera.matrix;return object;}});function SpotLightShadow(){LightShadow.call(this,new PerspectiveCamera(50,1,0.5,500));this.focus=1;}SpotLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:SpotLightShadow,isSpotLightShadow:true,updateMatrices:function updateMatrices(light){var camera=this.camera;var fov=MathUtils.RAD2DEG*2*light.angle*this.focus;var aspect=this.mapSize.width/this.mapSize.height;var far=light.distance||camera.far;if(fov!==camera.fov||aspect!==camera.aspect||far!==camera.far){camera.fov=fov;camera.aspect=aspect;camera.far=far;camera.updateProjectionMatrix();}LightShadow.prototype.updateMatrices.call(this,light);}});function SpotLight(color,intensity,distance,angle,penumbra,decay){Light.call(this,color,intensity);this.type='SpotLight';this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.target=new Object3D();Object.defineProperty(this,'power',{get:function get(){// intensity = power per solid angle.
  4710. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  4711. return this.intensity*Math.PI;},set:function set(power){// intensity = power per solid angle.
  4712. // ref: equation (17) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  4713. this.intensity=power/Math.PI;}});this.distance=distance!==undefined?distance:0;this.angle=angle!==undefined?angle:Math.PI/3;this.penumbra=penumbra!==undefined?penumbra:0;this.decay=decay!==undefined?decay:1;// for physically correct lights, should be 2.
  4714. this.shadow=new SpotLightShadow();}SpotLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:SpotLight,isSpotLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.distance=source.distance;this.angle=source.angle;this.penumbra=source.penumbra;this.decay=source.decay;this.target=source.target.clone();this.shadow=source.shadow.clone();return this;}});function PointLightShadow(){LightShadow.call(this,new PerspectiveCamera(90,1,0.5,500));this._frameExtents=new Vector2(4,2);this._viewportCount=6;this._viewports=[// These viewports map a cube-map onto a 2D texture with the
  4715. // following orientation:
  4716. //
  4717. // xzXZ
  4718. // y Y
  4719. //
  4720. // X - Positive x direction
  4721. // x - Negative x direction
  4722. // Y - Positive y direction
  4723. // y - Negative y direction
  4724. // Z - Positive z direction
  4725. // z - Negative z direction
  4726. // positive X
  4727. new Vector4(2,1,1,1),// negative X
  4728. new Vector4(0,1,1,1),// positive Z
  4729. new Vector4(3,1,1,1),// negative Z
  4730. new Vector4(1,1,1,1),// positive Y
  4731. new Vector4(3,0,1,1),// negative Y
  4732. new Vector4(1,0,1,1)];this._cubeDirections=[new Vector3(1,0,0),new Vector3(-1,0,0),new Vector3(0,0,1),new Vector3(0,0,-1),new Vector3(0,1,0),new Vector3(0,-1,0)];this._cubeUps=[new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,1,0),new Vector3(0,0,1),new Vector3(0,0,-1)];}PointLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:PointLightShadow,isPointLightShadow:true,updateMatrices:function updateMatrices(light){var viewportIndex=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var camera=this.camera,shadowMatrix=this.matrix,lightPositionWorld=this._lightPositionWorld,lookTarget=this._lookTarget,projScreenMatrix=this._projScreenMatrix;lightPositionWorld.setFromMatrixPosition(light.matrixWorld);camera.position.copy(lightPositionWorld);lookTarget.copy(camera.position);lookTarget.add(this._cubeDirections[viewportIndex]);camera.up.copy(this._cubeUps[viewportIndex]);camera.lookAt(lookTarget);camera.updateMatrixWorld();shadowMatrix.makeTranslation(-lightPositionWorld.x,-lightPositionWorld.y,-lightPositionWorld.z);projScreenMatrix.multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse);this._frustum.setFromProjectionMatrix(projScreenMatrix);}});function PointLight(color,intensity,distance,decay){Light.call(this,color,intensity);this.type='PointLight';Object.defineProperty(this,'power',{get:function get(){// intensity = power per solid angle.
  4733. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  4734. return this.intensity*4*Math.PI;},set:function set(power){// intensity = power per solid angle.
  4735. // ref: equation (15) from https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  4736. this.intensity=power/(4*Math.PI);}});this.distance=distance!==undefined?distance:0;this.decay=decay!==undefined?decay:1;// for physically correct lights, should be 2.
  4737. this.shadow=new PointLightShadow();}PointLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:PointLight,isPointLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.distance=source.distance;this.decay=source.decay;this.shadow=source.shadow.clone();return this;}});function OrthographicCamera(){var left=arguments.length>0&&arguments[0]!==undefined?arguments[0]:-1;var right=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var top=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var bottom=arguments.length>3&&arguments[3]!==undefined?arguments[3]:-1;var near=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0.1;var far=arguments.length>5&&arguments[5]!==undefined?arguments[5]:2000;Camera.call(this);this.type='OrthographicCamera';this.zoom=1;this.view=null;this.left=left;this.right=right;this.top=top;this.bottom=bottom;this.near=near;this.far=far;this.updateProjectionMatrix();}OrthographicCamera.prototype=Object.assign(Object.create(Camera.prototype),{constructor:OrthographicCamera,isOrthographicCamera:true,copy:function copy(source,recursive){Camera.prototype.copy.call(this,source,recursive);this.left=source.left;this.right=source.right;this.top=source.top;this.bottom=source.bottom;this.near=source.near;this.far=source.far;this.zoom=source.zoom;this.view=source.view===null?null:Object.assign({},source.view);return this;},setViewOffset:function setViewOffset(fullWidth,fullHeight,x,y,width,height){if(this.view===null){this.view={enabled:true,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1};}this.view.enabled=true;this.view.fullWidth=fullWidth;this.view.fullHeight=fullHeight;this.view.offsetX=x;this.view.offsetY=y;this.view.width=width;this.view.height=height;this.updateProjectionMatrix();},clearViewOffset:function clearViewOffset(){if(this.view!==null){this.view.enabled=false;}this.updateProjectionMatrix();},updateProjectionMatrix:function updateProjectionMatrix(){var dx=(this.right-this.left)/(2*this.zoom);var dy=(this.top-this.bottom)/(2*this.zoom);var cx=(this.right+this.left)/2;var cy=(this.top+this.bottom)/2;var left=cx-dx;var right=cx+dx;var top=cy+dy;var bottom=cy-dy;if(this.view!==null&&this.view.enabled){var scaleW=(this.right-this.left)/this.view.fullWidth/this.zoom;var scaleH=(this.top-this.bottom)/this.view.fullHeight/this.zoom;left+=scaleW*this.view.offsetX;right=left+scaleW*this.view.width;top-=scaleH*this.view.offsetY;bottom=top-scaleH*this.view.height;}this.projectionMatrix.makeOrthographic(left,right,top,bottom,this.near,this.far);this.projectionMatrixInverse.copy(this.projectionMatrix).invert();},toJSON:function toJSON(meta){var data=Object3D.prototype.toJSON.call(this,meta);data.object.zoom=this.zoom;data.object.left=this.left;data.object.right=this.right;data.object.top=this.top;data.object.bottom=this.bottom;data.object.near=this.near;data.object.far=this.far;if(this.view!==null)data.object.view=Object.assign({},this.view);return data;}});function DirectionalLightShadow(){LightShadow.call(this,new OrthographicCamera(-5,5,5,-5,0.5,500));}DirectionalLightShadow.prototype=Object.assign(Object.create(LightShadow.prototype),{constructor:DirectionalLightShadow,isDirectionalLightShadow:true,updateMatrices:function updateMatrices(light){LightShadow.prototype.updateMatrices.call(this,light);}});function DirectionalLight(color,intensity){Light.call(this,color,intensity);this.type='DirectionalLight';this.position.copy(Object3D.DefaultUp);this.updateMatrix();this.target=new Object3D();this.shadow=new DirectionalLightShadow();}DirectionalLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:DirectionalLight,isDirectionalLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.target=source.target.clone();this.shadow=source.shadow.clone();return this;}});function AmbientLight(color,intensity){Light.call(this,color,intensity);this.type='AmbientLight';}AmbientLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:AmbientLight,isAmbientLight:true});function RectAreaLight(color,intensity,width,height){Light.call(this,color,intensity);this.type='RectAreaLight';this.width=width!==undefined?width:10;this.height=height!==undefined?height:10;}RectAreaLight.prototype=Object.assign(Object.create(Light.prototype),{constructor:RectAreaLight,isRectAreaLight:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.width=source.width;this.height=source.height;return this;},toJSON:function toJSON(meta){var data=Light.prototype.toJSON.call(this,meta);data.object.width=this.width;data.object.height=this.height;return data;}});/**
  4738. * Primary reference:
  4739. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  4740. *
  4741. * Secondary reference:
  4742. * https://www.ppsloan.org/publications/StupidSH36.pdf
  4743. */ // 3-band SH defined by 9 coefficients
  4744. class SphericalHarmonics3{constructor(){Object.defineProperty(this,'isSphericalHarmonics3',{value:true});this.coefficients=[];for(var _i297=0;_i297<9;_i297++){this.coefficients.push(new Vector3());}}set(coefficients){for(var _i298=0;_i298<9;_i298++){this.coefficients[_i298].copy(coefficients[_i298]);}return this;}zero(){for(var _i299=0;_i299<9;_i299++){this.coefficients[_i299].set(0,0,0);}return this;}// get the radiance in the direction of the normal
  4745. // target is a Vector3
  4746. getAt(normal,target){// normal is assumed to be unit length
  4747. var x=normal.x,y=normal.y,z=normal.z;var coeff=this.coefficients;// band 0
  4748. target.copy(coeff[0]).multiplyScalar(0.282095);// band 1
  4749. target.addScaledVector(coeff[1],0.488603*y);target.addScaledVector(coeff[2],0.488603*z);target.addScaledVector(coeff[3],0.488603*x);// band 2
  4750. target.addScaledVector(coeff[4],1.092548*(x*y));target.addScaledVector(coeff[5],1.092548*(y*z));target.addScaledVector(coeff[6],0.315392*(3.0*z*z-1.0));target.addScaledVector(coeff[7],1.092548*(x*z));target.addScaledVector(coeff[8],0.546274*(x*x-y*y));return target;}// get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  4751. // target is a Vector3
  4752. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  4753. getIrradianceAt(normal,target){// normal is assumed to be unit length
  4754. var x=normal.x,y=normal.y,z=normal.z;var coeff=this.coefficients;// band 0
  4755. target.copy(coeff[0]).multiplyScalar(0.886227);// π * 0.282095
  4756. // band 1
  4757. target.addScaledVector(coeff[1],2.0*0.511664*y);// ( 2 * π / 3 ) * 0.488603
  4758. target.addScaledVector(coeff[2],2.0*0.511664*z);target.addScaledVector(coeff[3],2.0*0.511664*x);// band 2
  4759. target.addScaledVector(coeff[4],2.0*0.429043*x*y);// ( π / 4 ) * 1.092548
  4760. target.addScaledVector(coeff[5],2.0*0.429043*y*z);target.addScaledVector(coeff[6],0.743125*z*z-0.247708);// ( π / 4 ) * 0.315392 * 3
  4761. target.addScaledVector(coeff[7],2.0*0.429043*x*z);target.addScaledVector(coeff[8],0.429043*(x*x-y*y));// ( π / 4 ) * 0.546274
  4762. return target;}add(sh){for(var _i300=0;_i300<9;_i300++){this.coefficients[_i300].add(sh.coefficients[_i300]);}return this;}addScaledSH(sh,s){for(var _i301=0;_i301<9;_i301++){this.coefficients[_i301].addScaledVector(sh.coefficients[_i301],s);}return this;}scale(s){for(var _i302=0;_i302<9;_i302++){this.coefficients[_i302].multiplyScalar(s);}return this;}lerp(sh,alpha){for(var _i303=0;_i303<9;_i303++){this.coefficients[_i303].lerp(sh.coefficients[_i303],alpha);}return this;}equals(sh){for(var _i304=0;_i304<9;_i304++){if(!this.coefficients[_i304].equals(sh.coefficients[_i304])){return false;}}return true;}copy(sh){return this.set(sh.coefficients);}clone(){return new this.constructor().copy(this);}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var coefficients=this.coefficients;for(var _i305=0;_i305<9;_i305++){coefficients[_i305].fromArray(array,offset+_i305*3);}return this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var coefficients=this.coefficients;for(var _i306=0;_i306<9;_i306++){coefficients[_i306].toArray(array,offset+_i306*3);}return array;}// evaluate the basis functions
  4763. // shBasis is an Array[ 9 ]
  4764. static getBasisAt(normal,shBasis){// normal is assumed to be unit length
  4765. var x=normal.x,y=normal.y,z=normal.z;// band 0
  4766. shBasis[0]=0.282095;// band 1
  4767. shBasis[1]=0.488603*y;shBasis[2]=0.488603*z;shBasis[3]=0.488603*x;// band 2
  4768. shBasis[4]=1.092548*x*y;shBasis[5]=1.092548*y*z;shBasis[6]=0.315392*(3*z*z-1);shBasis[7]=1.092548*x*z;shBasis[8]=0.546274*(x*x-y*y);}}function LightProbe(sh,intensity){Light.call(this,undefined,intensity);this.type='LightProbe';this.sh=sh!==undefined?sh:new SphericalHarmonics3();}LightProbe.prototype=Object.assign(Object.create(Light.prototype),{constructor:LightProbe,isLightProbe:true,copy:function copy(source){Light.prototype.copy.call(this,source);this.sh.copy(source.sh);return this;},fromJSON:function fromJSON(json){this.intensity=json.intensity;// TODO: Move this bit to Light.fromJSON();
  4769. this.sh.fromArray(json.sh);return this;},toJSON:function toJSON(meta){var data=Light.prototype.toJSON.call(this,meta);data.object.sh=this.sh.toArray();return data;}});function MaterialLoader(manager){Loader.call(this,manager);this.textures={};}MaterialLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:MaterialLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.setPath(scope.path);loader.setRequestHeader(scope.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)));}catch(e){if(onError){onError(e);}else {console.error(e);}scope.manager.itemError(url);}},onProgress,onError);},parse:function parse(json){var textures=this.textures;function getTexture(name){if(textures[name]===undefined){console.warn('THREE.MaterialLoader: Undefined texture',name);}return textures[name];}var material=new Materials[json.type]();if(json.uuid!==undefined)material.uuid=json.uuid;if(json.name!==undefined)material.name=json.name;if(json.color!==undefined&&material.color!==undefined)material.color.setHex(json.color);if(json.roughness!==undefined)material.roughness=json.roughness;if(json.metalness!==undefined)material.metalness=json.metalness;if(json.sheen!==undefined)material.sheen=new Color().setHex(json.sheen);if(json.emissive!==undefined&&material.emissive!==undefined)material.emissive.setHex(json.emissive);if(json.specular!==undefined&&material.specular!==undefined)material.specular.setHex(json.specular);if(json.shininess!==undefined)material.shininess=json.shininess;if(json.clearcoat!==undefined)material.clearcoat=json.clearcoat;if(json.clearcoatRoughness!==undefined)material.clearcoatRoughness=json.clearcoatRoughness;if(json.fog!==undefined)material.fog=json.fog;if(json.flatShading!==undefined)material.flatShading=json.flatShading;if(json.blending!==undefined)material.blending=json.blending;if(json.combine!==undefined)material.combine=json.combine;if(json.side!==undefined)material.side=json.side;if(json.opacity!==undefined)material.opacity=json.opacity;if(json.transparent!==undefined)material.transparent=json.transparent;if(json.alphaTest!==undefined)material.alphaTest=json.alphaTest;if(json.depthTest!==undefined)material.depthTest=json.depthTest;if(json.depthWrite!==undefined)material.depthWrite=json.depthWrite;if(json.colorWrite!==undefined)material.colorWrite=json.colorWrite;if(json.stencilWrite!==undefined)material.stencilWrite=json.stencilWrite;if(json.stencilWriteMask!==undefined)material.stencilWriteMask=json.stencilWriteMask;if(json.stencilFunc!==undefined)material.stencilFunc=json.stencilFunc;if(json.stencilRef!==undefined)material.stencilRef=json.stencilRef;if(json.stencilFuncMask!==undefined)material.stencilFuncMask=json.stencilFuncMask;if(json.stencilFail!==undefined)material.stencilFail=json.stencilFail;if(json.stencilZFail!==undefined)material.stencilZFail=json.stencilZFail;if(json.stencilZPass!==undefined)material.stencilZPass=json.stencilZPass;if(json.wireframe!==undefined)material.wireframe=json.wireframe;if(json.wireframeLinewidth!==undefined)material.wireframeLinewidth=json.wireframeLinewidth;if(json.wireframeLinecap!==undefined)material.wireframeLinecap=json.wireframeLinecap;if(json.wireframeLinejoin!==undefined)material.wireframeLinejoin=json.wireframeLinejoin;if(json.rotation!==undefined)material.rotation=json.rotation;if(json.linewidth!==1)material.linewidth=json.linewidth;if(json.dashSize!==undefined)material.dashSize=json.dashSize;if(json.gapSize!==undefined)material.gapSize=json.gapSize;if(json.scale!==undefined)material.scale=json.scale;if(json.polygonOffset!==undefined)material.polygonOffset=json.polygonOffset;if(json.polygonOffsetFactor!==undefined)material.polygonOffsetFactor=json.polygonOffsetFactor;if(json.polygonOffsetUnits!==undefined)material.polygonOffsetUnits=json.polygonOffsetUnits;if(json.skinning!==undefined)material.skinning=json.skinning;if(json.morphTargets!==undefined)material.morphTargets=json.morphTargets;if(json.morphNormals!==undefined)material.morphNormals=json.morphNormals;if(json.dithering!==undefined)material.dithering=json.dithering;if(json.vertexTangents!==undefined)material.vertexTangents=json.vertexTangents;if(json.visible!==undefined)material.visible=json.visible;if(json.toneMapped!==undefined)material.toneMapped=json.toneMapped;if(json.userData!==undefined)material.userData=json.userData;if(json.vertexColors!==undefined){if(typeof json.vertexColors==='number'){material.vertexColors=json.vertexColors>0?true:false;}else {material.vertexColors=json.vertexColors;}}// Shader Material
  4770. if(json.uniforms!==undefined){for(var name in json.uniforms){var uniform=json.uniforms[name];material.uniforms[name]={};switch(uniform.type){case't':material.uniforms[name].value=getTexture(uniform.value);break;case'c':material.uniforms[name].value=new Color().setHex(uniform.value);break;case'v2':material.uniforms[name].value=new Vector2().fromArray(uniform.value);break;case'v3':material.uniforms[name].value=new Vector3().fromArray(uniform.value);break;case'v4':material.uniforms[name].value=new Vector4().fromArray(uniform.value);break;case'm3':material.uniforms[name].value=new Matrix3().fromArray(uniform.value);break;case'm4':material.uniforms[name].value=new Matrix4().fromArray(uniform.value);break;default:material.uniforms[name].value=uniform.value;}}}if(json.defines!==undefined)material.defines=json.defines;if(json.vertexShader!==undefined)material.vertexShader=json.vertexShader;if(json.fragmentShader!==undefined)material.fragmentShader=json.fragmentShader;if(json.extensions!==undefined){for(var key in json.extensions){material.extensions[key]=json.extensions[key];}}// Deprecated
  4771. if(json.shading!==undefined)material.flatShading=json.shading===1;// THREE.FlatShading
  4772. // for PointsMaterial
  4773. if(json.size!==undefined)material.size=json.size;if(json.sizeAttenuation!==undefined)material.sizeAttenuation=json.sizeAttenuation;// maps
  4774. if(json.map!==undefined)material.map=getTexture(json.map);if(json.matcap!==undefined)material.matcap=getTexture(json.matcap);if(json.alphaMap!==undefined)material.alphaMap=getTexture(json.alphaMap);if(json.bumpMap!==undefined)material.bumpMap=getTexture(json.bumpMap);if(json.bumpScale!==undefined)material.bumpScale=json.bumpScale;if(json.normalMap!==undefined)material.normalMap=getTexture(json.normalMap);if(json.normalMapType!==undefined)material.normalMapType=json.normalMapType;if(json.normalScale!==undefined){var normalScale=json.normalScale;if(Array.isArray(normalScale)===false){// Blender exporter used to export a scalar. See #7459
  4775. normalScale=[normalScale,normalScale];}material.normalScale=new Vector2().fromArray(normalScale);}if(json.displacementMap!==undefined)material.displacementMap=getTexture(json.displacementMap);if(json.displacementScale!==undefined)material.displacementScale=json.displacementScale;if(json.displacementBias!==undefined)material.displacementBias=json.displacementBias;if(json.roughnessMap!==undefined)material.roughnessMap=getTexture(json.roughnessMap);if(json.metalnessMap!==undefined)material.metalnessMap=getTexture(json.metalnessMap);if(json.emissiveMap!==undefined)material.emissiveMap=getTexture(json.emissiveMap);if(json.emissiveIntensity!==undefined)material.emissiveIntensity=json.emissiveIntensity;if(json.specularMap!==undefined)material.specularMap=getTexture(json.specularMap);if(json.envMap!==undefined)material.envMap=getTexture(json.envMap);if(json.envMapIntensity!==undefined)material.envMapIntensity=json.envMapIntensity;if(json.reflectivity!==undefined)material.reflectivity=json.reflectivity;if(json.refractionRatio!==undefined)material.refractionRatio=json.refractionRatio;if(json.lightMap!==undefined)material.lightMap=getTexture(json.lightMap);if(json.lightMapIntensity!==undefined)material.lightMapIntensity=json.lightMapIntensity;if(json.aoMap!==undefined)material.aoMap=getTexture(json.aoMap);if(json.aoMapIntensity!==undefined)material.aoMapIntensity=json.aoMapIntensity;if(json.gradientMap!==undefined)material.gradientMap=getTexture(json.gradientMap);if(json.clearcoatMap!==undefined)material.clearcoatMap=getTexture(json.clearcoatMap);if(json.clearcoatRoughnessMap!==undefined)material.clearcoatRoughnessMap=getTexture(json.clearcoatRoughnessMap);if(json.clearcoatNormalMap!==undefined)material.clearcoatNormalMap=getTexture(json.clearcoatNormalMap);if(json.clearcoatNormalScale!==undefined)material.clearcoatNormalScale=new Vector2().fromArray(json.clearcoatNormalScale);if(json.transmission!==undefined)material.transmission=json.transmission;if(json.transmissionMap!==undefined)material.transmissionMap=getTexture(json.transmissionMap);return material;},setTextures:function setTextures(value){this.textures=value;return this;}});var LoaderUtils={decodeText:function decodeText(array){if(typeof TextDecoder!=='undefined'){return new TextDecoder().decode(array);}// Avoid the String.fromCharCode.apply(null, array) shortcut, which
  4776. // throws a "maximum call stack size exceeded" error for large arrays.
  4777. var s='';for(var _i307=0,il=array.length;_i307<il;_i307++){// Implicitly assumes little-endian.
  4778. s+=String.fromCharCode(array[_i307]);}try{// merges multi-byte utf-8 characters.
  4779. return decodeURIComponent(escape(s));}catch(e){// see #16358
  4780. return s;}},extractUrlBase:function extractUrlBase(url){var index=url.lastIndexOf('/');if(index===-1)return './';return url.substr(0,index+1);}};function InstancedBufferGeometry(){BufferGeometry.call(this);this.type='InstancedBufferGeometry';this.instanceCount=Infinity;}InstancedBufferGeometry.prototype=Object.assign(Object.create(BufferGeometry.prototype),{constructor:InstancedBufferGeometry,isInstancedBufferGeometry:true,copy:function copy(source){BufferGeometry.prototype.copy.call(this,source);this.instanceCount=source.instanceCount;return this;},clone:function clone(){return new this.constructor().copy(this);},toJSON:function toJSON(){var data=BufferGeometry.prototype.toJSON.call(this);data.instanceCount=this.instanceCount;data.isInstancedBufferGeometry=true;return data;}});function InstancedBufferAttribute(array,itemSize,normalized,meshPerAttribute){if(typeof normalized==='number'){meshPerAttribute=normalized;normalized=false;console.error('THREE.InstancedBufferAttribute: The constructor now expects normalized as the third argument.');}BufferAttribute.call(this,array,itemSize,normalized);this.meshPerAttribute=meshPerAttribute||1;}InstancedBufferAttribute.prototype=Object.assign(Object.create(BufferAttribute.prototype),{constructor:InstancedBufferAttribute,isInstancedBufferAttribute:true,copy:function copy(source){BufferAttribute.prototype.copy.call(this,source);this.meshPerAttribute=source.meshPerAttribute;return this;},toJSON:function toJSON(){var data=BufferAttribute.prototype.toJSON.call(this);data.meshPerAttribute=this.meshPerAttribute;data.isInstancedBufferAttribute=true;return data;}});function BufferGeometryLoader(manager){Loader.call(this,manager);}BufferGeometryLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:BufferGeometryLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.setPath(scope.path);loader.setRequestHeader(scope.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(text){try{onLoad(scope.parse(JSON.parse(text)));}catch(e){if(onError){onError(e);}else {console.error(e);}scope.manager.itemError(url);}},onProgress,onError);},parse:function parse(json){var interleavedBufferMap={};var arrayBufferMap={};function getInterleavedBuffer(json,uuid){if(interleavedBufferMap[uuid]!==undefined)return interleavedBufferMap[uuid];var interleavedBuffers=json.interleavedBuffers;var interleavedBuffer=interleavedBuffers[uuid];var buffer=getArrayBuffer(json,interleavedBuffer.buffer);var array=getTypedArray(interleavedBuffer.type,buffer);var ib=new InterleavedBuffer(array,interleavedBuffer.stride);ib.uuid=interleavedBuffer.uuid;interleavedBufferMap[uuid]=ib;return ib;}function getArrayBuffer(json,uuid){if(arrayBufferMap[uuid]!==undefined)return arrayBufferMap[uuid];var arrayBuffers=json.arrayBuffers;var arrayBuffer=arrayBuffers[uuid];var ab=new Uint32Array(arrayBuffer).buffer;arrayBufferMap[uuid]=ab;return ab;}var geometry=json.isInstancedBufferGeometry?new InstancedBufferGeometry():new BufferGeometry();var index=json.data.index;if(index!==undefined){var typedArray=getTypedArray(index.type,index.array);geometry.setIndex(new BufferAttribute(typedArray,1));}var attributes=json.data.attributes;for(var key in attributes){var attribute=attributes[key];var bufferAttribute=void 0;if(attribute.isInterleavedBufferAttribute){var interleavedBuffer=getInterleavedBuffer(json.data,attribute.data);bufferAttribute=new InterleavedBufferAttribute(interleavedBuffer,attribute.itemSize,attribute.offset,attribute.normalized);}else {var _typedArray=getTypedArray(attribute.type,attribute.array);var bufferAttributeConstr=attribute.isInstancedBufferAttribute?InstancedBufferAttribute:BufferAttribute;bufferAttribute=new bufferAttributeConstr(_typedArray,attribute.itemSize,attribute.normalized);}if(attribute.name!==undefined)bufferAttribute.name=attribute.name;geometry.setAttribute(key,bufferAttribute);}var morphAttributes=json.data.morphAttributes;if(morphAttributes){for(var _key6 in morphAttributes){var attributeArray=morphAttributes[_key6];var array=[];for(var _i308=0,il=attributeArray.length;_i308<il;_i308++){var _attribute9=attributeArray[_i308];var _bufferAttribute=void 0;if(_attribute9.isInterleavedBufferAttribute){var _interleavedBuffer=getInterleavedBuffer(json.data,_attribute9.data);_bufferAttribute=new InterleavedBufferAttribute(_interleavedBuffer,_attribute9.itemSize,_attribute9.offset,_attribute9.normalized);}else {var _typedArray2=getTypedArray(_attribute9.type,_attribute9.array);_bufferAttribute=new BufferAttribute(_typedArray2,_attribute9.itemSize,_attribute9.normalized);}if(_attribute9.name!==undefined)_bufferAttribute.name=_attribute9.name;array.push(_bufferAttribute);}geometry.morphAttributes[_key6]=array;}}var morphTargetsRelative=json.data.morphTargetsRelative;if(morphTargetsRelative){geometry.morphTargetsRelative=true;}var groups=json.data.groups||json.data.drawcalls||json.data.offsets;if(groups!==undefined){for(var _i309=0,n=groups.length;_i309!==n;++_i309){var group=groups[_i309];geometry.addGroup(group.start,group.count,group.materialIndex);}}var boundingSphere=json.data.boundingSphere;if(boundingSphere!==undefined){var center=new Vector3();if(boundingSphere.center!==undefined){center.fromArray(boundingSphere.center);}geometry.boundingSphere=new Sphere(center,boundingSphere.radius);}if(json.name)geometry.name=json.name;if(json.userData)geometry.userData=json.userData;return geometry;}});class ObjectLoader extends Loader{constructor(manager){super(manager);}load(url,onLoad,onProgress,onError){var scope=this;var path=this.path===''?LoaderUtils.extractUrlBase(url):this.path;this.resourcePath=this.resourcePath||path;var loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setRequestHeader(this.requestHeader);loader.setWithCredentials(this.withCredentials);loader.load(url,function(text){var json=null;try{json=JSON.parse(text);}catch(error){if(onError!==undefined)onError(error);console.error('THREE:ObjectLoader: Can\'t parse '+url+'.',error.message);return;}var metadata=json.metadata;if(metadata===undefined||metadata.type===undefined||metadata.type.toLowerCase()==='geometry'){console.error('THREE.ObjectLoader: Can\'t load '+url);return;}scope.parse(json,onLoad);},onProgress,onError);}parse(json,onLoad){var animations=this.parseAnimations(json.animations);var shapes=this.parseShapes(json.shapes);var geometries=this.parseGeometries(json.geometries,shapes);var images=this.parseImages(json.images,function(){if(onLoad!==undefined)onLoad(object);});var textures=this.parseTextures(json.textures,images);var materials=this.parseMaterials(json.materials,textures);var object=this.parseObject(json.object,geometries,materials,animations);var skeletons=this.parseSkeletons(json.skeletons,object);this.bindSkeletons(object,skeletons);//
  4781. if(onLoad!==undefined){var hasImages=false;for(var uuid in images){if(images[uuid]instanceof HTMLImageElement){hasImages=true;break;}}if(hasImages===false)onLoad(object);}return object;}parseShapes(json){var shapes={};if(json!==undefined){for(var _i310=0,l=json.length;_i310<l;_i310++){var shape=new Shape().fromJSON(json[_i310]);shapes[shape.uuid]=shape;}}return shapes;}parseSkeletons(json,object){var skeletons={};var bones={};// generate bone lookup table
  4782. object.traverse(function(child){if(child.isBone)bones[child.uuid]=child;});// create skeletons
  4783. if(json!==undefined){for(var _i311=0,l=json.length;_i311<l;_i311++){var skeleton=new Skeleton().fromJSON(json[_i311],bones);skeletons[skeleton.uuid]=skeleton;}}return skeletons;}parseGeometries(json,shapes){var geometries={};var geometryShapes;if(json!==undefined){var bufferGeometryLoader=new BufferGeometryLoader();for(var _i312=0,l=json.length;_i312<l;_i312++){var geometry=void 0;var data=json[_i312];switch(data.type){case'PlaneGeometry':case'PlaneBufferGeometry':geometry=new Geometries[data.type](data.width,data.height,data.widthSegments,data.heightSegments);break;case'BoxGeometry':case'BoxBufferGeometry':case'CubeGeometry':// backwards compatible
  4784. geometry=new Geometries[data.type](data.width,data.height,data.depth,data.widthSegments,data.heightSegments,data.depthSegments);break;case'CircleGeometry':case'CircleBufferGeometry':geometry=new Geometries[data.type](data.radius,data.segments,data.thetaStart,data.thetaLength);break;case'CylinderGeometry':case'CylinderBufferGeometry':geometry=new Geometries[data.type](data.radiusTop,data.radiusBottom,data.height,data.radialSegments,data.heightSegments,data.openEnded,data.thetaStart,data.thetaLength);break;case'ConeGeometry':case'ConeBufferGeometry':geometry=new Geometries[data.type](data.radius,data.height,data.radialSegments,data.heightSegments,data.openEnded,data.thetaStart,data.thetaLength);break;case'SphereGeometry':case'SphereBufferGeometry':geometry=new Geometries[data.type](data.radius,data.widthSegments,data.heightSegments,data.phiStart,data.phiLength,data.thetaStart,data.thetaLength);break;case'DodecahedronGeometry':case'DodecahedronBufferGeometry':case'IcosahedronGeometry':case'IcosahedronBufferGeometry':case'OctahedronGeometry':case'OctahedronBufferGeometry':case'TetrahedronGeometry':case'TetrahedronBufferGeometry':geometry=new Geometries[data.type](data.radius,data.detail);break;case'RingGeometry':case'RingBufferGeometry':geometry=new Geometries[data.type](data.innerRadius,data.outerRadius,data.thetaSegments,data.phiSegments,data.thetaStart,data.thetaLength);break;case'TorusGeometry':case'TorusBufferGeometry':geometry=new Geometries[data.type](data.radius,data.tube,data.radialSegments,data.tubularSegments,data.arc);break;case'TorusKnotGeometry':case'TorusKnotBufferGeometry':geometry=new Geometries[data.type](data.radius,data.tube,data.tubularSegments,data.radialSegments,data.p,data.q);break;case'TubeGeometry':case'TubeBufferGeometry':// This only works for built-in curves (e.g. CatmullRomCurve3).
  4785. // User defined curves or instances of CurvePath will not be deserialized.
  4786. geometry=new Geometries[data.type](new Curves[data.path.type]().fromJSON(data.path),data.tubularSegments,data.radius,data.radialSegments,data.closed);break;case'LatheGeometry':case'LatheBufferGeometry':geometry=new Geometries[data.type](data.points,data.segments,data.phiStart,data.phiLength);break;case'PolyhedronGeometry':case'PolyhedronBufferGeometry':geometry=new Geometries[data.type](data.vertices,data.indices,data.radius,data.details);break;case'ShapeGeometry':case'ShapeBufferGeometry':geometryShapes=[];for(var j=0,jl=data.shapes.length;j<jl;j++){var shape=shapes[data.shapes[j]];geometryShapes.push(shape);}geometry=new Geometries[data.type](geometryShapes,data.curveSegments);break;case'ExtrudeGeometry':case'ExtrudeBufferGeometry':geometryShapes=[];for(var _j24=0,_jl8=data.shapes.length;_j24<_jl8;_j24++){var _shape=shapes[data.shapes[_j24]];geometryShapes.push(_shape);}var extrudePath=data.options.extrudePath;if(extrudePath!==undefined){data.options.extrudePath=new Curves[extrudePath.type]().fromJSON(extrudePath);}geometry=new Geometries[data.type](geometryShapes,data.options);break;case'BufferGeometry':case'InstancedBufferGeometry':geometry=bufferGeometryLoader.parse(data);break;case'Geometry':console.error('THREE.ObjectLoader: Loading "Geometry" is not supported anymore.');break;default:console.warn('THREE.ObjectLoader: Unsupported geometry type "'+data.type+'"');continue;}geometry.uuid=data.uuid;if(data.name!==undefined)geometry.name=data.name;if(geometry.isBufferGeometry===true&&data.userData!==undefined)geometry.userData=data.userData;geometries[data.uuid]=geometry;}}return geometries;}parseMaterials(json,textures){var cache={};// MultiMaterial
  4787. var materials={};if(json!==undefined){var loader=new MaterialLoader();loader.setTextures(textures);for(var _i313=0,l=json.length;_i313<l;_i313++){var data=json[_i313];if(data.type==='MultiMaterial'){// Deprecated
  4788. var array=[];for(var j=0;j<data.materials.length;j++){var material=data.materials[j];if(cache[material.uuid]===undefined){cache[material.uuid]=loader.parse(material);}array.push(cache[material.uuid]);}materials[data.uuid]=array;}else {if(cache[data.uuid]===undefined){cache[data.uuid]=loader.parse(data);}materials[data.uuid]=cache[data.uuid];}}}return materials;}parseAnimations(json){var animations={};if(json!==undefined){for(var _i314=0;_i314<json.length;_i314++){var data=json[_i314];var clip=AnimationClip.parse(data);animations[clip.uuid]=clip;}}return animations;}parseImages(json,onLoad){var scope=this;var images={};var loader;function loadImage(url){scope.manager.itemStart(url);return loader.load(url,function(){scope.manager.itemEnd(url);},undefined,function(){scope.manager.itemError(url);scope.manager.itemEnd(url);});}function deserializeImage(image){if(typeof image==='string'){var url=image;var path=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(url)?url:scope.resourcePath+url;return loadImage(path);}else {if(image.data){return {data:getTypedArray(image.type,image.data),width:image.width,height:image.height};}else {return null;}}}if(json!==undefined&&json.length>0){var manager=new LoadingManager(onLoad);loader=new ImageLoader(manager);loader.setCrossOrigin(this.crossOrigin);for(var _i315=0,il=json.length;_i315<il;_i315++){var image=json[_i315];var url=image.url;if(Array.isArray(url)){// load array of images e.g CubeTexture
  4789. images[image.uuid]=[];for(var j=0,jl=url.length;j<jl;j++){var currentUrl=url[j];var deserializedImage=deserializeImage(currentUrl);if(deserializedImage!==null){if(deserializedImage instanceof HTMLImageElement){images[image.uuid].push(deserializedImage);}else {// special case: handle array of data textures for cube textures
  4790. images[image.uuid].push(new DataTexture(deserializedImage.data,deserializedImage.width,deserializedImage.height));}}}}else {// load single image
  4791. var _deserializedImage=deserializeImage(image.url);if(_deserializedImage!==null){images[image.uuid]=_deserializedImage;}}}}return images;}parseTextures(json,images){function parseConstant(value,type){if(typeof value==='number')return value;console.warn('THREE.ObjectLoader.parseTexture: Constant should be in numeric form.',value);return type[value];}var textures={};if(json!==undefined){for(var _i316=0,l=json.length;_i316<l;_i316++){var data=json[_i316];if(data.image===undefined){console.warn('THREE.ObjectLoader: No "image" specified for',data.uuid);}if(images[data.image]===undefined){console.warn('THREE.ObjectLoader: Undefined image',data.image);}var texture=void 0;var image=images[data.image];if(Array.isArray(image)){texture=new CubeTexture(image);if(image.length===6)texture.needsUpdate=true;}else {if(image&&image.data){texture=new DataTexture(image.data,image.width,image.height);}else {texture=new Texture(image);}if(image)texture.needsUpdate=true;// textures can have undefined image data
  4792. }texture.uuid=data.uuid;if(data.name!==undefined)texture.name=data.name;if(data.mapping!==undefined)texture.mapping=parseConstant(data.mapping,TEXTURE_MAPPING);if(data.offset!==undefined)texture.offset.fromArray(data.offset);if(data.repeat!==undefined)texture.repeat.fromArray(data.repeat);if(data.center!==undefined)texture.center.fromArray(data.center);if(data.rotation!==undefined)texture.rotation=data.rotation;if(data.wrap!==undefined){texture.wrapS=parseConstant(data.wrap[0],TEXTURE_WRAPPING);texture.wrapT=parseConstant(data.wrap[1],TEXTURE_WRAPPING);}if(data.format!==undefined)texture.format=data.format;if(data.type!==undefined)texture.type=data.type;if(data.encoding!==undefined)texture.encoding=data.encoding;if(data.minFilter!==undefined)texture.minFilter=parseConstant(data.minFilter,TEXTURE_FILTER);if(data.magFilter!==undefined)texture.magFilter=parseConstant(data.magFilter,TEXTURE_FILTER);if(data.anisotropy!==undefined)texture.anisotropy=data.anisotropy;if(data.flipY!==undefined)texture.flipY=data.flipY;if(data.premultiplyAlpha!==undefined)texture.premultiplyAlpha=data.premultiplyAlpha;if(data.unpackAlignment!==undefined)texture.unpackAlignment=data.unpackAlignment;textures[data.uuid]=texture;}}return textures;}parseObject(data,geometries,materials,animations){var object;function getGeometry(name){if(geometries[name]===undefined){console.warn('THREE.ObjectLoader: Undefined geometry',name);}return geometries[name];}function getMaterial(name){if(name===undefined)return undefined;if(Array.isArray(name)){var array=[];for(var _i317=0,l=name.length;_i317<l;_i317++){var uuid=name[_i317];if(materials[uuid]===undefined){console.warn('THREE.ObjectLoader: Undefined material',uuid);}array.push(materials[uuid]);}return array;}if(materials[name]===undefined){console.warn('THREE.ObjectLoader: Undefined material',name);}return materials[name];}var geometry,material;switch(data.type){case'Scene':object=new Scene();if(data.background!==undefined){if(Number.isInteger(data.background)){object.background=new Color(data.background);}}if(data.fog!==undefined){if(data.fog.type==='Fog'){object.fog=new Fog(data.fog.color,data.fog.near,data.fog.far);}else if(data.fog.type==='FogExp2'){object.fog=new FogExp2(data.fog.color,data.fog.density);}}break;case'PerspectiveCamera':object=new PerspectiveCamera(data.fov,data.aspect,data.near,data.far);if(data.focus!==undefined)object.focus=data.focus;if(data.zoom!==undefined)object.zoom=data.zoom;if(data.filmGauge!==undefined)object.filmGauge=data.filmGauge;if(data.filmOffset!==undefined)object.filmOffset=data.filmOffset;if(data.view!==undefined)object.view=Object.assign({},data.view);break;case'OrthographicCamera':object=new OrthographicCamera(data.left,data.right,data.top,data.bottom,data.near,data.far);if(data.zoom!==undefined)object.zoom=data.zoom;if(data.view!==undefined)object.view=Object.assign({},data.view);break;case'AmbientLight':object=new AmbientLight(data.color,data.intensity);break;case'DirectionalLight':object=new DirectionalLight(data.color,data.intensity);break;case'PointLight':object=new PointLight(data.color,data.intensity,data.distance,data.decay);break;case'RectAreaLight':object=new RectAreaLight(data.color,data.intensity,data.width,data.height);break;case'SpotLight':object=new SpotLight(data.color,data.intensity,data.distance,data.angle,data.penumbra,data.decay);break;case'HemisphereLight':object=new HemisphereLight(data.color,data.groundColor,data.intensity);break;case'LightProbe':object=new LightProbe().fromJSON(data);break;case'SkinnedMesh':geometry=getGeometry(data.geometry);material=getMaterial(data.material);object=new SkinnedMesh(geometry,material);if(data.bindMode!==undefined)object.bindMode=data.bindMode;if(data.bindMatrix!==undefined)object.bindMatrix.fromArray(data.bindMatrix);if(data.skeleton!==undefined)object.skeleton=data.skeleton;break;case'Mesh':geometry=getGeometry(data.geometry);material=getMaterial(data.material);object=new Mesh(geometry,material);break;case'InstancedMesh':geometry=getGeometry(data.geometry);material=getMaterial(data.material);var count=data.count;var instanceMatrix=data.instanceMatrix;object=new InstancedMesh(geometry,material,count);object.instanceMatrix=new BufferAttribute(new Float32Array(instanceMatrix.array),16);break;case'LOD':object=new LOD();break;case'Line':object=new Line(getGeometry(data.geometry),getMaterial(data.material));break;case'LineLoop':object=new LineLoop(getGeometry(data.geometry),getMaterial(data.material));break;case'LineSegments':object=new LineSegments(getGeometry(data.geometry),getMaterial(data.material));break;case'PointCloud':case'Points':object=new Points(getGeometry(data.geometry),getMaterial(data.material));break;case'Sprite':object=new Sprite$1(getMaterial(data.material));break;case'Group':object=new Group();break;case'Bone':object=new Bone();break;default:object=new Object3D();}object.uuid=data.uuid;if(data.name!==undefined)object.name=data.name;if(data.matrix!==undefined){object.matrix.fromArray(data.matrix);if(data.matrixAutoUpdate!==undefined)object.matrixAutoUpdate=data.matrixAutoUpdate;if(object.matrixAutoUpdate)object.matrix.decompose(object.position,object.quaternion,object.scale);}else {if(data.position!==undefined)object.position.fromArray(data.position);if(data.rotation!==undefined)object.rotation.fromArray(data.rotation);if(data.quaternion!==undefined)object.quaternion.fromArray(data.quaternion);if(data.scale!==undefined)object.scale.fromArray(data.scale);}if(data.castShadow!==undefined)object.castShadow=data.castShadow;if(data.receiveShadow!==undefined)object.receiveShadow=data.receiveShadow;if(data.shadow){if(data.shadow.bias!==undefined)object.shadow.bias=data.shadow.bias;if(data.shadow.normalBias!==undefined)object.shadow.normalBias=data.shadow.normalBias;if(data.shadow.radius!==undefined)object.shadow.radius=data.shadow.radius;if(data.shadow.mapSize!==undefined)object.shadow.mapSize.fromArray(data.shadow.mapSize);if(data.shadow.camera!==undefined)object.shadow.camera=this.parseObject(data.shadow.camera);}if(data.visible!==undefined)object.visible=data.visible;if(data.frustumCulled!==undefined)object.frustumCulled=data.frustumCulled;if(data.renderOrder!==undefined)object.renderOrder=data.renderOrder;if(data.userData!==undefined)object.userData=data.userData;if(data.layers!==undefined)object.layers.mask=data.layers;if(data.children!==undefined){var children=data.children;for(var _i318=0;_i318<children.length;_i318++){object.add(this.parseObject(children[_i318],geometries,materials,animations));}}if(data.animations!==undefined){var objectAnimations=data.animations;for(var _i319=0;_i319<objectAnimations.length;_i319++){var uuid=objectAnimations[_i319];object.animations.push(animations[uuid]);}}if(data.type==='LOD'){if(data.autoUpdate!==undefined)object.autoUpdate=data.autoUpdate;var levels=data.levels;for(var l=0;l<levels.length;l++){var level=levels[l];var child=object.getObjectByProperty('uuid',level.object);if(child!==undefined){object.addLevel(child,level.distance);}}}return object;}bindSkeletons(object,skeletons){if(Object.keys(skeletons).length===0)return;object.traverse(function(child){if(child.isSkinnedMesh===true&&child.skeleton!==undefined){var skeleton=skeletons[child.skeleton];if(skeleton===undefined){console.warn('THREE.ObjectLoader: No skeleton found with UUID:',child.skeleton);}else {child.bind(skeleton,child.bindMatrix);}}});}/* DEPRECATED */setTexturePath(value){console.warn('THREE.ObjectLoader: .setTexturePath() has been renamed to .setResourcePath().');return this.setResourcePath(value);}}var TEXTURE_MAPPING={UVMapping:UVMapping,CubeReflectionMapping:CubeReflectionMapping,CubeRefractionMapping:CubeRefractionMapping,EquirectangularReflectionMapping:EquirectangularReflectionMapping,EquirectangularRefractionMapping:EquirectangularRefractionMapping,CubeUVReflectionMapping:CubeUVReflectionMapping,CubeUVRefractionMapping:CubeUVRefractionMapping};var TEXTURE_WRAPPING={RepeatWrapping:RepeatWrapping,ClampToEdgeWrapping:ClampToEdgeWrapping,MirroredRepeatWrapping:MirroredRepeatWrapping};var TEXTURE_FILTER={NearestFilter:NearestFilter,NearestMipmapNearestFilter:NearestMipmapNearestFilter,NearestMipmapLinearFilter:NearestMipmapLinearFilter,LinearFilter:LinearFilter,LinearMipmapNearestFilter:LinearMipmapNearestFilter,LinearMipmapLinearFilter:LinearMipmapLinearFilter};function ImageBitmapLoader(manager){if(typeof createImageBitmap==='undefined'){console.warn('THREE.ImageBitmapLoader: createImageBitmap() not supported.');}if(typeof fetch==='undefined'){console.warn('THREE.ImageBitmapLoader: fetch() not supported.');}Loader.call(this,manager);this.options={premultiplyAlpha:'none'};}ImageBitmapLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:ImageBitmapLoader,isImageBitmapLoader:true,setOptions:function setOptions(options){this.options=options;return this;},load:function load(url,onLoad,onProgress,onError){if(url===undefined)url='';if(this.path!==undefined)url=this.path+url;url=this.manager.resolveURL(url);var scope=this;var cached=Cache.get(url);if(cached!==undefined){scope.manager.itemStart(url);setTimeout(function(){if(onLoad)onLoad(cached);scope.manager.itemEnd(url);},0);return cached;}var fetchOptions={};fetchOptions.credentials=this.crossOrigin==='anonymous'?'same-origin':'include';fetch(url,fetchOptions).then(function(res){return res.blob();}).then(function(blob){//console.log('getBlob', url )
  4793. return createImageBitmap(blob,scope.options);}).then(function(imageBitmap){Cache.add(url,imageBitmap);if(onLoad)onLoad(imageBitmap);scope.manager.itemEnd(url);}).catch(function(e){//console.log('error', url, e)
  4794. if(onError)onError(e,url);scope.manager.itemError(url);scope.manager.itemEnd(url);});scope.manager.itemStart(url);}});function ShapePath(){this.type='ShapePath';this.color=new Color();this.subPaths=[];this.currentPath=null;}Object.assign(ShapePath.prototype,{moveTo:function moveTo(x,y){this.currentPath=new Path();this.subPaths.push(this.currentPath);this.currentPath.moveTo(x,y);return this;},lineTo:function lineTo(x,y){this.currentPath.lineTo(x,y);return this;},quadraticCurveTo:function quadraticCurveTo(aCPx,aCPy,aX,aY){this.currentPath.quadraticCurveTo(aCPx,aCPy,aX,aY);return this;},bezierCurveTo:function bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY){this.currentPath.bezierCurveTo(aCP1x,aCP1y,aCP2x,aCP2y,aX,aY);return this;},splineThru:function splineThru(pts){this.currentPath.splineThru(pts);return this;},toShapes:function toShapes(isCCW,noHoles){function toShapesNoHoles(inSubpaths){var shapes=[];for(var _i320=0,l=inSubpaths.length;_i320<l;_i320++){var _tmpPath=inSubpaths[_i320];var _tmpShape=new Shape();_tmpShape.curves=_tmpPath.curves;shapes.push(_tmpShape);}return shapes;}function isPointInsidePolygon(inPt,inPolygon){var polyLen=inPolygon.length;// inPt on polygon contour => immediate success or
  4795. // toggling of inside/outside at every single! intersection point of an edge
  4796. // with the horizontal line through inPt, left of inPt
  4797. // not counting lowerY endpoints of edges and whole edges on that line
  4798. var inside=false;for(var p=polyLen-1,q=0;q<polyLen;p=q++){var edgeLowPt=inPolygon[p];var edgeHighPt=inPolygon[q];var edgeDx=edgeHighPt.x-edgeLowPt.x;var edgeDy=edgeHighPt.y-edgeLowPt.y;if(Math.abs(edgeDy)>Number.EPSILON){// not parallel
  4799. if(edgeDy<0){edgeLowPt=inPolygon[q];edgeDx=-edgeDx;edgeHighPt=inPolygon[p];edgeDy=-edgeDy;}if(inPt.y<edgeLowPt.y||inPt.y>edgeHighPt.y)continue;if(inPt.y===edgeLowPt.y){if(inPt.x===edgeLowPt.x)return true;// inPt is on contour ?
  4800. // continue; // no intersection or edgeLowPt => doesn't count !!!
  4801. }else {var perpEdge=edgeDy*(inPt.x-edgeLowPt.x)-edgeDx*(inPt.y-edgeLowPt.y);if(perpEdge===0)return true;// inPt is on contour ?
  4802. if(perpEdge<0)continue;inside=!inside;// true intersection left of inPt
  4803. }}else {// parallel or collinear
  4804. if(inPt.y!==edgeLowPt.y)continue;// parallel
  4805. // edge lies on the same horizontal line as inPt
  4806. if(edgeHighPt.x<=inPt.x&&inPt.x<=edgeLowPt.x||edgeLowPt.x<=inPt.x&&inPt.x<=edgeHighPt.x)return true;// inPt: Point on contour !
  4807. // continue;
  4808. }}return inside;}var isClockWise=ShapeUtils.isClockWise;var subPaths=this.subPaths;if(subPaths.length===0)return [];if(noHoles===true)return toShapesNoHoles(subPaths);var solid,tmpPath,tmpShape;var shapes=[];if(subPaths.length===1){tmpPath=subPaths[0];tmpShape=new Shape();tmpShape.curves=tmpPath.curves;shapes.push(tmpShape);return shapes;}var holesFirst=!isClockWise(subPaths[0].getPoints());holesFirst=isCCW?!holesFirst:holesFirst;// console.log("Holes first", holesFirst);
  4809. var betterShapeHoles=[];var newShapes=[];var newShapeHoles=[];var mainIdx=0;var tmpPoints;newShapes[mainIdx]=undefined;newShapeHoles[mainIdx]=[];for(var _i321=0,l=subPaths.length;_i321<l;_i321++){tmpPath=subPaths[_i321];tmpPoints=tmpPath.getPoints();solid=isClockWise(tmpPoints);solid=isCCW?!solid:solid;if(solid){if(!holesFirst&&newShapes[mainIdx])mainIdx++;newShapes[mainIdx]={s:new Shape(),p:tmpPoints};newShapes[mainIdx].s.curves=tmpPath.curves;if(holesFirst)mainIdx++;newShapeHoles[mainIdx]=[];//console.log('cw', i);
  4810. }else {newShapeHoles[mainIdx].push({h:tmpPath,p:tmpPoints[0]});//console.log('ccw', i);
  4811. }}// only Holes? -> probably all Shapes with wrong orientation
  4812. if(!newShapes[0])return toShapesNoHoles(subPaths);if(newShapes.length>1){var ambiguous=false;var toChange=[];for(var sIdx=0,sLen=newShapes.length;sIdx<sLen;sIdx++){betterShapeHoles[sIdx]=[];}for(var _sIdx=0,_sLen=newShapes.length;_sIdx<_sLen;_sIdx++){var sho=newShapeHoles[_sIdx];for(var hIdx=0;hIdx<sho.length;hIdx++){var ho=sho[hIdx];var hole_unassigned=true;for(var s2Idx=0;s2Idx<newShapes.length;s2Idx++){if(isPointInsidePolygon(ho.p,newShapes[s2Idx].p)){if(_sIdx!==s2Idx)toChange.push({froms:_sIdx,tos:s2Idx,hole:hIdx});if(hole_unassigned){hole_unassigned=false;betterShapeHoles[s2Idx].push(ho);}else {ambiguous=true;}}}if(hole_unassigned){betterShapeHoles[_sIdx].push(ho);}}}// console.log("ambiguous: ", ambiguous);
  4813. if(toChange.length>0){// console.log("to change: ", toChange);
  4814. if(!ambiguous)newShapeHoles=betterShapeHoles;}}var tmpHoles;for(var _i322=0,il=newShapes.length;_i322<il;_i322++){tmpShape=newShapes[_i322].s;shapes.push(tmpShape);tmpHoles=newShapeHoles[_i322];for(var j=0,jl=tmpHoles.length;j<jl;j++){tmpShape.holes.push(tmpHoles[j].h);}}//console.log("shape", shapes);
  4815. return shapes;}});function Font(data){this.type='Font';this.data=data;}Object.assign(Font.prototype,{isFont:true,generateShapes:function generateShapes(text){var size=arguments.length>1&&arguments[1]!==undefined?arguments[1]:100;var shapes=[];var paths=createPaths(text,size,this.data);for(var p=0,pl=paths.length;p<pl;p++){Array.prototype.push.apply(shapes,paths[p].toShapes());}return shapes;}});function createPaths(text,size,data){var chars=Array.from?Array.from(text):String(text).split('');// workaround for IE11, see #13988
  4816. var scale=size/data.resolution;var line_height=(data.boundingBox.yMax-data.boundingBox.yMin+data.underlineThickness)*scale;var paths=[];var offsetX=0,offsetY=0;for(var _i323=0;_i323<chars.length;_i323++){var char=chars[_i323];if(char==='\n'){offsetX=0;offsetY-=line_height;}else {var ret=createPath(char,scale,offsetX,offsetY,data);offsetX+=ret.offsetX;paths.push(ret.path);}}return paths;}function createPath(char,scale,offsetX,offsetY,data){var glyph=data.glyphs[char]||data.glyphs['?'];if(!glyph){console.error('THREE.Font: character "'+char+'" does not exists in font family '+data.familyName+'.');return;}var path=new ShapePath();var x,y,cpx,cpy,cpx1,cpy1,cpx2,cpy2;if(glyph.o){var outline=glyph._cachedOutline||(glyph._cachedOutline=glyph.o.split(' '));for(var _i324=0,l=outline.length;_i324<l;){var action=outline[_i324++];switch(action){case'm':// moveTo
  4817. x=outline[_i324++]*scale+offsetX;y=outline[_i324++]*scale+offsetY;path.moveTo(x,y);break;case'l':// lineTo
  4818. x=outline[_i324++]*scale+offsetX;y=outline[_i324++]*scale+offsetY;path.lineTo(x,y);break;case'q':// quadraticCurveTo
  4819. cpx=outline[_i324++]*scale+offsetX;cpy=outline[_i324++]*scale+offsetY;cpx1=outline[_i324++]*scale+offsetX;cpy1=outline[_i324++]*scale+offsetY;path.quadraticCurveTo(cpx1,cpy1,cpx,cpy);break;case'b':// bezierCurveTo
  4820. cpx=outline[_i324++]*scale+offsetX;cpy=outline[_i324++]*scale+offsetY;cpx1=outline[_i324++]*scale+offsetX;cpy1=outline[_i324++]*scale+offsetY;cpx2=outline[_i324++]*scale+offsetX;cpy2=outline[_i324++]*scale+offsetY;path.bezierCurveTo(cpx1,cpy1,cpx2,cpy2,cpx,cpy);break;}}}return {offsetX:glyph.ha*scale,path:path};}function FontLoader(manager){Loader.call(this,manager);}FontLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:FontLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(this.manager);loader.setPath(this.path);loader.setRequestHeader(this.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(text){var json;try{json=JSON.parse(text);}catch(e){console.warn('THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.');json=JSON.parse(text.substring(65,text.length-2));}var font=scope.parse(json);if(onLoad)onLoad(font);},onProgress,onError);},parse:function parse(json){return new Font(json);}});var _context;var AudioContext={getContext:function getContext(){if(_context===undefined){_context=new(window.AudioContext||window.webkitAudioContext)();}return _context;},setContext:function setContext(value){_context=value;}};function AudioLoader(manager){Loader.call(this,manager);}AudioLoader.prototype=Object.assign(Object.create(Loader.prototype),{constructor:AudioLoader,load:function load(url,onLoad,onProgress,onError){var scope=this;var loader=new FileLoader(scope.manager);loader.setResponseType('arraybuffer');loader.setPath(scope.path);loader.setRequestHeader(scope.requestHeader);loader.setWithCredentials(scope.withCredentials);loader.load(url,function(buffer){try{// Create a copy of the buffer. The `decodeAudioData` method
  4821. // detaches the buffer when complete, preventing reuse.
  4822. var bufferCopy=buffer.slice(0);var context=AudioContext.getContext();context.decodeAudioData(bufferCopy,function(audioBuffer){onLoad(audioBuffer);});}catch(e){if(onError){onError(e);}else {console.error(e);}scope.manager.itemError(url);}},onProgress,onError);}});function HemisphereLightProbe(skyColor,groundColor,intensity){LightProbe.call(this,undefined,intensity);var color1=new Color().set(skyColor);var color2=new Color().set(groundColor);var sky=new Vector3(color1.r,color1.g,color1.b);var ground=new Vector3(color2.r,color2.g,color2.b);// without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  4823. var c0=Math.sqrt(Math.PI);var c1=c0*Math.sqrt(0.75);this.sh.coefficients[0].copy(sky).add(ground).multiplyScalar(c0);this.sh.coefficients[1].copy(sky).sub(ground).multiplyScalar(c1);}HemisphereLightProbe.prototype=Object.assign(Object.create(LightProbe.prototype),{constructor:HemisphereLightProbe,isHemisphereLightProbe:true,copy:function copy(source){// modifying colors not currently supported
  4824. LightProbe.prototype.copy.call(this,source);return this;},toJSON:function toJSON(meta){var data=LightProbe.prototype.toJSON.call(this,meta);// data.sh = this.sh.toArray(); // todo
  4825. return data;}});function AmbientLightProbe(color,intensity){LightProbe.call(this,undefined,intensity);var color1=new Color().set(color);// without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  4826. this.sh.coefficients[0].set(color1.r,color1.g,color1.b).multiplyScalar(2*Math.sqrt(Math.PI));}AmbientLightProbe.prototype=Object.assign(Object.create(LightProbe.prototype),{constructor:AmbientLightProbe,isAmbientLightProbe:true,copy:function copy(source){// modifying color not currently supported
  4827. LightProbe.prototype.copy.call(this,source);return this;},toJSON:function toJSON(meta){var data=LightProbe.prototype.toJSON.call(this,meta);// data.sh = this.sh.toArray(); // todo
  4828. return data;}});var _eyeRight=new Matrix4();var _eyeLeft=new Matrix4();function StereoCamera(){this.type='StereoCamera';this.aspect=1;this.eyeSep=0.064;this.cameraL=new PerspectiveCamera();this.cameraL.layers.enable(1);this.cameraL.matrixAutoUpdate=false;this.cameraR=new PerspectiveCamera();this.cameraR.layers.enable(2);this.cameraR.matrixAutoUpdate=false;this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null};}Object.assign(StereoCamera.prototype,{update:function update(camera){var cache=this._cache;var needsUpdate=cache.focus!==camera.focus||cache.fov!==camera.fov||cache.aspect!==camera.aspect*this.aspect||cache.near!==camera.near||cache.far!==camera.far||cache.zoom!==camera.zoom||cache.eyeSep!==this.eyeSep;if(needsUpdate){cache.focus=camera.focus;cache.fov=camera.fov;cache.aspect=camera.aspect*this.aspect;cache.near=camera.near;cache.far=camera.far;cache.zoom=camera.zoom;cache.eyeSep=this.eyeSep;// Off-axis stereoscopic effect based on
  4829. // http://paulbourke.net/stereographics/stereorender/
  4830. var projectionMatrix=camera.projectionMatrix.clone();var eyeSepHalf=cache.eyeSep/2;var eyeSepOnProjection=eyeSepHalf*cache.near/cache.focus;var ymax=cache.near*Math.tan(MathUtils.DEG2RAD*cache.fov*0.5)/cache.zoom;var xmin,xmax;// translate xOffset
  4831. _eyeLeft.elements[12]=-eyeSepHalf;_eyeRight.elements[12]=eyeSepHalf;// for left eye
  4832. xmin=-ymax*cache.aspect+eyeSepOnProjection;xmax=ymax*cache.aspect+eyeSepOnProjection;projectionMatrix.elements[0]=2*cache.near/(xmax-xmin);projectionMatrix.elements[8]=(xmax+xmin)/(xmax-xmin);this.cameraL.projectionMatrix.copy(projectionMatrix);// for right eye
  4833. xmin=-ymax*cache.aspect-eyeSepOnProjection;xmax=ymax*cache.aspect-eyeSepOnProjection;projectionMatrix.elements[0]=2*cache.near/(xmax-xmin);projectionMatrix.elements[8]=(xmax+xmin)/(xmax-xmin);this.cameraR.projectionMatrix.copy(projectionMatrix);}this.cameraL.matrixWorld.copy(camera.matrixWorld).multiply(_eyeLeft);this.cameraR.matrixWorld.copy(camera.matrixWorld).multiply(_eyeRight);}});class Clock{constructor(autoStart){this.autoStart=autoStart!==undefined?autoStart:true;this.startTime=0;this.oldTime=0;this.elapsedTime=0;this.running=false;}start(){this.startTime=now();this.oldTime=this.startTime;this.elapsedTime=0;this.running=true;}stop(){this.getElapsedTime();this.running=false;this.autoStart=false;}getElapsedTime(){this.getDelta();return this.elapsedTime;}getDelta(){var diff=0;if(this.autoStart&&!this.running){this.start();return 0;}if(this.running){var newTime=now();diff=(newTime-this.oldTime)/1000;this.oldTime=newTime;this.elapsedTime+=diff;}return diff;}}function now(){return (typeof performance==='undefined'?Date:performance).now();// see #10732
  4834. }var _position$2=/*@__PURE__*/new Vector3();var _quaternion$3=/*@__PURE__*/new Quaternion();var _scale$1=/*@__PURE__*/new Vector3();var _orientation=/*@__PURE__*/new Vector3();class AudioListener extends Object3D{constructor(){super();this.type='AudioListener';this.context=AudioContext.getContext();this.gain=this.context.createGain();this.gain.connect(this.context.destination);this.filter=null;this.timeDelta=0;// private
  4835. this._clock=new Clock();}getInput(){return this.gain;}removeFilter(){if(this.filter!==null){this.gain.disconnect(this.filter);this.filter.disconnect(this.context.destination);this.gain.connect(this.context.destination);this.filter=null;}return this;}getFilter(){return this.filter;}setFilter(value){if(this.filter!==null){this.gain.disconnect(this.filter);this.filter.disconnect(this.context.destination);}else {this.gain.disconnect(this.context.destination);}this.filter=value;this.gain.connect(this.filter);this.filter.connect(this.context.destination);return this;}getMasterVolume(){return this.gain.gain.value;}setMasterVolume(value){this.gain.gain.setTargetAtTime(value,this.context.currentTime,0.01);return this;}updateMatrixWorld(force){super.updateMatrixWorld(force);var listener=this.context.listener;var up=this.up;this.timeDelta=this._clock.getDelta();this.matrixWorld.decompose(_position$2,_quaternion$3,_scale$1);_orientation.set(0,0,-1).applyQuaternion(_quaternion$3);if(listener.positionX){// code path for Chrome (see #14393)
  4836. var endTime=this.context.currentTime+this.timeDelta;listener.positionX.linearRampToValueAtTime(_position$2.x,endTime);listener.positionY.linearRampToValueAtTime(_position$2.y,endTime);listener.positionZ.linearRampToValueAtTime(_position$2.z,endTime);listener.forwardX.linearRampToValueAtTime(_orientation.x,endTime);listener.forwardY.linearRampToValueAtTime(_orientation.y,endTime);listener.forwardZ.linearRampToValueAtTime(_orientation.z,endTime);listener.upX.linearRampToValueAtTime(up.x,endTime);listener.upY.linearRampToValueAtTime(up.y,endTime);listener.upZ.linearRampToValueAtTime(up.z,endTime);}else {listener.setPosition(_position$2.x,_position$2.y,_position$2.z);listener.setOrientation(_orientation.x,_orientation.y,_orientation.z,up.x,up.y,up.z);}}}class Audio extends Object3D{constructor(listener){super();this.type='Audio';this.listener=listener;this.context=listener.context;this.gain=this.context.createGain();this.gain.connect(listener.getInput());this.autoplay=false;this.buffer=null;this.detune=0;this.loop=false;this.loopStart=0;this.loopEnd=0;this.offset=0;this.duration=undefined;this.playbackRate=1;this.isPlaying=false;this.hasPlaybackControl=true;this.source=null;this.sourceType='empty';this._startedAt=0;this._progress=0;this._connected=false;this.filters=[];}getOutput(){return this.gain;}setNodeSource(audioNode){this.hasPlaybackControl=false;this.sourceType='audioNode';this.source=audioNode;this.connect();return this;}setMediaElementSource(mediaElement){this.hasPlaybackControl=false;this.sourceType='mediaNode';this.source=this.context.createMediaElementSource(mediaElement);this.connect();return this;}setMediaStreamSource(mediaStream){this.hasPlaybackControl=false;this.sourceType='mediaStreamNode';this.source=this.context.createMediaStreamSource(mediaStream);this.connect();return this;}setBuffer(audioBuffer){this.buffer=audioBuffer;this.sourceType='buffer';if(this.autoplay)this.play();return this;}play(){var delay=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;if(this.isPlaying===true){console.warn('THREE.Audio: Audio is already playing.');return;}if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}this._startedAt=this.context.currentTime+delay;var source=this.context.createBufferSource();source.buffer=this.buffer;source.loop=this.loop;source.loopStart=this.loopStart;source.loopEnd=this.loopEnd;source.onended=this.onEnded.bind(this);source.start(this._startedAt,this._progress+this.offset,this.duration);this.isPlaying=true;this.source=source;this.setDetune(this.detune);this.setPlaybackRate(this.playbackRate);return this.connect();}pause(){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}if(this.isPlaying===true){// update current progress
  4837. this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate;if(this.loop===true){// ensure _progress does not exceed duration with looped audios
  4838. this._progress=this._progress%(this.duration||this.buffer.duration);}this.source.stop();this.source.onended=null;this.isPlaying=false;}return this;}stop(){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}this._progress=0;this.source.stop();this.source.onended=null;this.isPlaying=false;return this;}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(var _i325=1,l=this.filters.length;_i325<l;_i325++){this.filters[_i325-1].connect(this.filters[_i325]);}this.filters[this.filters.length-1].connect(this.getOutput());}else {this.source.connect(this.getOutput());}this._connected=true;return this;}disconnect(){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(var _i326=1,l=this.filters.length;_i326<l;_i326++){this.filters[_i326-1].disconnect(this.filters[_i326]);}this.filters[this.filters.length-1].disconnect(this.getOutput());}else {this.source.disconnect(this.getOutput());}this._connected=false;return this;}getFilters(){return this.filters;}setFilters(value){if(!value)value=[];if(this._connected===true){this.disconnect();this.filters=value.slice();this.connect();}else {this.filters=value.slice();}return this;}setDetune(value){this.detune=value;if(this.source.detune===undefined)return;// only set detune when available
  4839. if(this.isPlaying===true){this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,0.01);}return this;}getDetune(){return this.detune;}getFilter(){return this.getFilters()[0];}setFilter(filter){return this.setFilters(filter?[filter]:[]);}setPlaybackRate(value){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}this.playbackRate=value;if(this.isPlaying===true){this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,0.01);}return this;}getPlaybackRate(){return this.playbackRate;}onEnded(){this.isPlaying=false;}getLoop(){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return false;}return this.loop;}setLoop(value){if(this.hasPlaybackControl===false){console.warn('THREE.Audio: this Audio has no playback control.');return;}this.loop=value;if(this.isPlaying===true){this.source.loop=this.loop;}return this;}setLoopStart(value){this.loopStart=value;return this;}setLoopEnd(value){this.loopEnd=value;return this;}getVolume(){return this.gain.gain.value;}setVolume(value){this.gain.gain.setTargetAtTime(value,this.context.currentTime,0.01);return this;}}var _position$3=/*@__PURE__*/new Vector3();var _quaternion$4=/*@__PURE__*/new Quaternion();var _scale$2=/*@__PURE__*/new Vector3();var _orientation$1=/*@__PURE__*/new Vector3();class PositionalAudio extends Audio{constructor(listener){super(listener);this.panner=this.context.createPanner();this.panner.panningModel='HRTF';this.panner.connect(this.gain);}getOutput(){return this.panner;}getRefDistance(){return this.panner.refDistance;}setRefDistance(value){this.panner.refDistance=value;return this;}getRolloffFactor(){return this.panner.rolloffFactor;}setRolloffFactor(value){this.panner.rolloffFactor=value;return this;}getDistanceModel(){return this.panner.distanceModel;}setDistanceModel(value){this.panner.distanceModel=value;return this;}getMaxDistance(){return this.panner.maxDistance;}setMaxDistance(value){this.panner.maxDistance=value;return this;}setDirectionalCone(coneInnerAngle,coneOuterAngle,coneOuterGain){this.panner.coneInnerAngle=coneInnerAngle;this.panner.coneOuterAngle=coneOuterAngle;this.panner.coneOuterGain=coneOuterGain;return this;}updateMatrixWorld(force){super.updateMatrixWorld(force);if(this.hasPlaybackControl===true&&this.isPlaying===false)return;this.matrixWorld.decompose(_position$3,_quaternion$4,_scale$2);_orientation$1.set(0,0,1).applyQuaternion(_quaternion$4);var panner=this.panner;if(panner.positionX){// code path for Chrome and Firefox (see #14393)
  4840. var endTime=this.context.currentTime+this.listener.timeDelta;panner.positionX.linearRampToValueAtTime(_position$3.x,endTime);panner.positionY.linearRampToValueAtTime(_position$3.y,endTime);panner.positionZ.linearRampToValueAtTime(_position$3.z,endTime);panner.orientationX.linearRampToValueAtTime(_orientation$1.x,endTime);panner.orientationY.linearRampToValueAtTime(_orientation$1.y,endTime);panner.orientationZ.linearRampToValueAtTime(_orientation$1.z,endTime);}else {panner.setPosition(_position$3.x,_position$3.y,_position$3.z);panner.setOrientation(_orientation$1.x,_orientation$1.y,_orientation$1.z);}}}class AudioAnalyser{constructor(audio){var fftSize=arguments.length>1&&arguments[1]!==undefined?arguments[1]:2048;this.analyser=audio.context.createAnalyser();this.analyser.fftSize=fftSize;this.data=new Uint8Array(this.analyser.frequencyBinCount);audio.getOutput().connect(this.analyser);}getFrequencyData(){this.analyser.getByteFrequencyData(this.data);return this.data;}getAverageFrequency(){var value=0;var data=this.getFrequencyData();for(var _i327=0;_i327<data.length;_i327++){value+=data[_i327];}return value/data.length;}}function PropertyMixer(binding,typeName,valueSize){this.binding=binding;this.valueSize=valueSize;var mixFunction,mixFunctionAdditive,setIdentity;// buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  4841. //
  4842. // interpolators can use .buffer as their .result
  4843. // the data then goes to 'incoming'
  4844. //
  4845. // 'accu0' and 'accu1' are used frame-interleaved for
  4846. // the cumulative result and are compared to detect
  4847. // changes
  4848. //
  4849. // 'orig' stores the original state of the property
  4850. //
  4851. // 'add' is used for additive cumulative results
  4852. //
  4853. // 'work' is optional and is only present for quaternion types. It is used
  4854. // to store intermediate quaternion multiplication results
  4855. switch(typeName){case'quaternion':mixFunction=this._slerp;mixFunctionAdditive=this._slerpAdditive;setIdentity=this._setAdditiveIdentityQuaternion;this.buffer=new Float64Array(valueSize*6);this._workIndex=5;break;case'string':case'bool':mixFunction=this._select;// Use the regular mix function and for additive on these types,
  4856. // additive is not relevant for non-numeric types
  4857. mixFunctionAdditive=this._select;setIdentity=this._setAdditiveIdentityOther;this.buffer=new Array(valueSize*5);break;default:mixFunction=this._lerp;mixFunctionAdditive=this._lerpAdditive;setIdentity=this._setAdditiveIdentityNumeric;this.buffer=new Float64Array(valueSize*5);}this._mixBufferRegion=mixFunction;this._mixBufferRegionAdditive=mixFunctionAdditive;this._setIdentity=setIdentity;this._origIndex=3;this._addIndex=4;this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;this.useCount=0;this.referenceCount=0;}Object.assign(PropertyMixer.prototype,{// accumulate data in the 'incoming' region into 'accu<i>'
  4858. accumulate:function accumulate(accuIndex,weight){// note: happily accumulating nothing when weight = 0, the caller knows
  4859. // the weight and shouldn't have made the call in the first place
  4860. var buffer=this.buffer,stride=this.valueSize,offset=accuIndex*stride+stride;var currentWeight=this.cumulativeWeight;if(currentWeight===0){// accuN := incoming * weight
  4861. for(var _i328=0;_i328!==stride;++_i328){buffer[offset+_i328]=buffer[_i328];}currentWeight=weight;}else {// accuN := accuN + incoming * weight
  4862. currentWeight+=weight;var mix=weight/currentWeight;this._mixBufferRegion(buffer,offset,0,mix,stride);}this.cumulativeWeight=currentWeight;},// accumulate data in the 'incoming' region into 'add'
  4863. accumulateAdditive:function accumulateAdditive(weight){var buffer=this.buffer,stride=this.valueSize,offset=stride*this._addIndex;if(this.cumulativeWeightAdditive===0){// add = identity
  4864. this._setIdentity();}// add := add + incoming * weight
  4865. this._mixBufferRegionAdditive(buffer,offset,0,weight,stride);this.cumulativeWeightAdditive+=weight;},// apply the state of 'accu<i>' to the binding when accus differ
  4866. apply:function apply(accuIndex){var stride=this.valueSize,buffer=this.buffer,offset=accuIndex*stride+stride,weight=this.cumulativeWeight,weightAdditive=this.cumulativeWeightAdditive,binding=this.binding;this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;if(weight<1){// accuN := accuN + original * ( 1 - cumulativeWeight )
  4867. var originalValueOffset=stride*this._origIndex;this._mixBufferRegion(buffer,offset,originalValueOffset,1-weight,stride);}if(weightAdditive>0){// accuN := accuN + additive accuN
  4868. this._mixBufferRegionAdditive(buffer,offset,this._addIndex*stride,1,stride);}for(var _i329=stride,e=stride+stride;_i329!==e;++_i329){if(buffer[_i329]!==buffer[_i329+stride]){// value has changed -> update scene graph
  4869. binding.setValue(buffer,offset);break;}}},// remember the state of the bound property and copy it to both accus
  4870. saveOriginalState:function saveOriginalState(){var binding=this.binding;var buffer=this.buffer,stride=this.valueSize,originalValueOffset=stride*this._origIndex;binding.getValue(buffer,originalValueOffset);// accu[0..1] := orig -- initially detect changes against the original
  4871. for(var _i330=stride,e=originalValueOffset;_i330!==e;++_i330){buffer[_i330]=buffer[originalValueOffset+_i330%stride];}// Add to identity for additive
  4872. this._setIdentity();this.cumulativeWeight=0;this.cumulativeWeightAdditive=0;},// apply the state previously taken via 'saveOriginalState' to the binding
  4873. restoreOriginalState:function restoreOriginalState(){var originalValueOffset=this.valueSize*3;this.binding.setValue(this.buffer,originalValueOffset);},_setAdditiveIdentityNumeric:function _setAdditiveIdentityNumeric(){var startIndex=this._addIndex*this.valueSize;var endIndex=startIndex+this.valueSize;for(var _i331=startIndex;_i331<endIndex;_i331++){this.buffer[_i331]=0;}},_setAdditiveIdentityQuaternion:function _setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric();this.buffer[this._addIndex*this.valueSize+3]=1;},_setAdditiveIdentityOther:function _setAdditiveIdentityOther(){var startIndex=this._origIndex*this.valueSize;var targetIndex=this._addIndex*this.valueSize;for(var _i332=0;_i332<this.valueSize;_i332++){this.buffer[targetIndex+_i332]=this.buffer[startIndex+_i332];}},// mix functions
  4874. _select:function _select(buffer,dstOffset,srcOffset,t,stride){if(t>=0.5){for(var _i333=0;_i333!==stride;++_i333){buffer[dstOffset+_i333]=buffer[srcOffset+_i333];}}},_slerp:function _slerp(buffer,dstOffset,srcOffset,t){Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,srcOffset,t);},_slerpAdditive:function _slerpAdditive(buffer,dstOffset,srcOffset,t,stride){var workOffset=this._workIndex*stride;// Store result in intermediate buffer offset
  4875. Quaternion.multiplyQuaternionsFlat(buffer,workOffset,buffer,dstOffset,buffer,srcOffset);// Slerp to the intermediate result
  4876. Quaternion.slerpFlat(buffer,dstOffset,buffer,dstOffset,buffer,workOffset,t);},_lerp:function _lerp(buffer,dstOffset,srcOffset,t,stride){var s=1-t;for(var _i334=0;_i334!==stride;++_i334){var j=dstOffset+_i334;buffer[j]=buffer[j]*s+buffer[srcOffset+_i334]*t;}},_lerpAdditive:function _lerpAdditive(buffer,dstOffset,srcOffset,t,stride){for(var _i335=0;_i335!==stride;++_i335){var j=dstOffset+_i335;buffer[j]=buffer[j]+buffer[srcOffset+_i335]*t;}}});// Characters [].:/ are reserved for track binding syntax.
  4877. var _RESERVED_CHARS_RE='\\[\\]\\.:\\/';var _reservedRe=new RegExp('['+_RESERVED_CHARS_RE+']','g');// Attempts to allow node names from any language. ES5's `\w` regexp matches
  4878. // only latin characters, and the unicode \p{L} is not yet supported. So
  4879. // instead, we exclude reserved characters and match everything else.
  4880. var _wordChar='[^'+_RESERVED_CHARS_RE+']';var _wordCharOrDot='[^'+_RESERVED_CHARS_RE.replace('\\.','')+']';// Parent directories, delimited by '/' or ':'. Currently unused, but must
  4881. // be matched to parse the rest of the track name.
  4882. var _directoryRe=/((?:WC+[\/:])*)/.source.replace('WC',_wordChar);// Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  4883. var _nodeRe=/(WCOD+)?/.source.replace('WCOD',_wordCharOrDot);// Object on target node, and accessor. May not contain reserved
  4884. // characters. Accessor may contain any character except closing bracket.
  4885. var _objectRe=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace('WC',_wordChar);// Property and accessor. May not contain reserved characters. Accessor may
  4886. // contain any non-bracket characters.
  4887. var _propertyRe=/\.(WC+)(?:\[(.+)\])?/.source.replace('WC',_wordChar);var _trackRe=new RegExp(''+'^'+_directoryRe+_nodeRe+_objectRe+_propertyRe+'$');var _supportedObjectNames=['material','materials','bones'];function Composite(targetGroup,path,optionalParsedPath){var parsedPath=optionalParsedPath||PropertyBinding.parseTrackName(path);this._targetGroup=targetGroup;this._bindings=targetGroup.subscribe_(path,parsedPath);}Object.assign(Composite.prototype,{getValue:function getValue(array,offset){this.bind();// bind all binding
  4888. var firstValidIndex=this._targetGroup.nCachedObjects_,binding=this._bindings[firstValidIndex];// and only call .getValue on the first
  4889. if(binding!==undefined)binding.getValue(array,offset);},setValue:function setValue(array,offset){var bindings=this._bindings;for(var _i336=this._targetGroup.nCachedObjects_,n=bindings.length;_i336!==n;++_i336){bindings[_i336].setValue(array,offset);}},bind:function bind(){var bindings=this._bindings;for(var _i337=this._targetGroup.nCachedObjects_,n=bindings.length;_i337!==n;++_i337){bindings[_i337].bind();}},unbind:function unbind(){var bindings=this._bindings;for(var _i338=this._targetGroup.nCachedObjects_,n=bindings.length;_i338!==n;++_i338){bindings[_i338].unbind();}}});function PropertyBinding(rootNode,path,parsedPath){this.path=path;this.parsedPath=parsedPath||PropertyBinding.parseTrackName(path);this.node=PropertyBinding.findNode(rootNode,this.parsedPath.nodeName)||rootNode;this.rootNode=rootNode;}Object.assign(PropertyBinding,{Composite:Composite,create:function create(root,path,parsedPath){if(!(root&&root.isAnimationObjectGroup)){return new PropertyBinding(root,path,parsedPath);}else {return new PropertyBinding.Composite(root,path,parsedPath);}},/**
  4890. * Replaces spaces with underscores and removes unsupported characters from
  4891. * node names, to ensure compatibility with parseTrackName().
  4892. *
  4893. * @param {string} name Node name to be sanitized.
  4894. * @return {string}
  4895. */sanitizeNodeName:function sanitizeNodeName(name){return name.replace(/\s/g,'_').replace(_reservedRe,'');},parseTrackName:function parseTrackName(trackName){var matches=_trackRe.exec(trackName);if(!matches){throw new Error('PropertyBinding: Cannot parse trackName: '+trackName);}var results={// directoryName: matches[ 1 ], // (tschw) currently unused
  4896. nodeName:matches[2],objectName:matches[3],objectIndex:matches[4],propertyName:matches[5],// required
  4897. propertyIndex:matches[6]};var lastDot=results.nodeName&&results.nodeName.lastIndexOf('.');if(lastDot!==undefined&&lastDot!==-1){var objectName=results.nodeName.substring(lastDot+1);// Object names must be checked against an allowlist. Otherwise, there
  4898. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  4899. // 'bar' could be the objectName, or part of a nodeName (which can
  4900. // include '.' characters).
  4901. if(_supportedObjectNames.indexOf(objectName)!==-1){results.nodeName=results.nodeName.substring(0,lastDot);results.objectName=objectName;}}if(results.propertyName===null||results.propertyName.length===0){throw new Error('PropertyBinding: can not parse propertyName from trackName: '+trackName);}return results;},findNode:function findNode(root,nodeName){if(!nodeName||nodeName===''||nodeName==='.'||nodeName===-1||nodeName===root.name||nodeName===root.uuid){return root;}// search into skeleton bones.
  4902. if(root.skeleton){var bone=root.skeleton.getBoneByName(nodeName);if(bone!==undefined){return bone;}}// search into node subtree.
  4903. if(root.children){var _searchNodeSubtree=function searchNodeSubtree(children){for(var _i339=0;_i339<children.length;_i339++){var childNode=children[_i339];if(childNode.name===nodeName||childNode.uuid===nodeName){return childNode;}var result=_searchNodeSubtree(childNode.children);if(result)return result;}return null;};var subTreeNode=_searchNodeSubtree(root.children);if(subTreeNode){return subTreeNode;}}return null;}});Object.assign(PropertyBinding.prototype,{// prototype, continued
  4904. // these are used to "bind" a nonexistent property
  4905. _getValue_unavailable:function _getValue_unavailable(){},_setValue_unavailable:function _setValue_unavailable(){},BindingType:{Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Versioning:{None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},GetterByBindingType:[function getValue_direct(buffer,offset){buffer[offset]=this.node[this.propertyName];},function getValue_array(buffer,offset){var source=this.resolvedProperty;for(var _i340=0,n=source.length;_i340!==n;++_i340){buffer[offset++]=source[_i340];}},function getValue_arrayElement(buffer,offset){buffer[offset]=this.resolvedProperty[this.propertyIndex];},function getValue_toArray(buffer,offset){this.resolvedProperty.toArray(buffer,offset);}],SetterByBindingTypeAndVersioning:[[// Direct
  4906. function setValue_direct(buffer,offset){this.targetObject[this.propertyName]=buffer[offset];},function setValue_direct_setNeedsUpdate(buffer,offset){this.targetObject[this.propertyName]=buffer[offset];this.targetObject.needsUpdate=true;},function setValue_direct_setMatrixWorldNeedsUpdate(buffer,offset){this.targetObject[this.propertyName]=buffer[offset];this.targetObject.matrixWorldNeedsUpdate=true;}],[// EntireArray
  4907. function setValue_array(buffer,offset){var dest=this.resolvedProperty;for(var _i341=0,n=dest.length;_i341!==n;++_i341){dest[_i341]=buffer[offset++];}},function setValue_array_setNeedsUpdate(buffer,offset){var dest=this.resolvedProperty;for(var _i342=0,n=dest.length;_i342!==n;++_i342){dest[_i342]=buffer[offset++];}this.targetObject.needsUpdate=true;},function setValue_array_setMatrixWorldNeedsUpdate(buffer,offset){var dest=this.resolvedProperty;for(var _i343=0,n=dest.length;_i343!==n;++_i343){dest[_i343]=buffer[offset++];}this.targetObject.matrixWorldNeedsUpdate=true;}],[// ArrayElement
  4908. function setValue_arrayElement(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset];},function setValue_arrayElement_setNeedsUpdate(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset];this.targetObject.needsUpdate=true;},function setValue_arrayElement_setMatrixWorldNeedsUpdate(buffer,offset){this.resolvedProperty[this.propertyIndex]=buffer[offset];this.targetObject.matrixWorldNeedsUpdate=true;}],[// HasToFromArray
  4909. function setValue_fromArray(buffer,offset){this.resolvedProperty.fromArray(buffer,offset);},function setValue_fromArray_setNeedsUpdate(buffer,offset){this.resolvedProperty.fromArray(buffer,offset);this.targetObject.needsUpdate=true;},function setValue_fromArray_setMatrixWorldNeedsUpdate(buffer,offset){this.resolvedProperty.fromArray(buffer,offset);this.targetObject.matrixWorldNeedsUpdate=true;}]],getValue:function getValue_unbound(targetArray,offset){this.bind();this.getValue(targetArray,offset);// Note: This class uses a State pattern on a per-method basis:
  4910. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  4911. // prototype version of these methods with one that represents
  4912. // the bound state. When the property is not found, the methods
  4913. // become no-ops.
  4914. },setValue:function getValue_unbound(sourceArray,offset){this.bind();this.setValue(sourceArray,offset);},// create getter / setter pair for a property in the scene graph
  4915. bind:function bind(){var targetObject=this.node;var parsedPath=this.parsedPath;var objectName=parsedPath.objectName;var propertyName=parsedPath.propertyName;var propertyIndex=parsedPath.propertyIndex;if(!targetObject){targetObject=PropertyBinding.findNode(this.rootNode,parsedPath.nodeName)||this.rootNode;this.node=targetObject;}// set fail state so we can just 'return' on error
  4916. this.getValue=this._getValue_unavailable;this.setValue=this._setValue_unavailable;// ensure there is a value node
  4917. if(!targetObject){console.error('THREE.PropertyBinding: Trying to update node for track: '+this.path+' but it wasn\'t found.');return;}if(objectName){var objectIndex=parsedPath.objectIndex;// special cases were we need to reach deeper into the hierarchy to get the face materials....
  4918. switch(objectName){case'materials':if(!targetObject.material){console.error('THREE.PropertyBinding: Can not bind to material as node does not have a material.',this);return;}if(!targetObject.material.materials){console.error('THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.',this);return;}targetObject=targetObject.material.materials;break;case'bones':if(!targetObject.skeleton){console.error('THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.',this);return;}// potential future optimization: skip this if propertyIndex is already an integer
  4919. // and convert the integer string to a true integer.
  4920. targetObject=targetObject.skeleton.bones;// support resolving morphTarget names into indices.
  4921. for(var _i344=0;_i344<targetObject.length;_i344++){if(targetObject[_i344].name===objectIndex){objectIndex=_i344;break;}}break;default:if(targetObject[objectName]===undefined){console.error('THREE.PropertyBinding: Can not bind to objectName of node undefined.',this);return;}targetObject=targetObject[objectName];}if(objectIndex!==undefined){if(targetObject[objectIndex]===undefined){console.error('THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.',this,targetObject);return;}targetObject=targetObject[objectIndex];}}// resolve property
  4922. var nodeProperty=targetObject[propertyName];if(nodeProperty===undefined){var nodeName=parsedPath.nodeName;console.error('THREE.PropertyBinding: Trying to update property for track: '+nodeName+'.'+propertyName+' but it wasn\'t found.',targetObject);return;}// determine versioning scheme
  4923. var versioning=this.Versioning.None;this.targetObject=targetObject;if(targetObject.needsUpdate!==undefined){// material
  4924. versioning=this.Versioning.NeedsUpdate;}else if(targetObject.matrixWorldNeedsUpdate!==undefined){// node transform
  4925. versioning=this.Versioning.MatrixWorldNeedsUpdate;}// determine how the property gets bound
  4926. var bindingType=this.BindingType.Direct;if(propertyIndex!==undefined){// access a sub element of the property array (only primitives are supported right now)
  4927. if(propertyName==='morphTargetInfluences'){// potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  4928. // support resolving morphTarget names into indices.
  4929. if(!targetObject.geometry){console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.',this);return;}if(targetObject.geometry.isBufferGeometry){if(!targetObject.geometry.morphAttributes){console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.',this);return;}if(targetObject.morphTargetDictionary[propertyIndex]!==undefined){propertyIndex=targetObject.morphTargetDictionary[propertyIndex];}}else {console.error('THREE.PropertyBinding: Can not bind to morphTargetInfluences on THREE.Geometry. Use THREE.BufferGeometry instead.',this);return;}}bindingType=this.BindingType.ArrayElement;this.resolvedProperty=nodeProperty;this.propertyIndex=propertyIndex;}else if(nodeProperty.fromArray!==undefined&&nodeProperty.toArray!==undefined){// must use copy for Object3D.Euler/Quaternion
  4930. bindingType=this.BindingType.HasFromToArray;this.resolvedProperty=nodeProperty;}else if(Array.isArray(nodeProperty)){bindingType=this.BindingType.EntireArray;this.resolvedProperty=nodeProperty;}else {this.propertyName=propertyName;}// select getter / setter
  4931. this.getValue=this.GetterByBindingType[bindingType];this.setValue=this.SetterByBindingTypeAndVersioning[bindingType][versioning];},unbind:function unbind(){this.node=null;// back to the prototype version of getValue / setValue
  4932. // note: avoiding to mutate the shape of 'this' via 'delete'
  4933. this.getValue=this._getValue_unbound;this.setValue=this._setValue_unbound;}});// DECLARE ALIAS AFTER assign prototype
  4934. Object.assign(PropertyBinding.prototype,{// initial state of these methods that calls 'bind'
  4935. _getValue_unbound:PropertyBinding.prototype.getValue,_setValue_unbound:PropertyBinding.prototype.setValue});/**
  4936. *
  4937. * A group of objects that receives a shared animation state.
  4938. *
  4939. * Usage:
  4940. *
  4941. * - Add objects you would otherwise pass as 'root' to the
  4942. * constructor or the .clipAction method of AnimationMixer.
  4943. *
  4944. * - Instead pass this object as 'root'.
  4945. *
  4946. * - You can also add and remove objects later when the mixer
  4947. * is running.
  4948. *
  4949. * Note:
  4950. *
  4951. * Objects of this class appear as one object to the mixer,
  4952. * so cache control of the individual objects must be done
  4953. * on the group.
  4954. *
  4955. * Limitation:
  4956. *
  4957. * - The animated properties must be compatible among the
  4958. * all objects in the group.
  4959. *
  4960. * - A single property can either be controlled through a
  4961. * target group or directly, but not both.
  4962. */function AnimationObjectGroup(){this.uuid=MathUtils.generateUUID();// cached objects followed by the active ones
  4963. this._objects=Array.prototype.slice.call(arguments);this.nCachedObjects_=0;// threshold
  4964. // note: read by PropertyBinding.Composite
  4965. var indices={};this._indicesByUUID=indices;// for bookkeeping
  4966. for(var _i345=0,n=arguments.length;_i345!==n;++_i345){indices[arguments[_i345].uuid]=_i345;}this._paths=[];// inside: string
  4967. this._parsedPaths=[];// inside: { we don't care, here }
  4968. this._bindings=[];// inside: Array< PropertyBinding >
  4969. this._bindingsIndicesByPath={};// inside: indices in these arrays
  4970. var scope=this;this.stats={objects:{get total(){return scope._objects.length;},get inUse(){return this.total-scope.nCachedObjects_;}},get bindingsPerObject(){return scope._bindings.length;}};}Object.assign(AnimationObjectGroup.prototype,{isAnimationObjectGroup:true,add:function add(){var objects=this._objects,indicesByUUID=this._indicesByUUID,paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,nBindings=bindings.length;var knownObject=undefined,nObjects=objects.length,nCachedObjects=this.nCachedObjects_;for(var _i346=0,n=arguments.length;_i346!==n;++_i346){var object=arguments[_i346],uuid=object.uuid;var index=indicesByUUID[uuid];if(index===undefined){// unknown object -> add it to the ACTIVE region
  4971. index=nObjects++;indicesByUUID[uuid]=index;objects.push(object);// accounting is done, now do the same for all bindings
  4972. for(var j=0,m=nBindings;j!==m;++j){bindings[j].push(new PropertyBinding(object,paths[j],parsedPaths[j]));}}else if(index<nCachedObjects){knownObject=objects[index];// move existing object to the ACTIVE region
  4973. var firstActiveIndex=--nCachedObjects,lastCachedObject=objects[firstActiveIndex];indicesByUUID[lastCachedObject.uuid]=index;objects[index]=lastCachedObject;indicesByUUID[uuid]=firstActiveIndex;objects[firstActiveIndex]=object;// accounting is done, now do the same for all bindings
  4974. for(var _j25=0,_m2=nBindings;_j25!==_m2;++_j25){var bindingsForPath=bindings[_j25],lastCached=bindingsForPath[firstActiveIndex];var binding=bindingsForPath[index];bindingsForPath[index]=lastCached;if(binding===undefined){// since we do not bother to create new bindings
  4975. // for objects that are cached, the binding may
  4976. // or may not exist
  4977. binding=new PropertyBinding(object,paths[_j25],parsedPaths[_j25]);}bindingsForPath[firstActiveIndex]=binding;}}else if(objects[index]!==knownObject){console.error('THREE.AnimationObjectGroup: Different objects with the same UUID '+'detected. Clean the caches or recreate your infrastructure when reloading scenes.');}// else the object is already where we want it to be
  4978. }// for arguments
  4979. this.nCachedObjects_=nCachedObjects;},remove:function remove(){var objects=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;var nCachedObjects=this.nCachedObjects_;for(var _i347=0,n=arguments.length;_i347!==n;++_i347){var object=arguments[_i347],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined&&index>=nCachedObjects){// move existing object into the CACHED region
  4980. var lastCachedIndex=nCachedObjects++,firstActiveObject=objects[lastCachedIndex];indicesByUUID[firstActiveObject.uuid]=index;objects[index]=firstActiveObject;indicesByUUID[uuid]=lastCachedIndex;objects[lastCachedIndex]=object;// accounting is done, now do the same for all bindings
  4981. for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],firstActive=bindingsForPath[lastCachedIndex],binding=bindingsForPath[index];bindingsForPath[index]=firstActive;bindingsForPath[lastCachedIndex]=binding;}}}// for arguments
  4982. this.nCachedObjects_=nCachedObjects;},// remove & forget
  4983. uncache:function uncache(){var objects=this._objects,indicesByUUID=this._indicesByUUID,bindings=this._bindings,nBindings=bindings.length;var nCachedObjects=this.nCachedObjects_,nObjects=objects.length;for(var _i348=0,n=arguments.length;_i348!==n;++_i348){var object=arguments[_i348],uuid=object.uuid,index=indicesByUUID[uuid];if(index!==undefined){delete indicesByUUID[uuid];if(index<nCachedObjects){// object is cached, shrink the CACHED region
  4984. var firstActiveIndex=--nCachedObjects,lastCachedObject=objects[firstActiveIndex],lastIndex=--nObjects,lastObject=objects[lastIndex];// last cached object takes this object's place
  4985. indicesByUUID[lastCachedObject.uuid]=index;objects[index]=lastCachedObject;// last object goes to the activated slot and pop
  4986. indicesByUUID[lastObject.uuid]=firstActiveIndex;objects[firstActiveIndex]=lastObject;objects.pop();// accounting is done, now do the same for all bindings
  4987. for(var j=0,m=nBindings;j!==m;++j){var bindingsForPath=bindings[j],lastCached=bindingsForPath[firstActiveIndex],last=bindingsForPath[lastIndex];bindingsForPath[index]=lastCached;bindingsForPath[firstActiveIndex]=last;bindingsForPath.pop();}}else {// object is active, just swap with the last and pop
  4988. var _lastIndex=--nObjects,_lastObject=objects[_lastIndex];if(_lastIndex>0){indicesByUUID[_lastObject.uuid]=index;}objects[index]=_lastObject;objects.pop();// accounting is done, now do the same for all bindings
  4989. for(var _j26=0,_m3=nBindings;_j26!==_m3;++_j26){var _bindingsForPath=bindings[_j26];_bindingsForPath[index]=_bindingsForPath[_lastIndex];_bindingsForPath.pop();}}// cached or active
  4990. }// if object is known
  4991. }// for arguments
  4992. this.nCachedObjects_=nCachedObjects;},// Internal interface used by befriended PropertyBinding.Composite:
  4993. subscribe_:function subscribe_(path,parsedPath){// returns an array of bindings for the given path that is changed
  4994. // according to the contained objects in the group
  4995. var indicesByPath=this._bindingsIndicesByPath;var index=indicesByPath[path];var bindings=this._bindings;if(index!==undefined)return bindings[index];var paths=this._paths,parsedPaths=this._parsedPaths,objects=this._objects,nObjects=objects.length,nCachedObjects=this.nCachedObjects_,bindingsForPath=new Array(nObjects);index=bindings.length;indicesByPath[path]=index;paths.push(path);parsedPaths.push(parsedPath);bindings.push(bindingsForPath);for(var _i349=nCachedObjects,n=objects.length;_i349!==n;++_i349){var object=objects[_i349];bindingsForPath[_i349]=new PropertyBinding(object,path,parsedPath);}return bindingsForPath;},unsubscribe_:function unsubscribe_(path){// tells the group to forget about a property path and no longer
  4996. // update the array previously obtained with 'subscribe_'
  4997. var indicesByPath=this._bindingsIndicesByPath,index=indicesByPath[path];if(index!==undefined){var paths=this._paths,parsedPaths=this._parsedPaths,bindings=this._bindings,lastBindingsIndex=bindings.length-1,lastBindings=bindings[lastBindingsIndex],lastBindingsPath=path[lastBindingsIndex];indicesByPath[lastBindingsPath]=index;bindings[index]=lastBindings;bindings.pop();parsedPaths[index]=parsedPaths[lastBindingsIndex];parsedPaths.pop();paths[index]=paths[lastBindingsIndex];paths.pop();}}});class AnimationAction{constructor(mixer,clip){var localRoot=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;var blendMode=arguments.length>3&&arguments[3]!==undefined?arguments[3]:clip.blendMode;this._mixer=mixer;this._clip=clip;this._localRoot=localRoot;this.blendMode=blendMode;var tracks=clip.tracks,nTracks=tracks.length,interpolants=new Array(nTracks);var interpolantSettings={endingStart:ZeroCurvatureEnding,endingEnd:ZeroCurvatureEnding};for(var _i350=0;_i350!==nTracks;++_i350){var interpolant=tracks[_i350].createInterpolant(null);interpolants[_i350]=interpolant;interpolant.settings=interpolantSettings;}this._interpolantSettings=interpolantSettings;this._interpolants=interpolants;// bound by the mixer
  4998. // inside: PropertyMixer (managed by the mixer)
  4999. this._propertyBindings=new Array(nTracks);this._cacheIndex=null;// for the memory manager
  5000. this._byClipCacheIndex=null;// for the memory manager
  5001. this._timeScaleInterpolant=null;this._weightInterpolant=null;this.loop=LoopRepeat;this._loopCount=-1;// global mixer time when the action is to be started
  5002. // it's set back to 'null' upon start of the action
  5003. this._startTime=null;// scaled local time of the action
  5004. // gets clamped or wrapped to 0..clip.duration according to loop
  5005. this.time=0;this.timeScale=1;this._effectiveTimeScale=1;this.weight=1;this._effectiveWeight=1;this.repetitions=Infinity;// no. of repetitions when looping
  5006. this.paused=false;// true -> zero effective time scale
  5007. this.enabled=true;// false -> zero effective weight
  5008. this.clampWhenFinished=false;// keep feeding the last frame?
  5009. this.zeroSlopeAtStart=true;// for smooth interpolation w/o separate
  5010. this.zeroSlopeAtEnd=true;// clips for start, loop and end
  5011. }// State & Scheduling
  5012. play(){this._mixer._activateAction(this);return this;}stop(){this._mixer._deactivateAction(this);return this.reset();}reset(){this.paused=false;this.enabled=true;this.time=0;// restart clip
  5013. this._loopCount=-1;// forget previous loops
  5014. this._startTime=null;// forget scheduling
  5015. return this.stopFading().stopWarping();}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this);}// return true when play has been called
  5016. isScheduled(){return this._mixer._isActiveAction(this);}startAt(time){this._startTime=time;return this;}setLoop(mode,repetitions){this.loop=mode;this.repetitions=repetitions;return this;}// Weight
  5017. // set the weight stopping any scheduled fading
  5018. // although .enabled = false yields an effective weight of zero, this
  5019. // method does *not* change .enabled, because it would be confusing
  5020. setEffectiveWeight(weight){this.weight=weight;// note: same logic as when updated at runtime
  5021. this._effectiveWeight=this.enabled?weight:0;return this.stopFading();}// return the weight considering fading and .enabled
  5022. getEffectiveWeight(){return this._effectiveWeight;}fadeIn(duration){return this._scheduleFading(duration,0,1);}fadeOut(duration){return this._scheduleFading(duration,1,0);}crossFadeFrom(fadeOutAction,duration,warp){fadeOutAction.fadeOut(duration);this.fadeIn(duration);if(warp){var fadeInDuration=this._clip.duration,fadeOutDuration=fadeOutAction._clip.duration,startEndRatio=fadeOutDuration/fadeInDuration,endStartRatio=fadeInDuration/fadeOutDuration;fadeOutAction.warp(1.0,startEndRatio,duration);this.warp(endStartRatio,1.0,duration);}return this;}crossFadeTo(fadeInAction,duration,warp){return fadeInAction.crossFadeFrom(this,duration,warp);}stopFading(){var weightInterpolant=this._weightInterpolant;if(weightInterpolant!==null){this._weightInterpolant=null;this._mixer._takeBackControlInterpolant(weightInterpolant);}return this;}// Time Scale Control
  5023. // set the time scale stopping any scheduled warping
  5024. // although .paused = true yields an effective time scale of zero, this
  5025. // method does *not* change .paused, because it would be confusing
  5026. setEffectiveTimeScale(timeScale){this.timeScale=timeScale;this._effectiveTimeScale=this.paused?0:timeScale;return this.stopWarping();}// return the time scale considering warping and .paused
  5027. getEffectiveTimeScale(){return this._effectiveTimeScale;}setDuration(duration){this.timeScale=this._clip.duration/duration;return this.stopWarping();}syncWith(action){this.time=action.time;this.timeScale=action.timeScale;return this.stopWarping();}halt(duration){return this.warp(this._effectiveTimeScale,0,duration);}warp(startTimeScale,endTimeScale,duration){var mixer=this._mixer,now=mixer.time,timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._timeScaleInterpolant=interpolant;}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;times[1]=now+duration;values[0]=startTimeScale/timeScale;values[1]=endTimeScale/timeScale;return this;}stopWarping(){var timeScaleInterpolant=this._timeScaleInterpolant;if(timeScaleInterpolant!==null){this._timeScaleInterpolant=null;this._mixer._takeBackControlInterpolant(timeScaleInterpolant);}return this;}// Object Accessors
  5028. getMixer(){return this._mixer;}getClip(){return this._clip;}getRoot(){return this._localRoot||this._mixer._root;}// Interna
  5029. _update(time,deltaTime,timeDirection,accuIndex){// called by the mixer
  5030. if(!this.enabled){// call ._updateWeight() to update ._effectiveWeight
  5031. this._updateWeight(time);return;}var startTime=this._startTime;if(startTime!==null){// check for scheduled start of action
  5032. var timeRunning=(time-startTime)*timeDirection;if(timeRunning<0||timeDirection===0){return;// yet to come / don't decide when delta = 0
  5033. }// start
  5034. this._startTime=null;// unschedule
  5035. deltaTime=timeDirection*timeRunning;}// apply time scale and advance time
  5036. deltaTime*=this._updateTimeScale(time);var clipTime=this._updateTime(deltaTime);// note: _updateTime may disable the action resulting in
  5037. // an effective weight of 0
  5038. var weight=this._updateWeight(time);if(weight>0){var interpolants=this._interpolants;var propertyMixers=this._propertyBindings;switch(this.blendMode){case AdditiveAnimationBlendMode:for(var j=0,m=interpolants.length;j!==m;++j){interpolants[j].evaluate(clipTime);propertyMixers[j].accumulateAdditive(weight);}break;case NormalAnimationBlendMode:default:for(var _j27=0,_m4=interpolants.length;_j27!==_m4;++_j27){interpolants[_j27].evaluate(clipTime);propertyMixers[_j27].accumulate(accuIndex,weight);}}}}_updateWeight(time){var weight=0;if(this.enabled){weight=this.weight;var interpolant=this._weightInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];weight*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopFading();if(interpolantValue===0){// faded out, disable
  5039. this.enabled=false;}}}}this._effectiveWeight=weight;return weight;}_updateTimeScale(time){var timeScale=0;if(!this.paused){timeScale=this.timeScale;var interpolant=this._timeScaleInterpolant;if(interpolant!==null){var interpolantValue=interpolant.evaluate(time)[0];timeScale*=interpolantValue;if(time>interpolant.parameterPositions[1]){this.stopWarping();if(timeScale===0){// motion has halted, pause
  5040. this.paused=true;}else {// warp done - apply final time scale
  5041. this.timeScale=timeScale;}}}}this._effectiveTimeScale=timeScale;return timeScale;}_updateTime(deltaTime){var duration=this._clip.duration;var loop=this.loop;var time=this.time+deltaTime;var loopCount=this._loopCount;var pingPong=loop===LoopPingPong;if(deltaTime===0){if(loopCount===-1)return time;return pingPong&&(loopCount&1)===1?duration-time:time;}if(loop===LoopOnce){if(loopCount===-1){// just started
  5042. this._loopCount=0;this._setEndings(true,true,false);}handle_stop:{if(time>=duration){time=duration;}else if(time<0){time=0;}else {this.time=time;break handle_stop;}if(this.clampWhenFinished)this.paused=true;else this.enabled=false;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime<0?-1:1});}}else {// repetitive Repeat or PingPong
  5043. if(loopCount===-1){// just started
  5044. if(deltaTime>=0){loopCount=0;this._setEndings(true,this.repetitions===0,pingPong);}else {// when looping in reverse direction, the initial
  5045. // transition through zero counts as a repetition,
  5046. // so leave loopCount at -1
  5047. this._setEndings(this.repetitions===0,true,pingPong);}}if(time>=duration||time<0){// wrap around
  5048. var loopDelta=Math.floor(time/duration);// signed
  5049. time-=duration*loopDelta;loopCount+=Math.abs(loopDelta);var pending=this.repetitions-loopCount;if(pending<=0){// have to stop (switch state, clamp time, fire event)
  5050. if(this.clampWhenFinished)this.paused=true;else this.enabled=false;time=deltaTime>0?duration:0;this.time=time;this._mixer.dispatchEvent({type:'finished',action:this,direction:deltaTime>0?1:-1});}else {// keep running
  5051. if(pending===1){// entering the last round
  5052. var atStart=deltaTime<0;this._setEndings(atStart,!atStart,pingPong);}else {this._setEndings(false,false,pingPong);}this._loopCount=loopCount;this.time=time;this._mixer.dispatchEvent({type:'loop',action:this,loopDelta:loopDelta});}}else {this.time=time;}if(pingPong&&(loopCount&1)===1){// invert time for the "pong round"
  5053. return duration-time;}}return time;}_setEndings(atStart,atEnd,pingPong){var settings=this._interpolantSettings;if(pingPong){settings.endingStart=ZeroSlopeEnding;settings.endingEnd=ZeroSlopeEnding;}else {// assuming for LoopOnce atStart == atEnd == true
  5054. if(atStart){settings.endingStart=this.zeroSlopeAtStart?ZeroSlopeEnding:ZeroCurvatureEnding;}else {settings.endingStart=WrapAroundEnding;}if(atEnd){settings.endingEnd=this.zeroSlopeAtEnd?ZeroSlopeEnding:ZeroCurvatureEnding;}else {settings.endingEnd=WrapAroundEnding;}}}_scheduleFading(duration,weightNow,weightThen){var mixer=this._mixer,now=mixer.time;var interpolant=this._weightInterpolant;if(interpolant===null){interpolant=mixer._lendControlInterpolant();this._weightInterpolant=interpolant;}var times=interpolant.parameterPositions,values=interpolant.sampleValues;times[0]=now;values[0]=weightNow;times[1]=now+duration;values[1]=weightThen;return this;}}function AnimationMixer(root){this._root=root;this._initMemoryManager();this._accuIndex=0;this.time=0;this.timeScale=1.0;}AnimationMixer.prototype=Object.assign(Object.create(EventDispatcher.prototype),{constructor:AnimationMixer,_bindAction:function _bindAction(action,prototypeAction){var root=action._localRoot||this._root,tracks=action._clip.tracks,nTracks=tracks.length,bindings=action._propertyBindings,interpolants=action._interpolants,rootUuid=root.uuid,bindingsByRoot=this._bindingsByRootAndName;var bindingsByName=bindingsByRoot[rootUuid];if(bindingsByName===undefined){bindingsByName={};bindingsByRoot[rootUuid]=bindingsByName;}for(var _i351=0;_i351!==nTracks;++_i351){var track=tracks[_i351],trackName=track.name;var binding=bindingsByName[trackName];if(binding!==undefined){bindings[_i351]=binding;}else {binding=bindings[_i351];if(binding!==undefined){// existing binding, make sure the cache knows
  5055. if(binding._cacheIndex===null){++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);}continue;}var path=prototypeAction&&prototypeAction._propertyBindings[_i351].binding.parsedPath;binding=new PropertyMixer(PropertyBinding.create(root,trackName,path),track.ValueTypeName,track.getValueSize());++binding.referenceCount;this._addInactiveBinding(binding,rootUuid,trackName);bindings[_i351]=binding;}interpolants[_i351].resultBuffer=binding.buffer;}},_activateAction:function _activateAction(action){if(!this._isActiveAction(action)){if(action._cacheIndex===null){// this action has been forgotten by the cache, but the user
  5056. // appears to be still using it -> rebind
  5057. var rootUuid=(action._localRoot||this._root).uuid,clipUuid=action._clip.uuid,actionsForClip=this._actionsByClip[clipUuid];this._bindAction(action,actionsForClip&&actionsForClip.knownActions[0]);this._addInactiveAction(action,clipUuid,rootUuid);}var bindings=action._propertyBindings;// increment reference counts / sort out state
  5058. for(var _i352=0,n=bindings.length;_i352!==n;++_i352){var binding=bindings[_i352];if(binding.useCount++===0){this._lendBinding(binding);binding.saveOriginalState();}}this._lendAction(action);}},_deactivateAction:function _deactivateAction(action){if(this._isActiveAction(action)){var bindings=action._propertyBindings;// decrement reference counts / sort out state
  5059. for(var _i353=0,n=bindings.length;_i353!==n;++_i353){var binding=bindings[_i353];if(--binding.useCount===0){binding.restoreOriginalState();this._takeBackBinding(binding);}}this._takeBackAction(action);}},// Memory manager
  5060. _initMemoryManager:function _initMemoryManager(){this._actions=[];// 'nActiveActions' followed by inactive ones
  5061. this._nActiveActions=0;this._actionsByClip={};// inside:
  5062. // {
  5063. // knownActions: Array< AnimationAction > - used as prototypes
  5064. // actionByRoot: AnimationAction - lookup
  5065. // }
  5066. this._bindings=[];// 'nActiveBindings' followed by inactive ones
  5067. this._nActiveBindings=0;this._bindingsByRootAndName={};// inside: Map< name, PropertyMixer >
  5068. this._controlInterpolants=[];// same game as above
  5069. this._nActiveControlInterpolants=0;var scope=this;this.stats={actions:{get total(){return scope._actions.length;},get inUse(){return scope._nActiveActions;}},bindings:{get total(){return scope._bindings.length;},get inUse(){return scope._nActiveBindings;}},controlInterpolants:{get total(){return scope._controlInterpolants.length;},get inUse(){return scope._nActiveControlInterpolants;}}};},// Memory management for AnimationAction objects
  5070. _isActiveAction:function _isActiveAction(action){var index=action._cacheIndex;return index!==null&&index<this._nActiveActions;},_addInactiveAction:function _addInactiveAction(action,clipUuid,rootUuid){var actions=this._actions,actionsByClip=this._actionsByClip;var actionsForClip=actionsByClip[clipUuid];if(actionsForClip===undefined){actionsForClip={knownActions:[action],actionByRoot:{}};action._byClipCacheIndex=0;actionsByClip[clipUuid]=actionsForClip;}else {var knownActions=actionsForClip.knownActions;action._byClipCacheIndex=knownActions.length;knownActions.push(action);}action._cacheIndex=actions.length;actions.push(action);actionsForClip.actionByRoot[rootUuid]=action;},_removeInactiveAction:function _removeInactiveAction(action){var actions=this._actions,lastInactiveAction=actions[actions.length-1],cacheIndex=action._cacheIndex;lastInactiveAction._cacheIndex=cacheIndex;actions[cacheIndex]=lastInactiveAction;actions.pop();action._cacheIndex=null;var clipUuid=action._clip.uuid,actionsByClip=this._actionsByClip,actionsForClip=actionsByClip[clipUuid],knownActionsForClip=actionsForClip.knownActions,lastKnownAction=knownActionsForClip[knownActionsForClip.length-1],byClipCacheIndex=action._byClipCacheIndex;lastKnownAction._byClipCacheIndex=byClipCacheIndex;knownActionsForClip[byClipCacheIndex]=lastKnownAction;knownActionsForClip.pop();action._byClipCacheIndex=null;var actionByRoot=actionsForClip.actionByRoot,rootUuid=(action._localRoot||this._root).uuid;delete actionByRoot[rootUuid];if(knownActionsForClip.length===0){delete actionsByClip[clipUuid];}this._removeInactiveBindingsForAction(action);},_removeInactiveBindingsForAction:function _removeInactiveBindingsForAction(action){var bindings=action._propertyBindings;for(var _i354=0,n=bindings.length;_i354!==n;++_i354){var binding=bindings[_i354];if(--binding.referenceCount===0){this._removeInactiveBinding(binding);}}},_lendAction:function _lendAction(action){// [ active actions | inactive actions ]
  5071. // [ active actions >| inactive actions ]
  5072. // s a
  5073. // <-swap->
  5074. // a s
  5075. var actions=this._actions,prevIndex=action._cacheIndex,lastActiveIndex=this._nActiveActions++,firstInactiveAction=actions[lastActiveIndex];action._cacheIndex=lastActiveIndex;actions[lastActiveIndex]=action;firstInactiveAction._cacheIndex=prevIndex;actions[prevIndex]=firstInactiveAction;},_takeBackAction:function _takeBackAction(action){// [ active actions | inactive actions ]
  5076. // [ active actions |< inactive actions ]
  5077. // a s
  5078. // <-swap->
  5079. // s a
  5080. var actions=this._actions,prevIndex=action._cacheIndex,firstInactiveIndex=--this._nActiveActions,lastActiveAction=actions[firstInactiveIndex];action._cacheIndex=firstInactiveIndex;actions[firstInactiveIndex]=action;lastActiveAction._cacheIndex=prevIndex;actions[prevIndex]=lastActiveAction;},// Memory management for PropertyMixer objects
  5081. _addInactiveBinding:function _addInactiveBinding(binding,rootUuid,trackName){var bindingsByRoot=this._bindingsByRootAndName,bindings=this._bindings;var bindingByName=bindingsByRoot[rootUuid];if(bindingByName===undefined){bindingByName={};bindingsByRoot[rootUuid]=bindingByName;}bindingByName[trackName]=binding;binding._cacheIndex=bindings.length;bindings.push(binding);},_removeInactiveBinding:function _removeInactiveBinding(binding){var bindings=this._bindings,propBinding=binding.binding,rootUuid=propBinding.rootNode.uuid,trackName=propBinding.path,bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid],lastInactiveBinding=bindings[bindings.length-1],cacheIndex=binding._cacheIndex;lastInactiveBinding._cacheIndex=cacheIndex;bindings[cacheIndex]=lastInactiveBinding;bindings.pop();delete bindingByName[trackName];if(Object.keys(bindingByName).length===0){delete bindingsByRoot[rootUuid];}},_lendBinding:function _lendBinding(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,lastActiveIndex=this._nActiveBindings++,firstInactiveBinding=bindings[lastActiveIndex];binding._cacheIndex=lastActiveIndex;bindings[lastActiveIndex]=binding;firstInactiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=firstInactiveBinding;},_takeBackBinding:function _takeBackBinding(binding){var bindings=this._bindings,prevIndex=binding._cacheIndex,firstInactiveIndex=--this._nActiveBindings,lastActiveBinding=bindings[firstInactiveIndex];binding._cacheIndex=firstInactiveIndex;bindings[firstInactiveIndex]=binding;lastActiveBinding._cacheIndex=prevIndex;bindings[prevIndex]=lastActiveBinding;},// Memory management of Interpolants for weight and time scale
  5082. _lendControlInterpolant:function _lendControlInterpolant(){var interpolants=this._controlInterpolants,lastActiveIndex=this._nActiveControlInterpolants++;var interpolant=interpolants[lastActiveIndex];if(interpolant===undefined){interpolant=new LinearInterpolant(new Float32Array(2),new Float32Array(2),1,this._controlInterpolantsResultBuffer);interpolant.__cacheIndex=lastActiveIndex;interpolants[lastActiveIndex]=interpolant;}return interpolant;},_takeBackControlInterpolant:function _takeBackControlInterpolant(interpolant){var interpolants=this._controlInterpolants,prevIndex=interpolant.__cacheIndex,firstInactiveIndex=--this._nActiveControlInterpolants,lastActiveInterpolant=interpolants[firstInactiveIndex];interpolant.__cacheIndex=firstInactiveIndex;interpolants[firstInactiveIndex]=interpolant;lastActiveInterpolant.__cacheIndex=prevIndex;interpolants[prevIndex]=lastActiveInterpolant;},_controlInterpolantsResultBuffer:new Float32Array(1),// return an action for a clip optionally using a custom root target
  5083. // object (this method allocates a lot of dynamic memory in case a
  5084. // previously unknown clip/root combination is specified)
  5085. clipAction:function clipAction(clip,optionalRoot,blendMode){var root=optionalRoot||this._root,rootUuid=root.uuid;var clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip;var clipUuid=clipObject!==null?clipObject.uuid:clip;var actionsForClip=this._actionsByClip[clipUuid];var prototypeAction=null;if(blendMode===undefined){if(clipObject!==null){blendMode=clipObject.blendMode;}else {blendMode=NormalAnimationBlendMode;}}if(actionsForClip!==undefined){var existingAction=actionsForClip.actionByRoot[rootUuid];if(existingAction!==undefined&&existingAction.blendMode===blendMode){return existingAction;}// we know the clip, so we don't have to parse all
  5086. // the bindings again but can just copy
  5087. prototypeAction=actionsForClip.knownActions[0];// also, take the clip from the prototype action
  5088. if(clipObject===null)clipObject=prototypeAction._clip;}// clip must be known when specified via string
  5089. if(clipObject===null)return null;// allocate all resources required to run it
  5090. var newAction=new AnimationAction(this,clipObject,optionalRoot,blendMode);this._bindAction(newAction,prototypeAction);// and make the action known to the memory manager
  5091. this._addInactiveAction(newAction,clipUuid,rootUuid);return newAction;},// get an existing action
  5092. existingAction:function existingAction(clip,optionalRoot){var root=optionalRoot||this._root,rootUuid=root.uuid,clipObject=typeof clip==='string'?AnimationClip.findByName(root,clip):clip,clipUuid=clipObject?clipObject.uuid:clip,actionsForClip=this._actionsByClip[clipUuid];if(actionsForClip!==undefined){return actionsForClip.actionByRoot[rootUuid]||null;}return null;},// deactivates all previously scheduled actions
  5093. stopAllAction:function stopAllAction(){var actions=this._actions,nActions=this._nActiveActions;for(var _i355=nActions-1;_i355>=0;--_i355){actions[_i355].stop();}return this;},// advance the time and update apply the animation
  5094. update:function update(deltaTime){deltaTime*=this.timeScale;var actions=this._actions,nActions=this._nActiveActions,time=this.time+=deltaTime,timeDirection=Math.sign(deltaTime),accuIndex=this._accuIndex^=1;// run active actions
  5095. for(var _i356=0;_i356!==nActions;++_i356){var action=actions[_i356];action._update(time,deltaTime,timeDirection,accuIndex);}// update scene graph
  5096. var bindings=this._bindings,nBindings=this._nActiveBindings;for(var _i357=0;_i357!==nBindings;++_i357){bindings[_i357].apply(accuIndex);}return this;},// Allows you to seek to a specific time in an animation.
  5097. setTime:function setTime(timeInSeconds){this.time=0;// Zero out time attribute for AnimationMixer object;
  5098. for(var _i358=0;_i358<this._actions.length;_i358++){this._actions[_i358].time=0;// Zero out time attribute for all associated AnimationAction objects.
  5099. }return this.update(timeInSeconds);// Update used to set exact time. Returns "this" AnimationMixer object.
  5100. },// return this mixer's root target object
  5101. getRoot:function getRoot(){return this._root;},// free all resources specific to a particular clip
  5102. uncacheClip:function uncacheClip(clip){var actions=this._actions,clipUuid=clip.uuid,actionsByClip=this._actionsByClip,actionsForClip=actionsByClip[clipUuid];if(actionsForClip!==undefined){// note: just calling _removeInactiveAction would mess up the
  5103. // iteration state and also require updating the state we can
  5104. // just throw away
  5105. var actionsToRemove=actionsForClip.knownActions;for(var _i359=0,n=actionsToRemove.length;_i359!==n;++_i359){var action=actionsToRemove[_i359];this._deactivateAction(action);var cacheIndex=action._cacheIndex,lastInactiveAction=actions[actions.length-1];action._cacheIndex=null;action._byClipCacheIndex=null;lastInactiveAction._cacheIndex=cacheIndex;actions[cacheIndex]=lastInactiveAction;actions.pop();this._removeInactiveBindingsForAction(action);}delete actionsByClip[clipUuid];}},// free all resources specific to a particular root target object
  5106. uncacheRoot:function uncacheRoot(root){var rootUuid=root.uuid,actionsByClip=this._actionsByClip;for(var clipUuid in actionsByClip){var actionByRoot=actionsByClip[clipUuid].actionByRoot,action=actionByRoot[rootUuid];if(action!==undefined){this._deactivateAction(action);this._removeInactiveAction(action);}}var bindingsByRoot=this._bindingsByRootAndName,bindingByName=bindingsByRoot[rootUuid];if(bindingByName!==undefined){for(var trackName in bindingByName){var binding=bindingByName[trackName];binding.restoreOriginalState();this._removeInactiveBinding(binding);}}},// remove a targeted clip from the cache
  5107. uncacheAction:function uncacheAction(clip,optionalRoot){var action=this.existingAction(clip,optionalRoot);if(action!==null){this._deactivateAction(action);this._removeInactiveAction(action);}}});class Uniform{constructor(value){if(typeof value==='string'){console.warn('THREE.Uniform: Type parameter is no longer needed.');value=arguments[1];}this.value=value;}clone(){return new Uniform(this.value.clone===undefined?this.value:this.value.clone());}}function InstancedInterleavedBuffer(array,stride,meshPerAttribute){InterleavedBuffer.call(this,array,stride);this.meshPerAttribute=meshPerAttribute||1;}InstancedInterleavedBuffer.prototype=Object.assign(Object.create(InterleavedBuffer.prototype),{constructor:InstancedInterleavedBuffer,isInstancedInterleavedBuffer:true,copy:function copy(source){InterleavedBuffer.prototype.copy.call(this,source);this.meshPerAttribute=source.meshPerAttribute;return this;},clone:function clone(data){var ib=InterleavedBuffer.prototype.clone.call(this,data);ib.meshPerAttribute=this.meshPerAttribute;return ib;},toJSON:function toJSON(data){var json=InterleavedBuffer.prototype.toJSON.call(this,data);json.isInstancedInterleavedBuffer=true;json.meshPerAttribute=this.meshPerAttribute;return json;}});function GLBufferAttribute(buffer,type,itemSize,elementSize,count){this.buffer=buffer;this.type=type;this.itemSize=itemSize;this.elementSize=elementSize;this.count=count;this.version=0;}Object.defineProperty(GLBufferAttribute.prototype,'needsUpdate',{set:function set(value){if(value===true)this.version++;}});Object.assign(GLBufferAttribute.prototype,{isGLBufferAttribute:true,setBuffer:function setBuffer(buffer){this.buffer=buffer;return this;},setType:function setType(type,elementSize){this.type=type;this.elementSize=elementSize;return this;},setItemSize:function setItemSize(itemSize){this.itemSize=itemSize;return this;},setCount:function setCount(count){this.count=count;return this;}});function Raycaster(origin,direction,near,far){this.ray=new Ray(origin,direction);// direction is assumed to be normalized (for accurate distance calculations)
  5108. this.near=near||0;this.far=far||Infinity;this.camera=null;this.layers=new Layers();this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}};Object.defineProperties(this.params,{PointCloud:{get:function get(){console.warn('THREE.Raycaster: params.PointCloud has been renamed to params.Points.');return this.Points;}}});}function ascSort(a,b){return a.distance-b.distance;}function _intersectObject(object,raycaster,intersects,recursive){if(object.layers.test(raycaster.layers)){object.raycast(raycaster,intersects);}if(recursive===true){var children=object.children;for(var _i360=0,l=children.length;_i360<l;_i360++){_intersectObject(children[_i360],raycaster,intersects,true);}}}Object.assign(Raycaster.prototype,{set:function set(origin,direction){// direction is assumed to be normalized (for accurate distance calculations)
  5109. this.ray.set(origin,direction);},setFromCamera:function setFromCamera(coords,camera){if(camera&&camera.isPerspectiveCamera){this.ray.origin.setFromMatrixPosition(camera.matrixWorld);this.ray.direction.set(coords.x,coords.y,0.5).unproject(camera).sub(this.ray.origin).normalize();this.camera=camera;}else if(camera&&camera.isOrthographicCamera){this.ray.origin.set(coords.x,coords.y,(camera.near+camera.far)/(camera.near-camera.far)).unproject(camera);// set origin in plane of camera
  5110. this.ray.direction.set(0,0,-1).transformDirection(camera.matrixWorld);this.camera=camera;}else {console.error('THREE.Raycaster: Unsupported camera type: '+camera.type);}},intersectObject:function intersectObject(object,recursive,optionalTarget){var intersects=optionalTarget||[];_intersectObject(object,this,intersects,recursive);intersects.sort(ascSort);return intersects;},intersectObjects:function intersectObjects(objects,recursive,optionalTarget){var intersects=optionalTarget||[];if(Array.isArray(objects)===false){console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');return intersects;}for(var _i361=0,l=objects.length;_i361<l;_i361++){_intersectObject(objects[_i361],this,intersects,recursive);}intersects.sort(ascSort);return intersects;}});/**
  5111. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  5112. *
  5113. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  5114. * The azimuthal angle (theta) is measured from the positive z-axis.
  5115. */class Spherical{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var phi=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var theta=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;this.radius=radius;this.phi=phi;// polar angle
  5116. this.theta=theta;// azimuthal angle
  5117. return this;}set(radius,phi,theta){this.radius=radius;this.phi=phi;this.theta=theta;return this;}clone(){return new this.constructor().copy(this);}copy(other){this.radius=other.radius;this.phi=other.phi;this.theta=other.theta;return this;}// restrict phi to be betwee EPS and PI-EPS
  5118. makeSafe(){var EPS=0.000001;this.phi=Math.max(EPS,Math.min(Math.PI-EPS,this.phi));return this;}setFromVector3(v){return this.setFromCartesianCoords(v.x,v.y,v.z);}setFromCartesianCoords(x,y,z){this.radius=Math.sqrt(x*x+y*y+z*z);if(this.radius===0){this.theta=0;this.phi=0;}else {this.theta=Math.atan2(x,z);this.phi=Math.acos(MathUtils.clamp(y/this.radius,-1,1));}return this;}}/**
  5119. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  5120. */class Cylindrical{constructor(radius,theta,y){this.radius=radius!==undefined?radius:1.0;// distance from the origin to a point in the x-z plane
  5121. this.theta=theta!==undefined?theta:0;// counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  5122. this.y=y!==undefined?y:0;// height above the x-z plane
  5123. return this;}set(radius,theta,y){this.radius=radius;this.theta=theta;this.y=y;return this;}clone(){return new this.constructor().copy(this);}copy(other){this.radius=other.radius;this.theta=other.theta;this.y=other.y;return this;}setFromVector3(v){return this.setFromCartesianCoords(v.x,v.y,v.z);}setFromCartesianCoords(x,y,z){this.radius=Math.sqrt(x*x+z*z);this.theta=Math.atan2(x,z);this.y=y;return this;}}var _vector$8=/*@__PURE__*/new Vector2();class Box2{constructor(min,max){Object.defineProperty(this,'isBox2',{value:true});this.min=min!==undefined?min:new Vector2(+Infinity,+Infinity);this.max=max!==undefined?max:new Vector2(-Infinity,-Infinity);}set(min,max){this.min.copy(min);this.max.copy(max);return this;}setFromPoints(points){this.makeEmpty();for(var _i362=0,il=points.length;_i362<il;_i362++){this.expandByPoint(points[_i362]);}return this;}setFromCenterAndSize(center,size){var halfSize=_vector$8.copy(size).multiplyScalar(0.5);this.min.copy(center).sub(halfSize);this.max.copy(center).add(halfSize);return this;}clone(){return new this.constructor().copy(this);}copy(box){this.min.copy(box.min);this.max.copy(box.max);return this;}makeEmpty(){this.min.x=this.min.y=+Infinity;this.max.x=this.max.y=-Infinity;return this;}isEmpty(){// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  5124. return this.max.x<this.min.x||this.max.y<this.min.y;}getCenter(target){if(target===undefined){console.warn('THREE.Box2: .getCenter() target is now required');target=new Vector2();}return this.isEmpty()?target.set(0,0):target.addVectors(this.min,this.max).multiplyScalar(0.5);}getSize(target){if(target===undefined){console.warn('THREE.Box2: .getSize() target is now required');target=new Vector2();}return this.isEmpty()?target.set(0,0):target.subVectors(this.max,this.min);}expandByPoint(point){this.min.min(point);this.max.max(point);return this;}expandByVector(vector){this.min.sub(vector);this.max.add(vector);return this;}expandByScalar(scalar){this.min.addScalar(-scalar);this.max.addScalar(scalar);return this;}containsPoint(point){return point.x<this.min.x||point.x>this.max.x||point.y<this.min.y||point.y>this.max.y?false:true;}containsBox(box){return this.min.x<=box.min.x&&box.max.x<=this.max.x&&this.min.y<=box.min.y&&box.max.y<=this.max.y;}getParameter(point,target){// This can potentially have a divide by zero if the box
  5125. // has a size dimension of 0.
  5126. if(target===undefined){console.warn('THREE.Box2: .getParameter() target is now required');target=new Vector2();}return target.set((point.x-this.min.x)/(this.max.x-this.min.x),(point.y-this.min.y)/(this.max.y-this.min.y));}intersectsBox(box){// using 4 splitting planes to rule out intersections
  5127. return box.max.x<this.min.x||box.min.x>this.max.x||box.max.y<this.min.y||box.min.y>this.max.y?false:true;}clampPoint(point,target){if(target===undefined){console.warn('THREE.Box2: .clampPoint() target is now required');target=new Vector2();}return target.copy(point).clamp(this.min,this.max);}distanceToPoint(point){var clampedPoint=_vector$8.copy(point).clamp(this.min,this.max);return clampedPoint.sub(point).length();}intersect(box){this.min.max(box.min);this.max.min(box.max);return this;}union(box){this.min.min(box.min);this.max.max(box.max);return this;}translate(offset){this.min.add(offset);this.max.add(offset);return this;}equals(box){return box.min.equals(this.min)&&box.max.equals(this.max);}}var _startP=/*@__PURE__*/new Vector3();var _startEnd=/*@__PURE__*/new Vector3();class Line3{constructor(start,end){this.start=start!==undefined?start:new Vector3();this.end=end!==undefined?end:new Vector3();}set(start,end){this.start.copy(start);this.end.copy(end);return this;}clone(){return new this.constructor().copy(this);}copy(line){this.start.copy(line.start);this.end.copy(line.end);return this;}getCenter(target){if(target===undefined){console.warn('THREE.Line3: .getCenter() target is now required');target=new Vector3();}return target.addVectors(this.start,this.end).multiplyScalar(0.5);}delta(target){if(target===undefined){console.warn('THREE.Line3: .delta() target is now required');target=new Vector3();}return target.subVectors(this.end,this.start);}distanceSq(){return this.start.distanceToSquared(this.end);}distance(){return this.start.distanceTo(this.end);}at(t,target){if(target===undefined){console.warn('THREE.Line3: .at() target is now required');target=new Vector3();}return this.delta(target).multiplyScalar(t).add(this.start);}closestPointToPointParameter(point,clampToLine){_startP.subVectors(point,this.start);_startEnd.subVectors(this.end,this.start);var startEnd2=_startEnd.dot(_startEnd);var startEnd_startP=_startEnd.dot(_startP);var t=startEnd_startP/startEnd2;if(clampToLine){t=MathUtils.clamp(t,0,1);}return t;}closestPointToPoint(point,clampToLine,target){var t=this.closestPointToPointParameter(point,clampToLine);if(target===undefined){console.warn('THREE.Line3: .closestPointToPoint() target is now required');target=new Vector3();}return this.delta(target).multiplyScalar(t).add(this.start);}applyMatrix4(matrix){this.start.applyMatrix4(matrix);this.end.applyMatrix4(matrix);return this;}equals(line){return line.start.equals(this.start)&&line.end.equals(this.end);}}function ImmediateRenderObject(material){Object3D.call(this);this.material=material;this.render=function/* renderCallback */(){};this.hasPositions=false;this.hasNormals=false;this.hasColors=false;this.hasUvs=false;this.positionArray=null;this.normalArray=null;this.colorArray=null;this.uvArray=null;this.count=0;}ImmediateRenderObject.prototype=Object.create(Object3D.prototype);ImmediateRenderObject.prototype.constructor=ImmediateRenderObject;ImmediateRenderObject.prototype.isImmediateRenderObject=true;var _vector$9=/*@__PURE__*/new Vector3();class SpotLightHelper extends Object3D{constructor(light,color){super();this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var geometry=new BufferGeometry();var positions=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(var _i363=0,j=1,l=32;_i363<l;_i363++,j++){var p1=_i363/l*Math.PI*2;var p2=j/l*Math.PI*2;positions.push(Math.cos(p1),Math.sin(p1),1,Math.cos(p2),Math.sin(p2),1);}geometry.setAttribute('position',new Float32BufferAttribute(positions,3));var material=new LineBasicMaterial({fog:false,toneMapped:false});this.cone=new LineSegments(geometry,material);this.add(this.cone);this.update();}dispose(){this.cone.geometry.dispose();this.cone.material.dispose();}update(){this.light.updateMatrixWorld();var coneLength=this.light.distance?this.light.distance:1000;var coneWidth=coneLength*Math.tan(this.light.angle);this.cone.scale.set(coneWidth,coneWidth,coneLength);_vector$9.setFromMatrixPosition(this.light.target.matrixWorld);this.cone.lookAt(_vector$9);if(this.color!==undefined){this.cone.material.color.set(this.color);}else {this.cone.material.color.copy(this.light.color);}}}var _vector$a=/*@__PURE__*/new Vector3();var _boneMatrix=/*@__PURE__*/new Matrix4();var _matrixWorldInv=/*@__PURE__*/new Matrix4();class SkeletonHelper extends LineSegments{constructor(object){var bones=getBoneList(object);var geometry=new BufferGeometry();var vertices=[];var colors=[];var color1=new Color(0,0,1);var color2=new Color(0,1,0);for(var _i364=0;_i364<bones.length;_i364++){var bone=bones[_i364];if(bone.parent&&bone.parent.isBone){vertices.push(0,0,0);vertices.push(0,0,0);colors.push(color1.r,color1.g,color1.b);colors.push(color2.r,color2.g,color2.b);}}geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,depthTest:false,depthWrite:false,toneMapped:false,transparent:true});super(geometry,material);this.type='SkeletonHelper';this.isSkeletonHelper=true;this.root=object;this.bones=bones;this.matrix=object.matrixWorld;this.matrixAutoUpdate=false;}updateMatrixWorld(force){var bones=this.bones;var geometry=this.geometry;var position=geometry.getAttribute('position');_matrixWorldInv.copy(this.root.matrixWorld).invert();for(var _i365=0,j=0;_i365<bones.length;_i365++){var bone=bones[_i365];if(bone.parent&&bone.parent.isBone){_boneMatrix.multiplyMatrices(_matrixWorldInv,bone.matrixWorld);_vector$a.setFromMatrixPosition(_boneMatrix);position.setXYZ(j,_vector$a.x,_vector$a.y,_vector$a.z);_boneMatrix.multiplyMatrices(_matrixWorldInv,bone.parent.matrixWorld);_vector$a.setFromMatrixPosition(_boneMatrix);position.setXYZ(j+1,_vector$a.x,_vector$a.y,_vector$a.z);j+=2;}}geometry.getAttribute('position').needsUpdate=true;super.updateMatrixWorld(force);}}function getBoneList(object){var boneList=[];if(object&&object.isBone){boneList.push(object);}for(var _i366=0;_i366<object.children.length;_i366++){boneList.push.apply(boneList,getBoneList(object.children[_i366]));}return boneList;}class PointLightHelper extends Mesh{constructor(light,sphereSize,color){var geometry=new SphereBufferGeometry(sphereSize,4,2);var material=new MeshBasicMaterial({wireframe:true,fog:false,toneMapped:false});super(geometry,material);this.light=light;this.light.updateMatrixWorld();this.color=color;this.type='PointLightHelper';this.matrix=this.light.matrixWorld;this.matrixAutoUpdate=false;this.update();/*
  5128. // TODO: delete this comment?
  5129. const distanceGeometry = new THREE.IcosahedronBufferGeometry( 1, 2 );
  5130. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  5131. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  5132. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  5133. const d = light.distance;
  5134. if ( d === 0.0 ) {
  5135. this.lightDistance.visible = false;
  5136. } else {
  5137. this.lightDistance.scale.set( d, d, d );
  5138. }
  5139. this.add( this.lightDistance );
  5140. */}dispose(){this.geometry.dispose();this.material.dispose();}update(){if(this.color!==undefined){this.material.color.set(this.color);}else {this.material.color.copy(this.light.color);}/*
  5141. const d = this.light.distance;
  5142. if ( d === 0.0 ) {
  5143. this.lightDistance.visible = false;
  5144. } else {
  5145. this.lightDistance.visible = true;
  5146. this.lightDistance.scale.set( d, d, d );
  5147. }
  5148. */}}var _vector$b=/*@__PURE__*/new Vector3();var _color1=/*@__PURE__*/new Color();var _color2=/*@__PURE__*/new Color();class HemisphereLightHelper extends Object3D{constructor(light,size,color){super();this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;var geometry=new OctahedronBufferGeometry(size);geometry.rotateY(Math.PI*0.5);this.material=new MeshBasicMaterial({wireframe:true,fog:false,toneMapped:false});if(this.color===undefined)this.material.vertexColors=true;var position=geometry.getAttribute('position');var colors=new Float32Array(position.count*3);geometry.setAttribute('color',new BufferAttribute(colors,3));this.add(new Mesh(geometry,this.material));this.update();}dispose(){this.children[0].geometry.dispose();this.children[0].material.dispose();}update(){var mesh=this.children[0];if(this.color!==undefined){this.material.color.set(this.color);}else {var colors=mesh.geometry.getAttribute('color');_color1.copy(this.light.color);_color2.copy(this.light.groundColor);for(var _i367=0,l=colors.count;_i367<l;_i367++){var color=_i367<l/2?_color1:_color2;colors.setXYZ(_i367,color.r,color.g,color.b);}colors.needsUpdate=true;}mesh.lookAt(_vector$b.setFromMatrixPosition(this.light.matrixWorld).negate());}}class GridHelper extends LineSegments{constructor(){var size=arguments.length>0&&arguments[0]!==undefined?arguments[0]:10;var divisions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var color1=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0x444444;var color2=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0x888888;color1=new Color(color1);color2=new Color(color2);var center=divisions/2;var step=size/divisions;var halfSize=size/2;var vertices=[],colors=[];for(var _i368=0,j=0,k=-halfSize;_i368<=divisions;_i368++,k+=step){vertices.push(-halfSize,0,k,halfSize,0,k);vertices.push(k,0,-halfSize,k,0,halfSize);var color=_i368===center?color1:color2;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3;color.toArray(colors,j);j+=3;}var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type='GridHelper';}}class PolarGridHelper extends LineSegments{constructor(){var radius=arguments.length>0&&arguments[0]!==undefined?arguments[0]:10;var radials=arguments.length>1&&arguments[1]!==undefined?arguments[1]:16;var circles=arguments.length>2&&arguments[2]!==undefined?arguments[2]:8;var divisions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:64;var color1=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0x444444;var color2=arguments.length>5&&arguments[5]!==undefined?arguments[5]:0x888888;color1=new Color(color1);color2=new Color(color2);var vertices=[];var colors=[];// create the radials
  5149. for(var _i369=0;_i369<=radials;_i369++){var v=_i369/radials*(Math.PI*2);var x=Math.sin(v)*radius;var z=Math.cos(v)*radius;vertices.push(0,0,0);vertices.push(x,0,z);var color=_i369&1?color1:color2;colors.push(color.r,color.g,color.b);colors.push(color.r,color.g,color.b);}// create the circles
  5150. for(var _i370=0;_i370<=circles;_i370++){var _color=_i370&1?color1:color2;var r=radius-radius/circles*_i370;for(var j=0;j<divisions;j++){// first vertex
  5151. var _v4=j/divisions*(Math.PI*2);var _x5=Math.sin(_v4)*r;var _z3=Math.cos(_v4)*r;vertices.push(_x5,0,_z3);colors.push(_color.r,_color.g,_color.b);// second vertex
  5152. _v4=(j+1)/divisions*(Math.PI*2);_x5=Math.sin(_v4)*r;_z3=Math.cos(_v4)*r;vertices.push(_x5,0,_z3);colors.push(_color.r,_color.g,_color.b);}}var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type='PolarGridHelper';}}var _v1$6=/*@__PURE__*/new Vector3();var _v2$3=/*@__PURE__*/new Vector3();var _v3$1=/*@__PURE__*/new Vector3();class DirectionalLightHelper extends Object3D{constructor(light,size,color){super();this.light=light;this.light.updateMatrixWorld();this.matrix=light.matrixWorld;this.matrixAutoUpdate=false;this.color=color;if(size===undefined)size=1;var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute([-size,size,0,size,size,0,size,-size,0,-size,-size,0,-size,size,0],3));var material=new LineBasicMaterial({fog:false,toneMapped:false});this.lightPlane=new Line(geometry,material);this.add(this.lightPlane);geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute([0,0,0,0,0,1],3));this.targetLine=new Line(geometry,material);this.add(this.targetLine);this.update();}dispose(){this.lightPlane.geometry.dispose();this.lightPlane.material.dispose();this.targetLine.geometry.dispose();this.targetLine.material.dispose();}update(){_v1$6.setFromMatrixPosition(this.light.matrixWorld);_v2$3.setFromMatrixPosition(this.light.target.matrixWorld);_v3$1.subVectors(_v2$3,_v1$6);this.lightPlane.lookAt(_v2$3);if(this.color!==undefined){this.lightPlane.material.color.set(this.color);this.targetLine.material.color.set(this.color);}else {this.lightPlane.material.color.copy(this.light.color);this.targetLine.material.color.copy(this.light.color);}this.targetLine.lookAt(_v2$3);this.targetLine.scale.z=_v3$1.length();}}var _vector$c=/*@__PURE__*/new Vector3();var _camera=/*@__PURE__*/new Camera();/**
  5153. * - shows frustum, line of sight and up of the camera
  5154. * - suitable for fast updates
  5155. * - based on frustum visualization in lightgl.js shadowmap example
  5156. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  5157. */class CameraHelper extends LineSegments{constructor(camera){var geometry=new BufferGeometry();var material=new LineBasicMaterial({color:0xffffff,vertexColors:true,toneMapped:false});var vertices=[];var colors=[];var pointMap={};// colors
  5158. var colorFrustum=new Color(0xffaa00);var colorCone=new Color(0xff0000);var colorUp=new Color(0x00aaff);var colorTarget=new Color(0xffffff);var colorCross=new Color(0x333333);// near
  5159. addLine('n1','n2',colorFrustum);addLine('n2','n4',colorFrustum);addLine('n4','n3',colorFrustum);addLine('n3','n1',colorFrustum);// far
  5160. addLine('f1','f2',colorFrustum);addLine('f2','f4',colorFrustum);addLine('f4','f3',colorFrustum);addLine('f3','f1',colorFrustum);// sides
  5161. addLine('n1','f1',colorFrustum);addLine('n2','f2',colorFrustum);addLine('n3','f3',colorFrustum);addLine('n4','f4',colorFrustum);// cone
  5162. addLine('p','n1',colorCone);addLine('p','n2',colorCone);addLine('p','n3',colorCone);addLine('p','n4',colorCone);// up
  5163. addLine('u1','u2',colorUp);addLine('u2','u3',colorUp);addLine('u3','u1',colorUp);// target
  5164. addLine('c','t',colorTarget);addLine('p','c',colorCross);// cross
  5165. addLine('cn1','cn2',colorCross);addLine('cn3','cn4',colorCross);addLine('cf1','cf2',colorCross);addLine('cf3','cf4',colorCross);function addLine(a,b,color){addPoint(a,color);addPoint(b,color);}function addPoint(id,color){vertices.push(0,0,0);colors.push(color.r,color.g,color.b);if(pointMap[id]===undefined){pointMap[id]=[];}pointMap[id].push(vertices.length/3-1);}geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));super(geometry,material);this.type='CameraHelper';this.camera=camera;if(this.camera.updateProjectionMatrix)this.camera.updateProjectionMatrix();this.matrix=camera.matrixWorld;this.matrixAutoUpdate=false;this.pointMap=pointMap;this.update();}update(){var geometry=this.geometry;var pointMap=this.pointMap;var w=1,h=1;// we need just camera projection matrix inverse
  5166. // world matrix must be identity
  5167. _camera.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse);// center / target
  5168. setPoint('c',pointMap,geometry,_camera,0,0,-1);setPoint('t',pointMap,geometry,_camera,0,0,1);// near
  5169. setPoint('n1',pointMap,geometry,_camera,-w,-h,-1);setPoint('n2',pointMap,geometry,_camera,w,-h,-1);setPoint('n3',pointMap,geometry,_camera,-w,h,-1);setPoint('n4',pointMap,geometry,_camera,w,h,-1);// far
  5170. setPoint('f1',pointMap,geometry,_camera,-w,-h,1);setPoint('f2',pointMap,geometry,_camera,w,-h,1);setPoint('f3',pointMap,geometry,_camera,-w,h,1);setPoint('f4',pointMap,geometry,_camera,w,h,1);// up
  5171. setPoint('u1',pointMap,geometry,_camera,w*0.7,h*1.1,-1);setPoint('u2',pointMap,geometry,_camera,-w*0.7,h*1.1,-1);setPoint('u3',pointMap,geometry,_camera,0,h*2,-1);// cross
  5172. setPoint('cf1',pointMap,geometry,_camera,-w,0,1);setPoint('cf2',pointMap,geometry,_camera,w,0,1);setPoint('cf3',pointMap,geometry,_camera,0,-h,1);setPoint('cf4',pointMap,geometry,_camera,0,h,1);setPoint('cn1',pointMap,geometry,_camera,-w,0,-1);setPoint('cn2',pointMap,geometry,_camera,w,0,-1);setPoint('cn3',pointMap,geometry,_camera,0,-h,-1);setPoint('cn4',pointMap,geometry,_camera,0,h,-1);geometry.getAttribute('position').needsUpdate=true;}}function setPoint(point,pointMap,geometry,camera,x,y,z){_vector$c.set(x,y,z).unproject(camera);var points=pointMap[point];if(points!==undefined){var position=geometry.getAttribute('position');for(var _i371=0,l=points.length;_i371<l;_i371++){position.setXYZ(points[_i371],_vector$c.x,_vector$c.y,_vector$c.z);}}}var _box$3=/*@__PURE__*/new Box3();class BoxHelper extends LineSegments{constructor(object){var color=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0xffff00;var indices=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var positions=new Float32Array(8*3);var geometry=new BufferGeometry();geometry.setIndex(new BufferAttribute(indices,1));geometry.setAttribute('position',new BufferAttribute(positions,3));super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.object=object;this.type='BoxHelper';this.matrixAutoUpdate=false;this.update();}update(object){if(object!==undefined){console.warn('THREE.BoxHelper: .update() has no longer arguments.');}if(this.object!==undefined){_box$3.setFromObject(this.object);}if(_box$3.isEmpty())return;var min=_box$3.min;var max=_box$3.max;/*
  5173. 5____4
  5174. 1/___0/|
  5175. | 6__|_7
  5176. 2/___3/
  5177. 0: max.x, max.y, max.z
  5178. 1: min.x, max.y, max.z
  5179. 2: min.x, min.y, max.z
  5180. 3: max.x, min.y, max.z
  5181. 4: max.x, max.y, min.z
  5182. 5: min.x, max.y, min.z
  5183. 6: min.x, min.y, min.z
  5184. 7: max.x, min.y, min.z
  5185. */var position=this.geometry.attributes.position;var array=position.array;array[0]=max.x;array[1]=max.y;array[2]=max.z;array[3]=min.x;array[4]=max.y;array[5]=max.z;array[6]=min.x;array[7]=min.y;array[8]=max.z;array[9]=max.x;array[10]=min.y;array[11]=max.z;array[12]=max.x;array[13]=max.y;array[14]=min.z;array[15]=min.x;array[16]=max.y;array[17]=min.z;array[18]=min.x;array[19]=min.y;array[20]=min.z;array[21]=max.x;array[22]=min.y;array[23]=min.z;position.needsUpdate=true;this.geometry.computeBoundingSphere();}setFromObject(object){this.object=object;this.update();return this;}copy(source){LineSegments.prototype.copy.call(this,source);this.object=source.object;return this;}}class Box3Helper extends LineSegments{constructor(box){var color=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0xffff00;var indices=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]);var positions=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1];var geometry=new BufferGeometry();geometry.setIndex(new BufferAttribute(indices,1));geometry.setAttribute('position',new Float32BufferAttribute(positions,3));super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.box=box;this.type='Box3Helper';this.geometry.computeBoundingSphere();}updateMatrixWorld(force){var box=this.box;if(box.isEmpty())return;box.getCenter(this.position);box.getSize(this.scale);this.scale.multiplyScalar(0.5);super.updateMatrixWorld(force);}}class PlaneHelper extends Line{constructor(plane){var size=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var hex=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0xffff00;var color=hex;var positions=[1,-1,1,-1,1,1,-1,-1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,0,0,1,0,0,0];var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(positions,3));geometry.computeBoundingSphere();super(geometry,new LineBasicMaterial({color:color,toneMapped:false}));this.type='PlaneHelper';this.plane=plane;this.size=size;var positions2=[1,1,1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,1];var geometry2=new BufferGeometry();geometry2.setAttribute('position',new Float32BufferAttribute(positions2,3));geometry2.computeBoundingSphere();this.add(new Mesh(geometry2,new MeshBasicMaterial({color:color,opacity:0.2,transparent:true,depthWrite:false,toneMapped:false})));}updateMatrixWorld(force){var scale=-this.plane.constant;if(Math.abs(scale)<1e-8)scale=1e-8;// sign does not matter
  5186. this.scale.set(0.5*this.size,0.5*this.size,scale);this.children[0].material.side=scale<0?BackSide:FrontSide;// renderer flips side when determinant < 0; flipping not wanted here
  5187. this.lookAt(this.plane.normal);super.updateMatrixWorld(force);}}var _axis$1=/*@__PURE__*/new Vector3();var _lineGeometry,_coneGeometry;class ArrowHelper extends Object3D{constructor(dir,origin,length,color,headLength,headWidth){super();// dir is assumed to be normalized
  5188. this.type='ArrowHelper';if(dir===undefined)dir=new Vector3(0,0,1);if(origin===undefined)origin=new Vector3(0,0,0);if(length===undefined)length=1;if(color===undefined)color=0xffff00;if(headLength===undefined)headLength=0.2*length;if(headWidth===undefined)headWidth=0.2*headLength;if(_lineGeometry===undefined){_lineGeometry=new BufferGeometry();_lineGeometry.setAttribute('position',new Float32BufferAttribute([0,0,0,0,1,0],3));_coneGeometry=new CylinderBufferGeometry(0,0.5,1,5,1);_coneGeometry.translate(0,-0.5,0);}this.position.copy(origin);this.line=new Line(_lineGeometry,new LineBasicMaterial({color:color,toneMapped:false}));this.line.matrixAutoUpdate=false;this.add(this.line);this.cone=new Mesh(_coneGeometry,new MeshBasicMaterial({color:color,toneMapped:false}));this.cone.matrixAutoUpdate=false;this.add(this.cone);this.setDirection(dir);this.setLength(length,headLength,headWidth);}setDirection(dir){// dir is assumed to be normalized
  5189. if(dir.y>0.99999){this.quaternion.set(0,0,0,1);}else if(dir.y<-0.99999){this.quaternion.set(1,0,0,0);}else {_axis$1.set(dir.z,0,-dir.x).normalize();var radians=Math.acos(dir.y);this.quaternion.setFromAxisAngle(_axis$1,radians);}}setLength(length,headLength,headWidth){if(headLength===undefined)headLength=0.2*length;if(headWidth===undefined)headWidth=0.2*headLength;this.line.scale.set(1,Math.max(0.0001,length-headLength),1);// see #17458
  5190. this.line.updateMatrix();this.cone.scale.set(headWidth,headLength,headWidth);this.cone.position.y=length;this.cone.updateMatrix();}setColor(color){this.line.material.color.set(color);this.cone.material.color.set(color);}copy(source){super.copy(source,false);this.line.copy(source.line);this.cone.copy(source.cone);return this;}}class AxesHelper extends LineSegments{constructor(){var size=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;var vertices=[0,0,0,size,0,0,0,0,0,0,size,0,0,0,0,0,0,size];var colors=[1,0,0,1,0.6,0,0,1,0,0.6,1,0,0,0,1,0,0.6,1];var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(vertices,3));geometry.setAttribute('color',new Float32BufferAttribute(colors,3));var material=new LineBasicMaterial({vertexColors:true,toneMapped:false});super(geometry,material);this.type='AxesHelper';}}var _floatView=new Float32Array(1);var _int32View=new Int32Array(_floatView.buffer);var DataUtils={// Converts float32 to float16 (stored as uint16 value).
  5191. toHalfFloat:function toHalfFloat(val){// Source: http://gamedev.stackexchange.com/questions/17326/conversion-of-a-number-from-single-precision-floating-point-representation-to-a/17410#17410
  5192. /* This method is faster than the OpenEXR implementation (very often
  5193. * used, eg. in Ogre), with the additional benefit of rounding, inspired
  5194. * by James Tursa?s half-precision code. */_floatView[0]=val;var x=_int32View[0];var bits=x>>16&0x8000;/* Get the sign */var m=x>>12&0x07ff;/* Keep one extra bit for rounding */var e=x>>23&0xff;/* Using int is faster here */ /* If zero, or denormal, or exponent underflows too much for a denormal
  5195. * half, return signed zero. */if(e<103)return bits;/* If NaN, return NaN. If Inf or exponent overflow, return Inf. */if(e>142){bits|=0x7c00;/* If exponent was 0xff and one mantissa bit was set, it means NaN,
  5196. * not Inf, so make sure we set one mantissa bit too. */bits|=(e==255?0:1)&&x&0x007fffff;return bits;}/* If exponent underflows but not too much, return a denormal */if(e<113){m|=0x0800;/* Extra rounding may overflow and set mantissa to 0 and exponent
  5197. * to 1, which is OK. */bits|=(m>>114-e)+(m>>113-e&1);return bits;}bits|=e-112<<10|m>>1;/* Extra rounding. An overflow will set mantissa to 0 and increment
  5198. * the exponent, which is OK. */bits+=m&1;return bits;}};var LOD_MIN=4;var LOD_MAX=8;var SIZE_MAX=Math.pow(2,LOD_MAX);// The standard deviations (radians) associated with the extra mips. These are
  5199. // chosen to approximate a Trowbridge-Reitz distribution function times the
  5200. // geometric shadowing function. These sigma values squared must match the
  5201. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  5202. var EXTRA_LOD_SIGMA=[0.125,0.215,0.35,0.446,0.526,0.582];var TOTAL_LODS=LOD_MAX-LOD_MIN+1+EXTRA_LOD_SIGMA.length;// The maximum length of the blur for loop. Smaller sigmas will use fewer
  5203. // samples and exit early, but not recompile the shader.
  5204. var MAX_SAMPLES=20;var ENCODINGS={[LinearEncoding]:0,[sRGBEncoding]:1,[RGBEEncoding]:2,[RGBM7Encoding]:3,[RGBM16Encoding]:4,[RGBDEncoding]:5,[GammaEncoding]:6};var _flatCamera=/*@__PURE__*/new OrthographicCamera();var{_lodPlanes,_sizeLods,_sigmas}=/*@__PURE__*/_createPlanes();var _clearColor=/*@__PURE__*/new Color();var _oldTarget=null;// Golden Ratio
  5205. var PHI=(1+Math.sqrt(5))/2;var INV_PHI=1/PHI;// Vertices of a dodecahedron (except the opposites, which represent the
  5206. // same axis), used as axis directions evenly spread on a sphere.
  5207. var _axisDirections=[/*@__PURE__*/new Vector3(1,1,1),/*@__PURE__*/new Vector3(-1,1,1),/*@__PURE__*/new Vector3(1,1,-1),/*@__PURE__*/new Vector3(-1,1,-1),/*@__PURE__*/new Vector3(0,PHI,INV_PHI),/*@__PURE__*/new Vector3(0,PHI,-INV_PHI),/*@__PURE__*/new Vector3(INV_PHI,0,PHI),/*@__PURE__*/new Vector3(-INV_PHI,0,PHI),/*@__PURE__*/new Vector3(PHI,INV_PHI,0),/*@__PURE__*/new Vector3(-PHI,INV_PHI,0)];/**
  5208. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  5209. * (PMREM) from a cubeMap environment texture. This allows different levels of
  5210. * blur to be quickly accessed based on material roughness. It is packed into a
  5211. * special CubeUV format that allows us to perform custom interpolation so that
  5212. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  5213. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  5214. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  5215. * higher roughness levels. In this way we maintain resolution to smoothly
  5216. * interpolate diffuse lighting while limiting sampling computation.
  5217. */class PMREMGenerator{constructor(renderer){this._renderer=renderer;this._pingPongRenderTarget=null;this._blurMaterial=_getBlurShader(MAX_SAMPLES);this._equirectShader=null;this._cubemapShader=null;this._compileMaterial(this._blurMaterial);}/**
  5218. * Generates a PMREM from a supplied Scene, which can be faster than using an
  5219. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  5220. * in radians to be applied to the scene before PMREM generation. Optional near
  5221. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  5222. * is placed at the origin).
  5223. */fromScene(scene){var sigma=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var near=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.1;var far=arguments.length>3&&arguments[3]!==undefined?arguments[3]:100;_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets();this._sceneToCubeUV(scene,near,far,cubeUVRenderTarget);if(sigma>0){this._blur(cubeUVRenderTarget,0,0,sigma);}this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}/**
  5224. * Generates a PMREM from an equirectangular texture, which can be either LDR
  5225. * (RGBFormat) or HDR (RGBEFormat). The ideal input image size is 1k (1024 x 512),
  5226. * as this matches best with the 256 x 256 cubemap output.
  5227. */fromEquirectangular(equirectangular){return this._fromTexture(equirectangular);}/**
  5228. * Generates a PMREM from an cubemap texture, which can be either LDR
  5229. * (RGBFormat) or HDR (RGBEFormat). The ideal input cube size is 256 x 256,
  5230. * as this matches best with the 256 x 256 cubemap output.
  5231. */fromCubemap(cubemap){return this._fromTexture(cubemap);}/**
  5232. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  5233. * your texture's network fetch for increased concurrency.
  5234. */compileCubemapShader(){if(this._cubemapShader===null){this._cubemapShader=_getCubemapShader();this._compileMaterial(this._cubemapShader);}}/**
  5235. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  5236. * your texture's network fetch for increased concurrency.
  5237. */compileEquirectangularShader(){if(this._equirectShader===null){this._equirectShader=_getEquirectShader();this._compileMaterial(this._equirectShader);}}/**
  5238. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  5239. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  5240. * one of them will cause any others to also become unusable.
  5241. */dispose(){this._blurMaterial.dispose();if(this._cubemapShader!==null)this._cubemapShader.dispose();if(this._equirectShader!==null)this._equirectShader.dispose();for(var _i372=0;_i372<_lodPlanes.length;_i372++){_lodPlanes[_i372].dispose();}}// private interface
  5242. _cleanup(outputTarget){this._pingPongRenderTarget.dispose();this._renderer.setRenderTarget(_oldTarget);outputTarget.scissorTest=false;_setViewport(outputTarget,0,0,outputTarget.width,outputTarget.height);}_fromTexture(texture){_oldTarget=this._renderer.getRenderTarget();var cubeUVRenderTarget=this._allocateTargets(texture);this._textureToCubeUV(texture,cubeUVRenderTarget);this._applyPMREM(cubeUVRenderTarget);this._cleanup(cubeUVRenderTarget);return cubeUVRenderTarget;}_allocateTargets(texture){// warning: null texture is valid
  5243. var params={magFilter:NearestFilter,minFilter:NearestFilter,generateMipmaps:false,type:UnsignedByteType,format:RGBEFormat,encoding:_isLDR(texture)?texture.encoding:RGBEEncoding,depthBuffer:false};var cubeUVRenderTarget=_createRenderTarget(params);cubeUVRenderTarget.depthBuffer=texture?false:true;this._pingPongRenderTarget=_createRenderTarget(params);return cubeUVRenderTarget;}_compileMaterial(material){var tmpMesh=new Mesh(_lodPlanes[0],material);this._renderer.compile(tmpMesh,_flatCamera);}_sceneToCubeUV(scene,near,far,cubeUVRenderTarget){var fov=90;var aspect=1;var cubeCamera=new PerspectiveCamera(fov,aspect,near,far);var upSign=[1,-1,1,1,1,1];var forwardSign=[1,1,1,-1,-1,-1];var renderer=this._renderer;var outputEncoding=renderer.outputEncoding;var toneMapping=renderer.toneMapping;renderer.getClearColor(_clearColor);var clearAlpha=renderer.getClearAlpha();renderer.toneMapping=NoToneMapping;renderer.outputEncoding=LinearEncoding;var background=scene.background;if(background&&background.isColor){background.convertSRGBToLinear();// Convert linear to RGBE
  5244. var maxComponent=Math.max(background.r,background.g,background.b);var fExp=Math.min(Math.max(Math.ceil(Math.log2(maxComponent)),-128.0),127.0);background=background.multiplyScalar(Math.pow(2.0,-fExp));var alpha=(fExp+128.0)/255.0;renderer.setClearColor(background,alpha);scene.background=null;}for(var _i373=0;_i373<6;_i373++){var col=_i373%3;if(col==0){cubeCamera.up.set(0,upSign[_i373],0);cubeCamera.lookAt(forwardSign[_i373],0,0);}else if(col==1){cubeCamera.up.set(0,0,upSign[_i373]);cubeCamera.lookAt(0,forwardSign[_i373],0);}else {cubeCamera.up.set(0,upSign[_i373],0);cubeCamera.lookAt(0,0,forwardSign[_i373]);}_setViewport(cubeUVRenderTarget,col*SIZE_MAX,_i373>2?SIZE_MAX:0,SIZE_MAX,SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(scene,cubeCamera);}renderer.toneMapping=toneMapping;renderer.outputEncoding=outputEncoding;renderer.setClearColor(_clearColor,clearAlpha);}_textureToCubeUV(texture,cubeUVRenderTarget){var renderer=this._renderer;if(texture.isCubeTexture){if(this._cubemapShader==null){this._cubemapShader=_getCubemapShader();}}else {if(this._equirectShader==null){this._equirectShader=_getEquirectShader();}}var material=texture.isCubeTexture?this._cubemapShader:this._equirectShader;var mesh=new Mesh(_lodPlanes[0],material);var uniforms=material.uniforms;uniforms['envMap'].value=texture;if(!texture.isCubeTexture){uniforms['texelSize'].value.set(1.0/texture.image.width,1.0/texture.image.height);}uniforms['inputEncoding'].value=ENCODINGS[texture.encoding];uniforms['outputEncoding'].value=ENCODINGS[cubeUVRenderTarget.texture.encoding];_setViewport(cubeUVRenderTarget,0,0,3*SIZE_MAX,2*SIZE_MAX);renderer.setRenderTarget(cubeUVRenderTarget);renderer.render(mesh,_flatCamera);}_applyPMREM(cubeUVRenderTarget){var renderer=this._renderer;var autoClear=renderer.autoClear;renderer.autoClear=false;for(var _i374=1;_i374<TOTAL_LODS;_i374++){var sigma=Math.sqrt(_sigmas[_i374]*_sigmas[_i374]-_sigmas[_i374-1]*_sigmas[_i374-1]);var poleAxis=_axisDirections[(_i374-1)%_axisDirections.length];this._blur(cubeUVRenderTarget,_i374-1,_i374,sigma,poleAxis);}renderer.autoClear=autoClear;}/**
  5245. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  5246. * vertically and horizontally, but this breaks down on a cube. Here we apply
  5247. * the blur latitudinally (around the poles), and then longitudinally (towards
  5248. * the poles) to approximate the orthogonally-separable blur. It is least
  5249. * accurate at the poles, but still does a decent job.
  5250. */_blur(cubeUVRenderTarget,lodIn,lodOut,sigma,poleAxis){var pingPongRenderTarget=this._pingPongRenderTarget;this._halfBlur(cubeUVRenderTarget,pingPongRenderTarget,lodIn,lodOut,sigma,'latitudinal',poleAxis);this._halfBlur(pingPongRenderTarget,cubeUVRenderTarget,lodOut,lodOut,sigma,'longitudinal',poleAxis);}_halfBlur(targetIn,targetOut,lodIn,lodOut,sigmaRadians,direction,poleAxis){var renderer=this._renderer;var blurMaterial=this._blurMaterial;if(direction!=='latitudinal'&&direction!=='longitudinal'){console.error('blur direction must be either latitudinal or longitudinal!');}// Number of standard deviations at which to cut off the discrete approximation.
  5251. var STANDARD_DEVIATIONS=3;var blurMesh=new Mesh(_lodPlanes[lodOut],blurMaterial);var blurUniforms=blurMaterial.uniforms;var pixels=_sizeLods[lodIn]-1;var radiansPerPixel=isFinite(sigmaRadians)?Math.PI/(2*pixels):2*Math.PI/(2*MAX_SAMPLES-1);var sigmaPixels=sigmaRadians/radiansPerPixel;var samples=isFinite(sigmaRadians)?1+Math.floor(STANDARD_DEVIATIONS*sigmaPixels):MAX_SAMPLES;if(samples>MAX_SAMPLES){console.warn("sigmaRadians, ".concat(sigmaRadians,", is too large and will clip, as it requested ").concat(samples," samples when the maximum is set to ").concat(MAX_SAMPLES));}var weights=[];var sum=0;for(var _i375=0;_i375<MAX_SAMPLES;++_i375){var _x6=_i375/sigmaPixels;var weight=Math.exp(-_x6*_x6/2);weights.push(weight);if(_i375==0){sum+=weight;}else if(_i375<samples){sum+=2*weight;}}for(var _i376=0;_i376<weights.length;_i376++){weights[_i376]=weights[_i376]/sum;}blurUniforms['envMap'].value=targetIn.texture;blurUniforms['samples'].value=samples;blurUniforms['weights'].value=weights;blurUniforms['latitudinal'].value=direction==='latitudinal';if(poleAxis){blurUniforms['poleAxis'].value=poleAxis;}blurUniforms['dTheta'].value=radiansPerPixel;blurUniforms['mipInt'].value=LOD_MAX-lodIn;blurUniforms['inputEncoding'].value=ENCODINGS[targetIn.texture.encoding];blurUniforms['outputEncoding'].value=ENCODINGS[targetIn.texture.encoding];var outputSize=_sizeLods[lodOut];var x=3*Math.max(0,SIZE_MAX-2*outputSize);var y=(lodOut===0?0:2*SIZE_MAX)+2*outputSize*(lodOut>LOD_MAX-LOD_MIN?lodOut-LOD_MAX+LOD_MIN:0);_setViewport(targetOut,x,y,3*outputSize,2*outputSize);renderer.setRenderTarget(targetOut);renderer.render(blurMesh,_flatCamera);}}function _isLDR(texture){if(texture===undefined||texture.type!==UnsignedByteType)return false;return texture.encoding===LinearEncoding||texture.encoding===sRGBEncoding||texture.encoding===GammaEncoding;}function _createPlanes(){var _lodPlanes=[];var _sizeLods=[];var _sigmas=[];var lod=LOD_MAX;for(var _i377=0;_i377<TOTAL_LODS;_i377++){var sizeLod=Math.pow(2,lod);_sizeLods.push(sizeLod);var sigma=1.0/sizeLod;if(_i377>LOD_MAX-LOD_MIN){sigma=EXTRA_LOD_SIGMA[_i377-LOD_MAX+LOD_MIN-1];}else if(_i377==0){sigma=0;}_sigmas.push(sigma);var texelSize=1.0/(sizeLod-1);var min=-texelSize/2;var max=1+texelSize/2;var uv1=[min,min,max,min,max,max,min,min,max,max,min,max];var cubeFaces=6;var vertices=6;var positionSize=3;var uvSize=2;var faceIndexSize=1;var position=new Float32Array(positionSize*vertices*cubeFaces);var uv=new Float32Array(uvSize*vertices*cubeFaces);var faceIndex=new Float32Array(faceIndexSize*vertices*cubeFaces);for(var face=0;face<cubeFaces;face++){var x=face%3*2/3-1;var y=face>2?0:-1;var coordinates=[x,y,0,x+2/3,y,0,x+2/3,y+1,0,x,y,0,x+2/3,y+1,0,x,y+1,0];position.set(coordinates,positionSize*vertices*face);uv.set(uv1,uvSize*vertices*face);var fill=[face,face,face,face,face,face];faceIndex.set(fill,faceIndexSize*vertices*face);}var planes=new BufferGeometry();planes.setAttribute('position',new BufferAttribute(position,positionSize));planes.setAttribute('uv',new BufferAttribute(uv,uvSize));planes.setAttribute('faceIndex',new BufferAttribute(faceIndex,faceIndexSize));_lodPlanes.push(planes);if(lod>LOD_MIN){lod--;}}return {_lodPlanes,_sizeLods,_sigmas};}function _createRenderTarget(params){var cubeUVRenderTarget=new WebGLRenderTarget(3*SIZE_MAX,3*SIZE_MAX,params);cubeUVRenderTarget.texture.mapping=CubeUVReflectionMapping;cubeUVRenderTarget.texture.name='PMREM.cubeUv';cubeUVRenderTarget.scissorTest=true;return cubeUVRenderTarget;}function _setViewport(target,x,y,width,height){target.viewport.set(x,y,width,height);target.scissor.set(x,y,width,height);}function _getBlurShader(maxSamples){var weights=new Float32Array(maxSamples);var poleAxis=new Vector3(0,1,0);var shaderMaterial=new RawShaderMaterial({name:'SphericalGaussianBlur',defines:{'n':maxSamples},uniforms:{'envMap':{value:null},'samples':{value:1},'weights':{value:weights},'latitudinal':{value:false},'dTheta':{value:0},'mipInt':{value:0},'poleAxis':{value:poleAxis},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform int samples;\n\t\t\tuniform float weights[ n ];\n\t\t\tuniform bool latitudinal;\n\t\t\tuniform float dTheta;\n\t\t\tuniform float mipInt;\n\t\t\tuniform vec3 poleAxis;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#define ENVMAP_TYPE_CUBE_UV\n\t\t\t#include <cube_uv_reflection_fragment>\n\n\t\t\tvec3 getSample( float theta, vec3 axis ) {\n\n\t\t\t\tfloat cosTheta = cos( theta );\n\t\t\t\t// Rodrigues' axis-angle rotation\n\t\t\t\tvec3 sampleDirection = vOutputDirection * cosTheta\n\t\t\t\t\t+ cross( axis, vOutputDirection ) * sin( theta )\n\t\t\t\t\t+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );\n\n\t\t\t\treturn bilinearCubeUV( envMap, sampleDirection, mipInt );\n\n\t\t\t}\n\n\t\t\tvoid main() {\n\n\t\t\t\tvec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );\n\n\t\t\t\tif ( all( equal( axis, vec3( 0.0 ) ) ) ) {\n\n\t\t\t\t\taxis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );\n\n\t\t\t\t}\n\n\t\t\t\taxis = normalize( axis );\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );\n\n\t\t\t\tfor ( int i = 1; i < n; i++ ) {\n\n\t\t\t\t\tif ( i >= samples ) {\n\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat theta = dTheta * float( i );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );\n\t\t\t\t\tgl_FragColor.rgb += weights[ i ] * getSample( theta, axis );\n\n\t\t\t\t}\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getEquirectShader(){var texelSize=new Vector2(1,1);var shaderMaterial=new RawShaderMaterial({name:'EquirectangularToCubeUV',uniforms:{'envMap':{value:null},'texelSize':{value:texelSize},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform sampler2D envMap;\n\t\t\tuniform vec2 texelSize;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\t#include <common>\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\n\t\t\t\tvec3 outputDirection = normalize( vOutputDirection );\n\t\t\t\tvec2 uv = equirectUv( outputDirection );\n\n\t\t\t\tvec2 f = fract( uv / texelSize - 0.5 );\n\t\t\t\tuv -= f * texelSize;\n\t\t\t\tvec3 tl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x += texelSize.x;\n\t\t\t\tvec3 tr = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.y += texelSize.y;\n\t\t\t\tvec3 br = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\t\t\t\tuv.x -= texelSize.x;\n\t\t\t\tvec3 bl = envMapTexelToLinear( texture2D ( envMap, uv ) ).rgb;\n\n\t\t\t\tvec3 tm = mix( tl, tr, f.x );\n\t\t\t\tvec3 bm = mix( bl, br, f.x );\n\t\t\t\tgl_FragColor.rgb = mix( tm, bm, f.y );\n\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCubemapShader(){var shaderMaterial=new RawShaderMaterial({name:'CubemapToCubeUV',uniforms:{'envMap':{value:null},'inputEncoding':{value:ENCODINGS[LinearEncoding]},'outputEncoding':{value:ENCODINGS[LinearEncoding]}},vertexShader:_getCommonVertexShader(),fragmentShader:/* glsl */"\n\n\t\t\tprecision mediump float;\n\t\t\tprecision mediump int;\n\n\t\t\tvarying vec3 vOutputDirection;\n\n\t\t\tuniform samplerCube envMap;\n\n\t\t\t".concat(_getEncodings(),"\n\n\t\t\tvoid main() {\n\n\t\t\t\tgl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t\t\t\tgl_FragColor.rgb = envMapTexelToLinear( textureCube( envMap, vec3( - vOutputDirection.x, vOutputDirection.yz ) ) ).rgb;\n\t\t\t\tgl_FragColor = linearToOutputTexel( gl_FragColor );\n\n\t\t\t}\n\t\t"),blending:NoBlending,depthTest:false,depthWrite:false});return shaderMaterial;}function _getCommonVertexShader(){return/* glsl */"\n\n\t\tprecision mediump float;\n\t\tprecision mediump int;\n\n\t\tattribute vec3 position;\n\t\tattribute vec2 uv;\n\t\tattribute float faceIndex;\n\n\t\tvarying vec3 vOutputDirection;\n\n\t\t// RH coordinate system; PMREM face-indexing convention\n\t\tvec3 getDirection( vec2 uv, float face ) {\n\n\t\t\tuv = 2.0 * uv - 1.0;\n\n\t\t\tvec3 direction = vec3( uv, 1.0 );\n\n\t\t\tif ( face == 0.0 ) {\n\n\t\t\t\tdirection = direction.zyx; // ( 1, v, u ) pos x\n\n\t\t\t} else if ( face == 1.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xz *= -1.0; // ( -u, 1, -v ) pos y\n\n\t\t\t} else if ( face == 2.0 ) {\n\n\t\t\t\tdirection.x *= -1.0; // ( -u, v, 1 ) pos z\n\n\t\t\t} else if ( face == 3.0 ) {\n\n\t\t\t\tdirection = direction.zyx;\n\t\t\t\tdirection.xz *= -1.0; // ( -1, v, -u ) neg x\n\n\t\t\t} else if ( face == 4.0 ) {\n\n\t\t\t\tdirection = direction.xzy;\n\t\t\t\tdirection.xy *= -1.0; // ( -u, -1, v ) neg y\n\n\t\t\t} else if ( face == 5.0 ) {\n\n\t\t\t\tdirection.z *= -1.0; // ( u, v, -1 ) neg z\n\n\t\t\t}\n\n\t\t\treturn direction;\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\tvOutputDirection = getDirection( uv, faceIndex );\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}\n\t";}function _getEncodings(){return/* glsl */"\n\n\t\tuniform int inputEncoding;\n\t\tuniform int outputEncoding;\n\n\t\t#include <encodings_pars_fragment>\n\n\t\tvec4 inputTexelToLinear( vec4 value ) {\n\n\t\t\tif ( inputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( inputEncoding == 1 ) {\n\n\t\t\t\treturn sRGBToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 2 ) {\n\n\t\t\t\treturn RGBEToLinear( value );\n\n\t\t\t} else if ( inputEncoding == 3 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 7.0 );\n\n\t\t\t} else if ( inputEncoding == 4 ) {\n\n\t\t\t\treturn RGBMToLinear( value, 16.0 );\n\n\t\t\t} else if ( inputEncoding == 5 ) {\n\n\t\t\t\treturn RGBDToLinear( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn GammaToLinear( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 linearToOutputTexel( vec4 value ) {\n\n\t\t\tif ( outputEncoding == 0 ) {\n\n\t\t\t\treturn value;\n\n\t\t\t} else if ( outputEncoding == 1 ) {\n\n\t\t\t\treturn LinearTosRGB( value );\n\n\t\t\t} else if ( outputEncoding == 2 ) {\n\n\t\t\t\treturn LinearToRGBE( value );\n\n\t\t\t} else if ( outputEncoding == 3 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 7.0 );\n\n\t\t\t} else if ( outputEncoding == 4 ) {\n\n\t\t\t\treturn LinearToRGBM( value, 16.0 );\n\n\t\t\t} else if ( outputEncoding == 5 ) {\n\n\t\t\t\treturn LinearToRGBD( value, 256.0 );\n\n\t\t\t} else {\n\n\t\t\t\treturn LinearToGamma( value, 2.2 );\n\n\t\t\t}\n\n\t\t}\n\n\t\tvec4 envMapTexelToLinear( vec4 color ) {\n\n\t\t\treturn inputTexelToLinear( color );\n\n\t\t}\n\t";}function Face4(a,b,c,d,normal,color,materialIndex){console.warn('THREE.Face4 has been removed. A THREE.Face3 will be created instead.');return new Face3(a,b,c,normal,color,materialIndex);}var LineStrip=0;var LinePieces=1;var NoColors=0;var FaceColors=1;var VertexColors=2;function MeshFaceMaterial(materials){console.warn('THREE.MeshFaceMaterial has been removed. Use an Array instead.');return materials;}function MultiMaterial(){var materials=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];console.warn('THREE.MultiMaterial has been removed. Use an Array instead.');materials.isMultiMaterial=true;materials.materials=materials;materials.clone=function(){return materials.slice();};return materials;}function PointCloud(geometry,material){console.warn('THREE.PointCloud has been renamed to THREE.Points.');return new Points(geometry,material);}function Particle(material){console.warn('THREE.Particle has been renamed to THREE.Sprite.');return new Sprite$1(material);}function ParticleSystem(geometry,material){console.warn('THREE.ParticleSystem has been renamed to THREE.Points.');return new Points(geometry,material);}function PointCloudMaterial(parameters){console.warn('THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.');return new PointsMaterial(parameters);}function ParticleBasicMaterial(parameters){console.warn('THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.');return new PointsMaterial(parameters);}function ParticleSystemMaterial(parameters){console.warn('THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.');return new PointsMaterial(parameters);}function Vertex(x,y,z){console.warn('THREE.Vertex has been removed. Use THREE.Vector3 instead.');return new Vector3(x,y,z);}//
  5252. function DynamicBufferAttribute(array,itemSize){console.warn('THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setUsage( THREE.DynamicDrawUsage ) instead.');return new BufferAttribute(array,itemSize).setUsage(DynamicDrawUsage);}function Int8Attribute(array,itemSize){console.warn('THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.');return new Int8BufferAttribute(array,itemSize);}function Uint8Attribute(array,itemSize){console.warn('THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.');return new Uint8BufferAttribute(array,itemSize);}function Uint8ClampedAttribute(array,itemSize){console.warn('THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.');return new Uint8ClampedBufferAttribute(array,itemSize);}function Int16Attribute(array,itemSize){console.warn('THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.');return new Int16BufferAttribute(array,itemSize);}function Uint16Attribute(array,itemSize){console.warn('THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.');return new Uint16BufferAttribute(array,itemSize);}function Int32Attribute(array,itemSize){console.warn('THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.');return new Int32BufferAttribute(array,itemSize);}function Uint32Attribute(array,itemSize){console.warn('THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.');return new Uint32BufferAttribute(array,itemSize);}function Float32Attribute(array,itemSize){console.warn('THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.');return new Float32BufferAttribute(array,itemSize);}function Float64Attribute(array,itemSize){console.warn('THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.');return new Float64BufferAttribute(array,itemSize);}//
  5253. Curve.create=function(construct,getPoint){console.log('THREE.Curve.create() has been deprecated');construct.prototype=Object.create(Curve.prototype);construct.prototype.constructor=construct;construct.prototype.getPoint=getPoint;return construct;};//
  5254. Object.assign(CurvePath.prototype,{createPointsGeometry:function createPointsGeometry(divisions){console.warn('THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from path points (for Line or Points objects)
  5255. var pts=this.getPoints(divisions);return this.createGeometry(pts);},createSpacedPointsGeometry:function createSpacedPointsGeometry(divisions){console.warn('THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');// generate geometry from equidistant sampling along the path
  5256. var pts=this.getSpacedPoints(divisions);return this.createGeometry(pts);},createGeometry:function createGeometry(points){console.warn('THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.');var geometry=new Geometry();for(var _i378=0,l=points.length;_i378<l;_i378++){var point=points[_i378];geometry.vertices.push(new Vector3(point.x,point.y,point.z||0));}return geometry;}});//
  5257. Object.assign(Path.prototype,{fromPoints:function fromPoints(points){console.warn('THREE.Path: .fromPoints() has been renamed to .setFromPoints().');return this.setFromPoints(points);}});//
  5258. function ClosedSplineCurve3(points){console.warn('THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');CatmullRomCurve3.call(this,points);this.type='catmullrom';this.closed=true;}ClosedSplineCurve3.prototype=Object.create(CatmullRomCurve3.prototype);//
  5259. function SplineCurve3(points){console.warn('THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.');CatmullRomCurve3.call(this,points);this.type='catmullrom';}SplineCurve3.prototype=Object.create(CatmullRomCurve3.prototype);//
  5260. function Spline(points){console.warn('THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.');CatmullRomCurve3.call(this,points);this.type='catmullrom';}Spline.prototype=Object.create(CatmullRomCurve3.prototype);Object.assign(Spline.prototype,{initFromArray:function initFromArray(/* a */){console.error('THREE.Spline: .initFromArray() has been removed.');},getControlPointsArray:function getControlPointsArray(/* optionalTarget */){console.error('THREE.Spline: .getControlPointsArray() has been removed.');},reparametrizeByArcLength:function reparametrizeByArcLength(/* samplingCoef */){console.error('THREE.Spline: .reparametrizeByArcLength() has been removed.');}});//
  5261. function AxisHelper(size){console.warn('THREE.AxisHelper has been renamed to THREE.AxesHelper.');return new AxesHelper(size);}function BoundingBoxHelper(object,color){console.warn('THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.');return new BoxHelper(object,color);}function EdgesHelper(object,hex){console.warn('THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.');return new LineSegments(new EdgesGeometry(object.geometry),new LineBasicMaterial({color:hex!==undefined?hex:0xffffff}));}GridHelper.prototype.setColors=function(){console.error('THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.');};SkeletonHelper.prototype.update=function(){console.error('THREE.SkeletonHelper: update() no longer needs to be called.');};function WireframeHelper(object,hex){console.warn('THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.');return new LineSegments(new WireframeGeometry(object.geometry),new LineBasicMaterial({color:hex!==undefined?hex:0xffffff}));}//
  5262. Object.assign(Loader.prototype,{extractUrlBase:function extractUrlBase(url){console.warn('THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.');return LoaderUtils.extractUrlBase(url);}});Loader.Handlers={add:function add(/* regex, loader */){console.error('THREE.Loader: Handlers.add() has been removed. Use LoadingManager.addHandler() instead.');},get:function get(/* file */){console.error('THREE.Loader: Handlers.get() has been removed. Use LoadingManager.getHandler() instead.');}};function XHRLoader(manager){console.warn('THREE.XHRLoader has been renamed to THREE.FileLoader.');return new FileLoader(manager);}function BinaryTextureLoader(manager){console.warn('THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.');return new DataTextureLoader(manager);}//
  5263. Object.assign(Box2.prototype,{center:function center(optionalTarget){console.warn('THREE.Box2: .center() has been renamed to .getCenter().');return this.getCenter(optionalTarget);},empty:function empty(){console.warn('THREE.Box2: .empty() has been renamed to .isEmpty().');return this.isEmpty();},isIntersectionBox:function isIntersectionBox(box){console.warn('THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().');return this.intersectsBox(box);},size:function size(optionalTarget){console.warn('THREE.Box2: .size() has been renamed to .getSize().');return this.getSize(optionalTarget);}});Object.assign(Box3.prototype,{center:function center(optionalTarget){console.warn('THREE.Box3: .center() has been renamed to .getCenter().');return this.getCenter(optionalTarget);},empty:function empty(){console.warn('THREE.Box3: .empty() has been renamed to .isEmpty().');return this.isEmpty();},isIntersectionBox:function isIntersectionBox(box){console.warn('THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().');return this.intersectsBox(box);},isIntersectionSphere:function isIntersectionSphere(sphere){console.warn('THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().');return this.intersectsSphere(sphere);},size:function size(optionalTarget){console.warn('THREE.Box3: .size() has been renamed to .getSize().');return this.getSize(optionalTarget);}});Object.assign(Sphere.prototype,{empty:function empty(){console.warn('THREE.Sphere: .empty() has been renamed to .isEmpty().');return this.isEmpty();}});Frustum.prototype.setFromMatrix=function(m){console.warn('THREE.Frustum: .setFromMatrix() has been renamed to .setFromProjectionMatrix().');return this.setFromProjectionMatrix(m);};Line3.prototype.center=function(optionalTarget){console.warn('THREE.Line3: .center() has been renamed to .getCenter().');return this.getCenter(optionalTarget);};Object.assign(MathUtils,{random16:function random16(){console.warn('THREE.Math: .random16() has been deprecated. Use Math.random() instead.');return Math.random();},nearestPowerOfTwo:function nearestPowerOfTwo(value){console.warn('THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().');return MathUtils.floorPowerOfTwo(value);},nextPowerOfTwo:function nextPowerOfTwo(value){console.warn('THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().');return MathUtils.ceilPowerOfTwo(value);}});Object.assign(Matrix3.prototype,{flattenToArrayOffset:function flattenToArrayOffset(array,offset){console.warn('THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');return this.toArray(array,offset);},multiplyVector3:function multiplyVector3(vector){console.warn('THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.');return vector.applyMatrix3(this);},multiplyVector3Array:function multiplyVector3Array(/* a */){console.error('THREE.Matrix3: .multiplyVector3Array() has been removed.');},applyToBufferAttribute:function applyToBufferAttribute(attribute){console.warn('THREE.Matrix3: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix3( matrix ) instead.');return attribute.applyMatrix3(this);},applyToVector3Array:function applyToVector3Array(/* array, offset, length */){console.error('THREE.Matrix3: .applyToVector3Array() has been removed.');},getInverse:function getInverse(matrix){console.warn('THREE.Matrix3: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');return this.copy(matrix).invert();}});Object.assign(Matrix4.prototype,{extractPosition:function extractPosition(m){console.warn('THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().');return this.copyPosition(m);},flattenToArrayOffset:function flattenToArrayOffset(array,offset){console.warn('THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead.');return this.toArray(array,offset);},getPosition:function getPosition(){console.warn('THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.');return new Vector3().setFromMatrixColumn(this,3);},setRotationFromQuaternion:function setRotationFromQuaternion(q){console.warn('THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().');return this.makeRotationFromQuaternion(q);},multiplyToArray:function multiplyToArray(){console.warn('THREE.Matrix4: .multiplyToArray() has been removed.');},multiplyVector3:function multiplyVector3(vector){console.warn('THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.');return vector.applyMatrix4(this);},multiplyVector4:function multiplyVector4(vector){console.warn('THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.');return vector.applyMatrix4(this);},multiplyVector3Array:function multiplyVector3Array(/* a */){console.error('THREE.Matrix4: .multiplyVector3Array() has been removed.');},rotateAxis:function rotateAxis(v){console.warn('THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.');v.transformDirection(this);},crossVector:function crossVector(vector){console.warn('THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.');return vector.applyMatrix4(this);},translate:function translate(){console.error('THREE.Matrix4: .translate() has been removed.');},rotateX:function rotateX(){console.error('THREE.Matrix4: .rotateX() has been removed.');},rotateY:function rotateY(){console.error('THREE.Matrix4: .rotateY() has been removed.');},rotateZ:function rotateZ(){console.error('THREE.Matrix4: .rotateZ() has been removed.');},rotateByAxis:function rotateByAxis(){console.error('THREE.Matrix4: .rotateByAxis() has been removed.');},applyToBufferAttribute:function applyToBufferAttribute(attribute){console.warn('THREE.Matrix4: .applyToBufferAttribute() has been removed. Use attribute.applyMatrix4( matrix ) instead.');return attribute.applyMatrix4(this);},applyToVector3Array:function applyToVector3Array(/* array, offset, length */){console.error('THREE.Matrix4: .applyToVector3Array() has been removed.');},makeFrustum:function makeFrustum(left,right,bottom,top,near,far){console.warn('THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.');return this.makePerspective(left,right,top,bottom,near,far);},getInverse:function getInverse(matrix){console.warn('THREE.Matrix4: .getInverse() has been removed. Use matrixInv.copy( matrix ).invert(); instead.');return this.copy(matrix).invert();}});Plane.prototype.isIntersectionLine=function(line){console.warn('THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().');return this.intersectsLine(line);};Object.assign(Quaternion.prototype,{multiplyVector3:function multiplyVector3(vector){console.warn('THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.');return vector.applyQuaternion(this);},inverse:function inverse(){console.warn('THREE.Quaternion: .inverse() has been renamed to invert().');return this.invert();}});Object.assign(Ray.prototype,{isIntersectionBox:function isIntersectionBox(box){console.warn('THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().');return this.intersectsBox(box);},isIntersectionPlane:function isIntersectionPlane(plane){console.warn('THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().');return this.intersectsPlane(plane);},isIntersectionSphere:function isIntersectionSphere(sphere){console.warn('THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().');return this.intersectsSphere(sphere);}});Object.assign(Triangle.prototype,{area:function area(){console.warn('THREE.Triangle: .area() has been renamed to .getArea().');return this.getArea();},barycoordFromPoint:function barycoordFromPoint(point,target){console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');return this.getBarycoord(point,target);},midpoint:function midpoint(target){console.warn('THREE.Triangle: .midpoint() has been renamed to .getMidpoint().');return this.getMidpoint(target);},normal:function normal(target){console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');return this.getNormal(target);},plane:function plane(target){console.warn('THREE.Triangle: .plane() has been renamed to .getPlane().');return this.getPlane(target);}});Object.assign(Triangle,{barycoordFromPoint:function barycoordFromPoint(point,a,b,c,target){console.warn('THREE.Triangle: .barycoordFromPoint() has been renamed to .getBarycoord().');return Triangle.getBarycoord(point,a,b,c,target);},normal:function normal(a,b,c,target){console.warn('THREE.Triangle: .normal() has been renamed to .getNormal().');return Triangle.getNormal(a,b,c,target);}});Object.assign(Shape.prototype,{extractAllPoints:function extractAllPoints(divisions){console.warn('THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.');return this.extractPoints(divisions);},extrude:function extrude(options){console.warn('THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.');return new ExtrudeGeometry(this,options);},makeGeometry:function makeGeometry(options){console.warn('THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.');return new ShapeGeometry(this,options);}});Object.assign(Vector2.prototype,{fromAttribute:function fromAttribute(attribute,index,offset){console.warn('THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().');return this.fromBufferAttribute(attribute,index,offset);},distanceToManhattan:function distanceToManhattan(v){console.warn('THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');return this.manhattanDistanceTo(v);},lengthManhattan:function lengthManhattan(){console.warn('THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().');return this.manhattanLength();}});Object.assign(Vector3.prototype,{setEulerFromRotationMatrix:function setEulerFromRotationMatrix(){console.error('THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.');},setEulerFromQuaternion:function setEulerFromQuaternion(){console.error('THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.');},getPositionFromMatrix:function getPositionFromMatrix(m){console.warn('THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().');return this.setFromMatrixPosition(m);},getScaleFromMatrix:function getScaleFromMatrix(m){console.warn('THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().');return this.setFromMatrixScale(m);},getColumnFromMatrix:function getColumnFromMatrix(index,matrix){console.warn('THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().');return this.setFromMatrixColumn(matrix,index);},applyProjection:function applyProjection(m){console.warn('THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.');return this.applyMatrix4(m);},fromAttribute:function fromAttribute(attribute,index,offset){console.warn('THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().');return this.fromBufferAttribute(attribute,index,offset);},distanceToManhattan:function distanceToManhattan(v){console.warn('THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().');return this.manhattanDistanceTo(v);},lengthManhattan:function lengthManhattan(){console.warn('THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().');return this.manhattanLength();}});Object.assign(Vector4.prototype,{fromAttribute:function fromAttribute(attribute,index,offset){console.warn('THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().');return this.fromBufferAttribute(attribute,index,offset);},lengthManhattan:function lengthManhattan(){console.warn('THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().');return this.manhattanLength();}});//
  5264. Object.assign(Geometry.prototype,{computeTangents:function computeTangents(){console.error('THREE.Geometry: .computeTangents() has been removed.');},computeLineDistances:function computeLineDistances(){console.error('THREE.Geometry: .computeLineDistances() has been removed. Use THREE.Line.computeLineDistances() instead.');},applyMatrix:function applyMatrix(matrix){console.warn('THREE.Geometry: .applyMatrix() has been renamed to .applyMatrix4().');return this.applyMatrix4(matrix);}});Object.assign(Object3D.prototype,{getChildByName:function getChildByName(name){console.warn('THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().');return this.getObjectByName(name);},renderDepth:function renderDepth(){console.warn('THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.');},translate:function translate(distance,axis){console.warn('THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.');return this.translateOnAxis(axis,distance);},getWorldRotation:function getWorldRotation(){console.error('THREE.Object3D: .getWorldRotation() has been removed. Use THREE.Object3D.getWorldQuaternion( target ) instead.');},applyMatrix:function applyMatrix(matrix){console.warn('THREE.Object3D: .applyMatrix() has been renamed to .applyMatrix4().');return this.applyMatrix4(matrix);}});Object.defineProperties(Object3D.prototype,{eulerOrder:{get:function get(){console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');return this.rotation.order;},set:function set(value){console.warn('THREE.Object3D: .eulerOrder is now .rotation.order.');this.rotation.order=value;}},useQuaternion:{get:function get(){console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');},set:function set(){console.warn('THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.');}}});Object.assign(Mesh.prototype,{setDrawMode:function setDrawMode(){console.error('THREE.Mesh: .setDrawMode() has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');}});Object.defineProperties(Mesh.prototype,{drawMode:{get:function get(){console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode.');return TrianglesDrawMode;},set:function set(){console.error('THREE.Mesh: .drawMode has been removed. The renderer now always assumes THREE.TrianglesDrawMode. Transform your geometry via BufferGeometryUtils.toTrianglesDrawMode() if necessary.');}}});Object.defineProperties(LOD.prototype,{objects:{get:function get(){console.warn('THREE.LOD: .objects has been renamed to .levels.');return this.levels;}}});Object.defineProperty(Skeleton.prototype,'useVertexTexture',{get:function get(){console.warn('THREE.Skeleton: useVertexTexture has been removed.');},set:function set(){console.warn('THREE.Skeleton: useVertexTexture has been removed.');}});SkinnedMesh.prototype.initBones=function(){console.error('THREE.SkinnedMesh: initBones() has been removed.');};Object.defineProperty(Curve.prototype,'__arcLengthDivisions',{get:function get(){console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');return this.arcLengthDivisions;},set:function set(value){console.warn('THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.');this.arcLengthDivisions=value;}});//
  5265. PerspectiveCamera.prototype.setLens=function(focalLength,filmGauge){console.warn('THREE.PerspectiveCamera.setLens is deprecated. '+'Use .setFocalLength and .filmGauge for a photographic setup.');if(filmGauge!==undefined)this.filmGauge=filmGauge;this.setFocalLength(focalLength);};//
  5266. Object.defineProperties(Light.prototype,{onlyShadow:{set:function set(){console.warn('THREE.Light: .onlyShadow has been removed.');}},shadowCameraFov:{set:function set(value){console.warn('THREE.Light: .shadowCameraFov is now .shadow.camera.fov.');this.shadow.camera.fov=value;}},shadowCameraLeft:{set:function set(value){console.warn('THREE.Light: .shadowCameraLeft is now .shadow.camera.left.');this.shadow.camera.left=value;}},shadowCameraRight:{set:function set(value){console.warn('THREE.Light: .shadowCameraRight is now .shadow.camera.right.');this.shadow.camera.right=value;}},shadowCameraTop:{set:function set(value){console.warn('THREE.Light: .shadowCameraTop is now .shadow.camera.top.');this.shadow.camera.top=value;}},shadowCameraBottom:{set:function set(value){console.warn('THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.');this.shadow.camera.bottom=value;}},shadowCameraNear:{set:function set(value){console.warn('THREE.Light: .shadowCameraNear is now .shadow.camera.near.');this.shadow.camera.near=value;}},shadowCameraFar:{set:function set(value){console.warn('THREE.Light: .shadowCameraFar is now .shadow.camera.far.');this.shadow.camera.far=value;}},shadowCameraVisible:{set:function set(){console.warn('THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.');}},shadowBias:{set:function set(value){console.warn('THREE.Light: .shadowBias is now .shadow.bias.');this.shadow.bias=value;}},shadowDarkness:{set:function set(){console.warn('THREE.Light: .shadowDarkness has been removed.');}},shadowMapWidth:{set:function set(value){console.warn('THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.');this.shadow.mapSize.width=value;}},shadowMapHeight:{set:function set(value){console.warn('THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.');this.shadow.mapSize.height=value;}}});//
  5267. Object.defineProperties(BufferAttribute.prototype,{length:{get:function get(){console.warn('THREE.BufferAttribute: .length has been deprecated. Use .count instead.');return this.array.length;}},dynamic:{get:function get(){console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');return this.usage===DynamicDrawUsage;},set:function set(/* value */){console.warn('THREE.BufferAttribute: .dynamic has been deprecated. Use .usage instead.');this.setUsage(DynamicDrawUsage);}}});Object.assign(BufferAttribute.prototype,{setDynamic:function setDynamic(value){//console.warn( 'THREE.BufferAttribute: .setDynamic() has been deprecated. Use .setUsage() instead.' );
  5268. this.setUsage(value===true?DynamicDrawUsage:StaticDrawUsage);return this;},copyIndicesArray:function copyIndicesArray(/* indices */){console.error('THREE.BufferAttribute: .copyIndicesArray() has been removed.');},setArray:function setArray(/* array */){console.error('THREE.BufferAttribute: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');}});Object.assign(BufferGeometry.prototype,{addIndex:function addIndex(index){console.warn('THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().');this.setIndex(index);},addAttribute:function addAttribute(name,attribute){console.warn('THREE.BufferGeometry: .addAttribute() has been renamed to .setAttribute().');if(!(attribute&&attribute.isBufferAttribute)&&!(attribute&&attribute.isInterleavedBufferAttribute)){console.warn('THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).');return this.setAttribute(name,new BufferAttribute(arguments[1],arguments[2]));}if(name==='index'){console.warn('THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.');this.setIndex(attribute);return this;}return this.setAttribute(name,attribute);},addDrawCall:function addDrawCall(start,count,indexOffset){if(indexOffset!==undefined){console.warn('THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.');}console.warn('THREE.BufferGeometry: .addDrawCall() is now .addGroup().');this.addGroup(start,count);},clearDrawCalls:function clearDrawCalls(){console.warn('THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().');this.clearGroups();},computeTangents:function computeTangents(){console.warn('THREE.BufferGeometry: .computeTangents() has been removed.');},computeOffsets:function computeOffsets(){console.warn('THREE.BufferGeometry: .computeOffsets() has been removed.');},removeAttribute:function removeAttribute(name){console.warn('THREE.BufferGeometry: .removeAttribute() has been renamed to .deleteAttribute().');return this.deleteAttribute(name);},applyMatrix:function applyMatrix(matrix){console.warn('THREE.BufferGeometry: .applyMatrix() has been renamed to .applyMatrix4().');return this.applyMatrix4(matrix);}});Object.defineProperties(BufferGeometry.prototype,{drawcalls:{get:function get(){console.error('THREE.BufferGeometry: .drawcalls has been renamed to .groups.');return this.groups;}},offsets:{get:function get(){console.warn('THREE.BufferGeometry: .offsets has been renamed to .groups.');return this.groups;}}});Object.defineProperties(InstancedBufferGeometry.prototype,{maxInstancedCount:{get:function get(){console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');return this.instanceCount;},set:function set(value){console.warn('THREE.InstancedBufferGeometry: .maxInstancedCount has been renamed to .instanceCount.');this.instanceCount=value;}}});Object.defineProperties(Raycaster.prototype,{linePrecision:{get:function get(){console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');return this.params.Line.threshold;},set:function set(value){console.warn('THREE.Raycaster: .linePrecision has been deprecated. Use .params.Line.threshold instead.');this.params.Line.threshold=value;}}});Object.defineProperties(InterleavedBuffer.prototype,{dynamic:{get:function get(){console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');return this.usage===DynamicDrawUsage;},set:function set(value){console.warn('THREE.InterleavedBuffer: .length has been deprecated. Use .usage instead.');this.setUsage(value);}}});Object.assign(InterleavedBuffer.prototype,{setDynamic:function setDynamic(value){console.warn('THREE.InterleavedBuffer: .setDynamic() has been deprecated. Use .setUsage() instead.');this.setUsage(value===true?DynamicDrawUsage:StaticDrawUsage);return this;},setArray:function setArray(/* array */){console.error('THREE.InterleavedBuffer: .setArray has been removed. Use BufferGeometry .setAttribute to replace/resize attribute buffers');}});//
  5269. Object.assign(ExtrudeBufferGeometry.prototype,{getArrays:function getArrays(){console.error('THREE.ExtrudeBufferGeometry: .getArrays() has been removed.');},addShapeList:function addShapeList(){console.error('THREE.ExtrudeBufferGeometry: .addShapeList() has been removed.');},addShape:function addShape(){console.error('THREE.ExtrudeBufferGeometry: .addShape() has been removed.');}});//
  5270. Object.assign(Scene.prototype,{dispose:function dispose(){console.error('THREE.Scene: .dispose() has been removed.');}});//
  5271. Object.defineProperties(Uniform.prototype,{dynamic:{set:function set(){console.warn('THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.');}},onUpdate:{value:function value(){console.warn('THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.');return this;}}});//
  5272. Object.defineProperties(Material.prototype,{wrapAround:{get:function get(){console.warn('THREE.Material: .wrapAround has been removed.');},set:function set(){console.warn('THREE.Material: .wrapAround has been removed.');}},overdraw:{get:function get(){console.warn('THREE.Material: .overdraw has been removed.');},set:function set(){console.warn('THREE.Material: .overdraw has been removed.');}},wrapRGB:{get:function get(){console.warn('THREE.Material: .wrapRGB has been removed.');return new Color();}},shading:{get:function get(){console.error('THREE.'+this.type+': .shading has been removed. Use the boolean .flatShading instead.');},set:function set(value){console.warn('THREE.'+this.type+': .shading has been removed. Use the boolean .flatShading instead.');this.flatShading=value===FlatShading$1;}},stencilMask:{get:function get(){console.warn('THREE.'+this.type+': .stencilMask has been removed. Use .stencilFuncMask instead.');return this.stencilFuncMask;},set:function set(value){console.warn('THREE.'+this.type+': .stencilMask has been removed. Use .stencilFuncMask instead.');this.stencilFuncMask=value;}}});Object.defineProperties(MeshPhongMaterial.prototype,{metal:{get:function get(){console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.');return false;},set:function set(){console.warn('THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead');}}});Object.defineProperties(MeshPhysicalMaterial.prototype,{transparency:{get:function get(){console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');return this.transmission;},set:function set(value){console.warn('THREE.MeshPhysicalMaterial: .transparency has been renamed to .transmission.');this.transmission=value;}}});Object.defineProperties(ShaderMaterial.prototype,{derivatives:{get:function get(){console.warn('THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');return this.extensions.derivatives;},set:function set(value){console.warn('THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.');this.extensions.derivatives=value;}}});//
  5273. Object.assign(WebGLRenderer.prototype,{clearTarget:function clearTarget(renderTarget,color,depth,stencil){console.warn('THREE.WebGLRenderer: .clearTarget() has been deprecated. Use .setRenderTarget() and .clear() instead.');this.setRenderTarget(renderTarget);this.clear(color,depth,stencil);},animate:function animate(callback){console.warn('THREE.WebGLRenderer: .animate() is now .setAnimationLoop().');this.setAnimationLoop(callback);},getCurrentRenderTarget:function getCurrentRenderTarget(){console.warn('THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().');return this.getRenderTarget();},getMaxAnisotropy:function getMaxAnisotropy(){console.warn('THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().');return this.capabilities.getMaxAnisotropy();},getPrecision:function getPrecision(){console.warn('THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.');return this.capabilities.precision;},resetGLState:function resetGLState(){console.warn('THREE.WebGLRenderer: .resetGLState() is now .state.reset().');return this.state.reset();},supportsFloatTextures:function supportsFloatTextures(){console.warn('THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).');return this.extensions.get('OES_texture_float');},supportsHalfFloatTextures:function supportsHalfFloatTextures(){console.warn('THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).');return this.extensions.get('OES_texture_half_float');},supportsStandardDerivatives:function supportsStandardDerivatives(){console.warn('THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).');return this.extensions.get('OES_standard_derivatives');},supportsCompressedTextureS3TC:function supportsCompressedTextureS3TC(){console.warn('THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).');return this.extensions.get('WEBGL_compressed_texture_s3tc');},supportsCompressedTexturePVRTC:function supportsCompressedTexturePVRTC(){console.warn('THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).');return this.extensions.get('WEBGL_compressed_texture_pvrtc');},supportsBlendMinMax:function supportsBlendMinMax(){console.warn('THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).');return this.extensions.get('EXT_blend_minmax');},supportsVertexTextures:function supportsVertexTextures(){console.warn('THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.');return this.capabilities.vertexTextures;},supportsInstancedArrays:function supportsInstancedArrays(){console.warn('THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).');return this.extensions.get('ANGLE_instanced_arrays');},enableScissorTest:function enableScissorTest(boolean){console.warn('THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().');this.setScissorTest(boolean);},initMaterial:function initMaterial(){console.warn('THREE.WebGLRenderer: .initMaterial() has been removed.');},addPrePlugin:function addPrePlugin(){console.warn('THREE.WebGLRenderer: .addPrePlugin() has been removed.');},addPostPlugin:function addPostPlugin(){console.warn('THREE.WebGLRenderer: .addPostPlugin() has been removed.');},updateShadowMap:function updateShadowMap(){console.warn('THREE.WebGLRenderer: .updateShadowMap() has been removed.');},setFaceCulling:function setFaceCulling(){console.warn('THREE.WebGLRenderer: .setFaceCulling() has been removed.');},allocTextureUnit:function allocTextureUnit(){console.warn('THREE.WebGLRenderer: .allocTextureUnit() has been removed.');},setTexture:function setTexture(){console.warn('THREE.WebGLRenderer: .setTexture() has been removed.');},setTexture2D:function setTexture2D(){console.warn('THREE.WebGLRenderer: .setTexture2D() has been removed.');},setTextureCube:function setTextureCube(){console.warn('THREE.WebGLRenderer: .setTextureCube() has been removed.');},getActiveMipMapLevel:function getActiveMipMapLevel(){console.warn('THREE.WebGLRenderer: .getActiveMipMapLevel() is now .getActiveMipmapLevel().');return this.getActiveMipmapLevel();}});Object.defineProperties(WebGLRenderer.prototype,{shadowMapEnabled:{get:function get(){return this.shadowMap.enabled;},set:function set(value){console.warn('THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.');this.shadowMap.enabled=value;}},shadowMapType:{get:function get(){return this.shadowMap.type;},set:function set(value){console.warn('THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.');this.shadowMap.type=value;}},shadowMapCullFace:{get:function get(){console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');return undefined;},set:function set(/* value */){console.warn('THREE.WebGLRenderer: .shadowMapCullFace has been removed. Set Material.shadowSide instead.');}},context:{get:function get(){console.warn('THREE.WebGLRenderer: .context has been removed. Use .getContext() instead.');return this.getContext();}},vr:{get:function get(){console.warn('THREE.WebGLRenderer: .vr has been renamed to .xr');return this.xr;}},gammaInput:{get:function get(){console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');return false;},set:function set(){console.warn('THREE.WebGLRenderer: .gammaInput has been removed. Set the encoding for textures via Texture.encoding instead.');}},gammaOutput:{get:function get(){console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');return false;},set:function set(value){console.warn('THREE.WebGLRenderer: .gammaOutput has been removed. Set WebGLRenderer.outputEncoding instead.');this.outputEncoding=value===true?sRGBEncoding:LinearEncoding;}},toneMappingWhitePoint:{get:function get(){console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');return 1.0;},set:function set(){console.warn('THREE.WebGLRenderer: .toneMappingWhitePoint has been removed.');}}});Object.defineProperties(WebGLShadowMap.prototype,{cullFace:{get:function get(){console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');return undefined;},set:function set(/* cullFace */){console.warn('THREE.WebGLRenderer: .shadowMap.cullFace has been removed. Set Material.shadowSide instead.');}},renderReverseSided:{get:function get(){console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');return undefined;},set:function set(){console.warn('THREE.WebGLRenderer: .shadowMap.renderReverseSided has been removed. Set Material.shadowSide instead.');}},renderSingleSided:{get:function get(){console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');return undefined;},set:function set(){console.warn('THREE.WebGLRenderer: .shadowMap.renderSingleSided has been removed. Set Material.shadowSide instead.');}}});function WebGLRenderTargetCube(width,height,options){console.warn('THREE.WebGLRenderTargetCube( width, height, options ) is now WebGLCubeRenderTarget( size, options ).');return new WebGLCubeRenderTarget(width,options);}//
  5274. Object.defineProperties(WebGLRenderTarget.prototype,{wrapS:{get:function get(){console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');return this.texture.wrapS;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.');this.texture.wrapS=value;}},wrapT:{get:function get(){console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');return this.texture.wrapT;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.');this.texture.wrapT=value;}},magFilter:{get:function get(){console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');return this.texture.magFilter;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.');this.texture.magFilter=value;}},minFilter:{get:function get(){console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');return this.texture.minFilter;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.');this.texture.minFilter=value;}},anisotropy:{get:function get(){console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');return this.texture.anisotropy;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.');this.texture.anisotropy=value;}},offset:{get:function get(){console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');return this.texture.offset;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .offset is now .texture.offset.');this.texture.offset=value;}},repeat:{get:function get(){console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');return this.texture.repeat;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .repeat is now .texture.repeat.');this.texture.repeat=value;}},format:{get:function get(){console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');return this.texture.format;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .format is now .texture.format.');this.texture.format=value;}},type:{get:function get(){console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');return this.texture.type;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .type is now .texture.type.');this.texture.type=value;}},generateMipmaps:{get:function get(){console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');return this.texture.generateMipmaps;},set:function set(value){console.warn('THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.');this.texture.generateMipmaps=value;}}});//
  5275. Object.defineProperties(Audio.prototype,{load:{value:function value(file){console.warn('THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.');var scope=this;var audioLoader=new AudioLoader();audioLoader.load(file,function(buffer){scope.setBuffer(buffer);});return this;}},startTime:{set:function set(){console.warn('THREE.Audio: .startTime is now .play( delay ).');}}});AudioAnalyser.prototype.getData=function(){console.warn('THREE.AudioAnalyser: .getData() is now .getFrequencyData().');return this.getFrequencyData();};//
  5276. CubeCamera.prototype.updateCubeMap=function(renderer,scene){console.warn('THREE.CubeCamera: .updateCubeMap() is now .update().');return this.update(renderer,scene);};CubeCamera.prototype.clear=function(renderer,color,depth,stencil){console.warn('THREE.CubeCamera: .clear() is now .renderTarget.clear().');return this.renderTarget.clear(renderer,color,depth,stencil);};//
  5277. var GeometryUtils={merge:function merge(geometry1,geometry2,materialIndexOffset){console.warn('THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.');var matrix;if(geometry2.isMesh){geometry2.matrixAutoUpdate&&geometry2.updateMatrix();matrix=geometry2.matrix;geometry2=geometry2.geometry;}geometry1.merge(geometry2,matrix,materialIndexOffset);},center:function center(geometry){console.warn('THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.');return geometry.center();}};ImageUtils.crossOrigin=undefined;ImageUtils.loadTexture=function(url,mapping,onLoad,onError){console.warn('THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.');var loader=new TextureLoader();loader.setCrossOrigin(this.crossOrigin);var texture=loader.load(url,onLoad,undefined,onError);if(mapping)texture.mapping=mapping;return texture;};ImageUtils.loadTextureCube=function(urls,mapping,onLoad,onError){console.warn('THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.');var loader=new CubeTextureLoader();loader.setCrossOrigin(this.crossOrigin);var texture=loader.load(urls,onLoad,undefined,onError);if(mapping)texture.mapping=mapping;return texture;};ImageUtils.loadCompressedTexture=function(){console.error('THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.');};ImageUtils.loadCompressedTextureCube=function(){console.error('THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.');};//
  5278. function CanvasRenderer(){console.error('THREE.CanvasRenderer has been removed');}//
  5279. function JSONLoader(){console.error('THREE.JSONLoader has been removed.');}//
  5280. var SceneUtils={createMultiMaterialObject:function createMultiMaterialObject(/* geometry, materials */){console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');},detach:function detach(/* child, parent, scene */){console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');},attach:function attach(/* child, scene, parent */){console.error('THREE.SceneUtils has been moved to /examples/jsm/utils/SceneUtils.js');}};//
  5281. function LensFlare(){console.error('THREE.LensFlare has been moved to /examples/jsm/objects/Lensflare.js');}if(typeof __THREE_DEVTOOLS__!=='undefined'){/* eslint-disable no-undef */__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent('register',{detail:{revision:REVISION}}));/* eslint-enable no-undef */}
  5282. var THREE$1 = /*#__PURE__*/Object.freeze({
  5283. __proto__: null,
  5284. ACESFilmicToneMapping: ACESFilmicToneMapping,
  5285. AddEquation: AddEquation,
  5286. AddOperation: AddOperation,
  5287. AdditiveAnimationBlendMode: AdditiveAnimationBlendMode,
  5288. AdditiveBlending: AdditiveBlending,
  5289. AlphaFormat: AlphaFormat,
  5290. AlwaysDepth: AlwaysDepth,
  5291. AlwaysStencilFunc: AlwaysStencilFunc,
  5292. AmbientLight: AmbientLight,
  5293. AmbientLightProbe: AmbientLightProbe,
  5294. AnimationClip: AnimationClip,
  5295. AnimationLoader: AnimationLoader,
  5296. AnimationMixer: AnimationMixer,
  5297. AnimationObjectGroup: AnimationObjectGroup,
  5298. AnimationUtils: AnimationUtils,
  5299. ArcCurve: ArcCurve,
  5300. ArrayCamera: ArrayCamera,
  5301. ArrowHelper: ArrowHelper,
  5302. Audio: Audio,
  5303. AudioAnalyser: AudioAnalyser,
  5304. AudioContext: AudioContext,
  5305. AudioListener: AudioListener,
  5306. AudioLoader: AudioLoader,
  5307. AxesHelper: AxesHelper,
  5308. AxisHelper: AxisHelper,
  5309. BackSide: BackSide,
  5310. BasicDepthPacking: BasicDepthPacking,
  5311. BasicShadowMap: BasicShadowMap,
  5312. BinaryTextureLoader: BinaryTextureLoader,
  5313. Bone: Bone,
  5314. BooleanKeyframeTrack: BooleanKeyframeTrack,
  5315. BoundingBoxHelper: BoundingBoxHelper,
  5316. Box2: Box2,
  5317. Box3: Box3,
  5318. Box3Helper: Box3Helper,
  5319. BoxBufferGeometry: BoxBufferGeometry,
  5320. BoxGeometry: BoxGeometry,
  5321. BoxHelper: BoxHelper,
  5322. BufferAttribute: BufferAttribute,
  5323. BufferGeometry: BufferGeometry,
  5324. BufferGeometryLoader: BufferGeometryLoader,
  5325. ByteType: ByteType,
  5326. Cache: Cache,
  5327. Camera: Camera,
  5328. CameraHelper: CameraHelper,
  5329. CanvasRenderer: CanvasRenderer,
  5330. CanvasTexture: CanvasTexture,
  5331. CatmullRomCurve3: CatmullRomCurve3,
  5332. CineonToneMapping: CineonToneMapping,
  5333. CircleBufferGeometry: CircleBufferGeometry,
  5334. CircleGeometry: CircleGeometry,
  5335. ClampToEdgeWrapping: ClampToEdgeWrapping,
  5336. Clock: Clock,
  5337. ClosedSplineCurve3: ClosedSplineCurve3,
  5338. Color: Color,
  5339. ColorKeyframeTrack: ColorKeyframeTrack,
  5340. CompressedTexture: CompressedTexture,
  5341. CompressedTextureLoader: CompressedTextureLoader,
  5342. ConeBufferGeometry: ConeBufferGeometry,
  5343. ConeGeometry: ConeGeometry,
  5344. CubeCamera: CubeCamera,
  5345. CubeGeometry: BoxGeometry,
  5346. CubeReflectionMapping: CubeReflectionMapping,
  5347. CubeRefractionMapping: CubeRefractionMapping,
  5348. CubeTexture: CubeTexture,
  5349. CubeTextureLoader: CubeTextureLoader,
  5350. CubeUVReflectionMapping: CubeUVReflectionMapping,
  5351. CubeUVRefractionMapping: CubeUVRefractionMapping,
  5352. CubicBezierCurve: CubicBezierCurve,
  5353. CubicBezierCurve3: CubicBezierCurve3,
  5354. CubicInterpolant: CubicInterpolant,
  5355. CullFaceBack: CullFaceBack,
  5356. CullFaceFront: CullFaceFront,
  5357. CullFaceFrontBack: CullFaceFrontBack,
  5358. CullFaceNone: CullFaceNone,
  5359. Curve: Curve,
  5360. CurvePath: CurvePath,
  5361. CustomBlending: CustomBlending,
  5362. CustomToneMapping: CustomToneMapping,
  5363. CylinderBufferGeometry: CylinderBufferGeometry,
  5364. CylinderGeometry: CylinderGeometry,
  5365. Cylindrical: Cylindrical,
  5366. DataTexture: DataTexture,
  5367. DataTexture2DArray: DataTexture2DArray,
  5368. DataTexture3D: DataTexture3D,
  5369. DataTextureLoader: DataTextureLoader,
  5370. DataUtils: DataUtils,
  5371. DecrementStencilOp: DecrementStencilOp,
  5372. DecrementWrapStencilOp: DecrementWrapStencilOp,
  5373. DefaultLoadingManager: DefaultLoadingManager,
  5374. DepthFormat: DepthFormat,
  5375. DepthStencilFormat: DepthStencilFormat,
  5376. DepthTexture: DepthTexture,
  5377. DirectionalLight: DirectionalLight,
  5378. DirectionalLightHelper: DirectionalLightHelper,
  5379. DiscreteInterpolant: DiscreteInterpolant,
  5380. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  5381. DodecahedronGeometry: DodecahedronGeometry,
  5382. DoubleSide: DoubleSide,
  5383. DstAlphaFactor: DstAlphaFactor,
  5384. DstColorFactor: DstColorFactor,
  5385. DynamicBufferAttribute: DynamicBufferAttribute,
  5386. DynamicCopyUsage: DynamicCopyUsage,
  5387. DynamicDrawUsage: DynamicDrawUsage,
  5388. DynamicReadUsage: DynamicReadUsage,
  5389. EdgesGeometry: EdgesGeometry,
  5390. EdgesHelper: EdgesHelper,
  5391. EllipseCurve: EllipseCurve,
  5392. EqualDepth: EqualDepth,
  5393. EqualStencilFunc: EqualStencilFunc,
  5394. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  5395. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  5396. Euler: Euler,
  5397. EventDispatcher: EventDispatcher,
  5398. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  5399. ExtrudeGeometry: ExtrudeGeometry,
  5400. Face3: Face3,
  5401. Face4: Face4,
  5402. FaceColors: FaceColors,
  5403. FileLoader: FileLoader,
  5404. FlatShading: FlatShading$1,
  5405. Float16BufferAttribute: Float16BufferAttribute,
  5406. Float32Attribute: Float32Attribute,
  5407. Float32BufferAttribute: Float32BufferAttribute,
  5408. Float64Attribute: Float64Attribute,
  5409. Float64BufferAttribute: Float64BufferAttribute,
  5410. FloatType: FloatType,
  5411. Fog: Fog,
  5412. FogExp2: FogExp2,
  5413. Font: Font,
  5414. FontLoader: FontLoader,
  5415. FrontSide: FrontSide,
  5416. Frustum: Frustum,
  5417. GLBufferAttribute: GLBufferAttribute,
  5418. GLSL1: GLSL1,
  5419. GLSL3: GLSL3,
  5420. GammaEncoding: GammaEncoding,
  5421. Geometry: Geometry,
  5422. GeometryUtils: GeometryUtils,
  5423. GreaterDepth: GreaterDepth,
  5424. GreaterEqualDepth: GreaterEqualDepth,
  5425. GreaterEqualStencilFunc: GreaterEqualStencilFunc,
  5426. GreaterStencilFunc: GreaterStencilFunc,
  5427. GridHelper: GridHelper,
  5428. Group: Group,
  5429. HalfFloatType: HalfFloatType,
  5430. HemisphereLight: HemisphereLight,
  5431. HemisphereLightHelper: HemisphereLightHelper,
  5432. HemisphereLightProbe: HemisphereLightProbe,
  5433. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  5434. IcosahedronGeometry: IcosahedronGeometry,
  5435. ImageBitmapLoader: ImageBitmapLoader,
  5436. ImageLoader: ImageLoader,
  5437. ImageUtils: ImageUtils,
  5438. ImmediateRenderObject: ImmediateRenderObject,
  5439. IncrementStencilOp: IncrementStencilOp,
  5440. IncrementWrapStencilOp: IncrementWrapStencilOp,
  5441. InstancedBufferAttribute: InstancedBufferAttribute,
  5442. InstancedBufferGeometry: InstancedBufferGeometry,
  5443. InstancedInterleavedBuffer: InstancedInterleavedBuffer,
  5444. InstancedMesh: InstancedMesh,
  5445. Int16Attribute: Int16Attribute,
  5446. Int16BufferAttribute: Int16BufferAttribute,
  5447. Int32Attribute: Int32Attribute,
  5448. Int32BufferAttribute: Int32BufferAttribute,
  5449. Int8Attribute: Int8Attribute,
  5450. Int8BufferAttribute: Int8BufferAttribute,
  5451. IntType: IntType,
  5452. InterleavedBuffer: InterleavedBuffer,
  5453. InterleavedBufferAttribute: InterleavedBufferAttribute,
  5454. Interpolant: Interpolant,
  5455. InterpolateDiscrete: InterpolateDiscrete,
  5456. InterpolateLinear: InterpolateLinear,
  5457. InterpolateSmooth: InterpolateSmooth,
  5458. InvertStencilOp: InvertStencilOp,
  5459. JSONLoader: JSONLoader,
  5460. KeepStencilOp: KeepStencilOp,
  5461. KeyframeTrack: KeyframeTrack,
  5462. LOD: LOD,
  5463. LatheBufferGeometry: LatheBufferGeometry,
  5464. LatheGeometry: LatheGeometry,
  5465. Layers: Layers,
  5466. LensFlare: LensFlare,
  5467. LessDepth: LessDepth,
  5468. LessEqualDepth: LessEqualDepth,
  5469. LessEqualStencilFunc: LessEqualStencilFunc,
  5470. LessStencilFunc: LessStencilFunc,
  5471. Light: Light,
  5472. LightProbe: LightProbe,
  5473. Line: Line,
  5474. Line3: Line3,
  5475. LineBasicMaterial: LineBasicMaterial,
  5476. LineCurve: LineCurve,
  5477. LineCurve3: LineCurve3,
  5478. LineDashedMaterial: LineDashedMaterial,
  5479. LineLoop: LineLoop,
  5480. LinePieces: LinePieces,
  5481. LineSegments: LineSegments,
  5482. LineStrip: LineStrip,
  5483. LinearEncoding: LinearEncoding,
  5484. LinearFilter: LinearFilter,
  5485. LinearInterpolant: LinearInterpolant,
  5486. LinearMipMapLinearFilter: LinearMipMapLinearFilter,
  5487. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  5488. LinearMipmapLinearFilter: LinearMipmapLinearFilter,
  5489. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  5490. LinearToneMapping: LinearToneMapping,
  5491. Loader: Loader,
  5492. LoaderUtils: LoaderUtils,
  5493. LoadingManager: LoadingManager,
  5494. LogLuvEncoding: LogLuvEncoding,
  5495. LoopOnce: LoopOnce,
  5496. LoopPingPong: LoopPingPong,
  5497. LoopRepeat: LoopRepeat,
  5498. LuminanceAlphaFormat: LuminanceAlphaFormat,
  5499. LuminanceFormat: LuminanceFormat,
  5500. MOUSE: MOUSE,
  5501. Material: Material,
  5502. MaterialLoader: MaterialLoader,
  5503. Math: MathUtils,
  5504. MathUtils: MathUtils,
  5505. Matrix3: Matrix3,
  5506. Matrix4: Matrix4,
  5507. MaxEquation: MaxEquation,
  5508. Mesh: Mesh,
  5509. MeshBasicMaterial: MeshBasicMaterial,
  5510. MeshDepthMaterial: MeshDepthMaterial,
  5511. MeshDistanceMaterial: MeshDistanceMaterial,
  5512. MeshFaceMaterial: MeshFaceMaterial,
  5513. MeshLambertMaterial: MeshLambertMaterial,
  5514. MeshMatcapMaterial: MeshMatcapMaterial,
  5515. MeshNormalMaterial: MeshNormalMaterial,
  5516. MeshPhongMaterial: MeshPhongMaterial,
  5517. MeshPhysicalMaterial: MeshPhysicalMaterial,
  5518. MeshStandardMaterial: MeshStandardMaterial,
  5519. MeshToonMaterial: MeshToonMaterial,
  5520. MinEquation: MinEquation,
  5521. MirroredRepeatWrapping: MirroredRepeatWrapping,
  5522. MixOperation: MixOperation,
  5523. MultiMaterial: MultiMaterial,
  5524. MultiplyBlending: MultiplyBlending,
  5525. MultiplyOperation: MultiplyOperation,
  5526. NearestFilter: NearestFilter,
  5527. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  5528. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  5529. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  5530. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  5531. NeverDepth: NeverDepth,
  5532. NeverStencilFunc: NeverStencilFunc,
  5533. NoBlending: NoBlending,
  5534. NoColors: NoColors,
  5535. NoToneMapping: NoToneMapping,
  5536. NormalAnimationBlendMode: NormalAnimationBlendMode,
  5537. NormalBlending: NormalBlending,
  5538. NotEqualDepth: NotEqualDepth,
  5539. NotEqualStencilFunc: NotEqualStencilFunc,
  5540. NumberKeyframeTrack: NumberKeyframeTrack,
  5541. Object3D: Object3D,
  5542. ObjectLoader: ObjectLoader,
  5543. ObjectSpaceNormalMap: ObjectSpaceNormalMap,
  5544. OctahedronBufferGeometry: OctahedronBufferGeometry,
  5545. OctahedronGeometry: OctahedronGeometry,
  5546. OneFactor: OneFactor,
  5547. OneMinusDstAlphaFactor: OneMinusDstAlphaFactor,
  5548. OneMinusDstColorFactor: OneMinusDstColorFactor,
  5549. OneMinusSrcAlphaFactor: OneMinusSrcAlphaFactor,
  5550. OneMinusSrcColorFactor: OneMinusSrcColorFactor,
  5551. OrthographicCamera: OrthographicCamera,
  5552. PCFShadowMap: PCFShadowMap,
  5553. PCFSoftShadowMap: PCFSoftShadowMap,
  5554. PMREMGenerator: PMREMGenerator,
  5555. ParametricBufferGeometry: ParametricBufferGeometry,
  5556. ParametricGeometry: ParametricGeometry,
  5557. Particle: Particle,
  5558. ParticleBasicMaterial: ParticleBasicMaterial,
  5559. ParticleSystem: ParticleSystem,
  5560. ParticleSystemMaterial: ParticleSystemMaterial,
  5561. Path: Path,
  5562. PerspectiveCamera: PerspectiveCamera,
  5563. Plane: Plane,
  5564. PlaneBufferGeometry: PlaneBufferGeometry,
  5565. PlaneGeometry: PlaneGeometry,
  5566. PlaneHelper: PlaneHelper,
  5567. PointCloud: PointCloud,
  5568. PointCloudMaterial: PointCloudMaterial,
  5569. PointLight: PointLight,
  5570. PointLightHelper: PointLightHelper,
  5571. Points: Points,
  5572. PointsMaterial: PointsMaterial,
  5573. PolarGridHelper: PolarGridHelper,
  5574. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  5575. PolyhedronGeometry: PolyhedronGeometry,
  5576. PositionalAudio: PositionalAudio,
  5577. PropertyBinding: PropertyBinding,
  5578. PropertyMixer: PropertyMixer,
  5579. QuadraticBezierCurve: QuadraticBezierCurve,
  5580. QuadraticBezierCurve3: QuadraticBezierCurve3,
  5581. Quaternion: Quaternion,
  5582. QuaternionKeyframeTrack: QuaternionKeyframeTrack,
  5583. QuaternionLinearInterpolant: QuaternionLinearInterpolant,
  5584. REVISION: REVISION,
  5585. RGBADepthPacking: RGBADepthPacking,
  5586. RGBAFormat: RGBAFormat,
  5587. RGBAIntegerFormat: RGBAIntegerFormat,
  5588. RGBA_ASTC_10x10_Format: RGBA_ASTC_10x10_Format,
  5589. RGBA_ASTC_10x5_Format: RGBA_ASTC_10x5_Format,
  5590. RGBA_ASTC_10x6_Format: RGBA_ASTC_10x6_Format,
  5591. RGBA_ASTC_10x8_Format: RGBA_ASTC_10x8_Format,
  5592. RGBA_ASTC_12x10_Format: RGBA_ASTC_12x10_Format,
  5593. RGBA_ASTC_12x12_Format: RGBA_ASTC_12x12_Format,
  5594. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  5595. RGBA_ASTC_5x4_Format: RGBA_ASTC_5x4_Format,
  5596. RGBA_ASTC_5x5_Format: RGBA_ASTC_5x5_Format,
  5597. RGBA_ASTC_6x5_Format: RGBA_ASTC_6x5_Format,
  5598. RGBA_ASTC_6x6_Format: RGBA_ASTC_6x6_Format,
  5599. RGBA_ASTC_8x5_Format: RGBA_ASTC_8x5_Format,
  5600. RGBA_ASTC_8x6_Format: RGBA_ASTC_8x6_Format,
  5601. RGBA_ASTC_8x8_Format: RGBA_ASTC_8x8_Format,
  5602. RGBA_BPTC_Format: RGBA_BPTC_Format,
  5603. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  5604. RGBA_PVRTC_2BPPV1_Format: RGBA_PVRTC_2BPPV1_Format,
  5605. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  5606. RGBA_S3TC_DXT1_Format: RGBA_S3TC_DXT1_Format$1,
  5607. RGBA_S3TC_DXT3_Format: RGBA_S3TC_DXT3_Format,
  5608. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  5609. RGBDEncoding: RGBDEncoding,
  5610. RGBEEncoding: RGBEEncoding,
  5611. RGBEFormat: RGBEFormat,
  5612. RGBFormat: RGBFormat,
  5613. RGBIntegerFormat: RGBIntegerFormat,
  5614. RGBM16Encoding: RGBM16Encoding,
  5615. RGBM7Encoding: RGBM7Encoding,
  5616. RGB_ETC1_Format: RGB_ETC1_Format,
  5617. RGB_ETC2_Format: RGB_ETC2_Format,
  5618. RGB_PVRTC_2BPPV1_Format: RGB_PVRTC_2BPPV1_Format,
  5619. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  5620. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format,
  5621. RGFormat: RGFormat,
  5622. RGIntegerFormat: RGIntegerFormat,
  5623. RawShaderMaterial: RawShaderMaterial,
  5624. Ray: Ray,
  5625. Raycaster: Raycaster,
  5626. RectAreaLight: RectAreaLight,
  5627. RedFormat: RedFormat,
  5628. RedIntegerFormat: RedIntegerFormat,
  5629. ReinhardToneMapping: ReinhardToneMapping,
  5630. RepeatWrapping: RepeatWrapping,
  5631. ReplaceStencilOp: ReplaceStencilOp,
  5632. ReverseSubtractEquation: ReverseSubtractEquation,
  5633. RingBufferGeometry: RingBufferGeometry,
  5634. RingGeometry: RingGeometry,
  5635. SRGB8_ALPHA8_ASTC_10x10_Format: SRGB8_ALPHA8_ASTC_10x10_Format,
  5636. SRGB8_ALPHA8_ASTC_10x5_Format: SRGB8_ALPHA8_ASTC_10x5_Format,
  5637. SRGB8_ALPHA8_ASTC_10x6_Format: SRGB8_ALPHA8_ASTC_10x6_Format,
  5638. SRGB8_ALPHA8_ASTC_10x8_Format: SRGB8_ALPHA8_ASTC_10x8_Format,
  5639. SRGB8_ALPHA8_ASTC_12x10_Format: SRGB8_ALPHA8_ASTC_12x10_Format,
  5640. SRGB8_ALPHA8_ASTC_12x12_Format: SRGB8_ALPHA8_ASTC_12x12_Format,
  5641. SRGB8_ALPHA8_ASTC_4x4_Format: SRGB8_ALPHA8_ASTC_4x4_Format,
  5642. SRGB8_ALPHA8_ASTC_5x4_Format: SRGB8_ALPHA8_ASTC_5x4_Format,
  5643. SRGB8_ALPHA8_ASTC_5x5_Format: SRGB8_ALPHA8_ASTC_5x5_Format,
  5644. SRGB8_ALPHA8_ASTC_6x5_Format: SRGB8_ALPHA8_ASTC_6x5_Format,
  5645. SRGB8_ALPHA8_ASTC_6x6_Format: SRGB8_ALPHA8_ASTC_6x6_Format,
  5646. SRGB8_ALPHA8_ASTC_8x5_Format: SRGB8_ALPHA8_ASTC_8x5_Format,
  5647. SRGB8_ALPHA8_ASTC_8x6_Format: SRGB8_ALPHA8_ASTC_8x6_Format,
  5648. SRGB8_ALPHA8_ASTC_8x8_Format: SRGB8_ALPHA8_ASTC_8x8_Format,
  5649. Scene: Scene,
  5650. SceneUtils: SceneUtils,
  5651. ShaderChunk: ShaderChunk,
  5652. ShaderLib: ShaderLib,
  5653. ShaderMaterial: ShaderMaterial,
  5654. ShadowMaterial: ShadowMaterial,
  5655. Shape: Shape,
  5656. ShapeBufferGeometry: ShapeBufferGeometry,
  5657. ShapeGeometry: ShapeGeometry,
  5658. ShapePath: ShapePath,
  5659. ShapeUtils: ShapeUtils,
  5660. ShortType: ShortType,
  5661. Skeleton: Skeleton,
  5662. SkeletonHelper: SkeletonHelper,
  5663. SkinnedMesh: SkinnedMesh,
  5664. SmoothShading: SmoothShading,
  5665. Sphere: Sphere,
  5666. SphereBufferGeometry: SphereBufferGeometry,
  5667. SphereGeometry: SphereGeometry,
  5668. Spherical: Spherical,
  5669. SphericalHarmonics3: SphericalHarmonics3,
  5670. Spline: Spline,
  5671. SplineCurve: SplineCurve,
  5672. SplineCurve3: SplineCurve3,
  5673. SpotLight: SpotLight,
  5674. SpotLightHelper: SpotLightHelper,
  5675. Sprite: Sprite$1,
  5676. SpriteMaterial: SpriteMaterial,
  5677. SrcAlphaFactor: SrcAlphaFactor,
  5678. SrcAlphaSaturateFactor: SrcAlphaSaturateFactor,
  5679. SrcColorFactor: SrcColorFactor,
  5680. StaticCopyUsage: StaticCopyUsage,
  5681. StaticDrawUsage: StaticDrawUsage,
  5682. StaticReadUsage: StaticReadUsage,
  5683. StereoCamera: StereoCamera,
  5684. StreamCopyUsage: StreamCopyUsage,
  5685. StreamDrawUsage: StreamDrawUsage,
  5686. StreamReadUsage: StreamReadUsage,
  5687. StringKeyframeTrack: StringKeyframeTrack,
  5688. SubtractEquation: SubtractEquation,
  5689. SubtractiveBlending: SubtractiveBlending,
  5690. TOUCH: TOUCH,
  5691. TangentSpaceNormalMap: TangentSpaceNormalMap,
  5692. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  5693. TetrahedronGeometry: TetrahedronGeometry,
  5694. TextBufferGeometry: TextBufferGeometry,
  5695. TextGeometry: TextGeometry,
  5696. Texture: Texture,
  5697. TextureLoader: TextureLoader,
  5698. TorusBufferGeometry: TorusBufferGeometry,
  5699. TorusGeometry: TorusGeometry,
  5700. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  5701. TorusKnotGeometry: TorusKnotGeometry,
  5702. Triangle: Triangle,
  5703. TriangleFanDrawMode: TriangleFanDrawMode,
  5704. TriangleStripDrawMode: TriangleStripDrawMode,
  5705. TrianglesDrawMode: TrianglesDrawMode,
  5706. TubeBufferGeometry: TubeBufferGeometry,
  5707. TubeGeometry: TubeGeometry,
  5708. UVMapping: UVMapping,
  5709. Uint16Attribute: Uint16Attribute,
  5710. Uint16BufferAttribute: Uint16BufferAttribute,
  5711. Uint32Attribute: Uint32Attribute,
  5712. Uint32BufferAttribute: Uint32BufferAttribute,
  5713. Uint8Attribute: Uint8Attribute,
  5714. Uint8BufferAttribute: Uint8BufferAttribute,
  5715. Uint8ClampedAttribute: Uint8ClampedAttribute,
  5716. Uint8ClampedBufferAttribute: Uint8ClampedBufferAttribute,
  5717. Uniform: Uniform,
  5718. UniformsLib: UniformsLib,
  5719. UniformsUtils: UniformsUtils,
  5720. UnsignedByteType: UnsignedByteType,
  5721. UnsignedInt248Type: UnsignedInt248Type$1,
  5722. UnsignedIntType: UnsignedIntType,
  5723. UnsignedShort4444Type: UnsignedShort4444Type,
  5724. UnsignedShort5551Type: UnsignedShort5551Type,
  5725. UnsignedShort565Type: UnsignedShort565Type,
  5726. UnsignedShortType: UnsignedShortType,
  5727. VSMShadowMap: VSMShadowMap,
  5728. Vector2: Vector2,
  5729. Vector3: Vector3,
  5730. Vector4: Vector4,
  5731. VectorKeyframeTrack: VectorKeyframeTrack,
  5732. Vertex: Vertex,
  5733. VertexColors: VertexColors,
  5734. VideoTexture: VideoTexture,
  5735. WebGL1Renderer: WebGL1Renderer,
  5736. WebGLCubeRenderTarget: WebGLCubeRenderTarget,
  5737. WebGLMultisampleRenderTarget: WebGLMultisampleRenderTarget,
  5738. WebGLRenderTarget: WebGLRenderTarget,
  5739. WebGLRenderTargetCube: WebGLRenderTargetCube,
  5740. WebGLRenderer: WebGLRenderer,
  5741. WebGLUtils: WebGLUtils,
  5742. WireframeGeometry: WireframeGeometry,
  5743. WireframeHelper: WireframeHelper,
  5744. WrapAroundEnding: WrapAroundEnding,
  5745. XHRLoader: XHRLoader,
  5746. ZeroCurvatureEnding: ZeroCurvatureEnding,
  5747. ZeroFactor: ZeroFactor,
  5748. ZeroSlopeEnding: ZeroSlopeEnding,
  5749. ZeroStencilOp: ZeroStencilOp,
  5750. sRGBEncoding: sRGBEncoding
  5751. });
  5752. var points = [];
  5753. var lines = [];
  5754. var rings = [];
  5755. var precision = 0.1; //容错精度 //正常是0.01 但是在编辑时容易出现交错的线看不出来,导致需要getSliceLines 然后多出新增点
  5756. var getPoint = function getPoint(o, type) {
  5757. var point;
  5758. if (typeof o == "string" || typeof o == "number") point = points.find(p => p.ids.includes(o));else {
  5759. point = points.find(p => math.closeTo(p.x, o.x, precision) && math.closeTo(p.y, o.y, precision));
  5760. if (!point) point = new Point(o.x, o.y, {
  5761. record: true,
  5762. id: o.id
  5763. }, type);else {
  5764. //console.log('addPoint', point, o)
  5765. point.addPoint(o.id);
  5766. }
  5767. }
  5768. if (!point) {
  5769. console.log("no point!");
  5770. }
  5771. return point;
  5772. };
  5773. var getLine = function getLine(id) {
  5774. return lines.find(line => line.ids.includes(id));
  5775. };
  5776. var getAngleInfo = function getAngleInfo(points) {
  5777. var info = {};
  5778. info.angle = points[1].clone().sub(points[0]).angle();
  5779. if (math.closeTo(info.angle, Math.PI * 2)) {
  5780. //如360-0.01
  5781. info.angle -= Math.PI * 2; //有可能得到负数-0.001
  5782. } else if (info.angle > Math.PI || math.closeTo(info.angle, Math.PI)) {
  5783. //如180+-0.01
  5784. info.angle -= Math.PI;
  5785. info.reverse = true;
  5786. }
  5787. return info; //结果大约是 0 - 3.14
  5788. };
  5789. class Point extends Vector2 {
  5790. constructor(x, y) {
  5791. var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  5792. super(x, y);
  5793. if (o.record) {
  5794. this.id = o.id;
  5795. if (this.id == void 0) this.id = "add_" + points.length;
  5796. this.ids = [this.id]; //存储拥有该坐标的点原始数据的id
  5797. points.push(this);
  5798. }
  5799. this.type = o.type || "";
  5800. this.lines = [];
  5801. }
  5802. addPoint(id) {
  5803. this.ids.push(id);
  5804. }
  5805. searchLineByFactor(dir, type, comeLine) {
  5806. var lines = this.lines.filter(line => line.searchTime < 2);
  5807. if (lines.length == 0) return;else if (lines.length == 1) return lines[0];else lines = lines.filter(line => line != comeLine);
  5808. if (lines.length == 1) return lines[0];
  5809. var result;
  5810. lines.forEach(line => {
  5811. var vec = line.getVector();
  5812. if (line.points[1] == this) vec.negate();
  5813. var factor = math.getVec2Angle(dir, vec);
  5814. if (new Vector3(dir.x, dir.y, 0).cross(new Vector3(vec.x, vec.y, 0)).z < 0) factor *= -1; /////
  5815. if (!result) {
  5816. result = {
  5817. line,
  5818. factor
  5819. };
  5820. } else {
  5821. if (type == "min" && factor < result.factor || type == "max" && factor > result.factor) result = {
  5822. line,
  5823. factor
  5824. };
  5825. }
  5826. });
  5827. return result.line;
  5828. }
  5829. }
  5830. var lineLen = 0;
  5831. class Line$1 {
  5832. constructor(o) {
  5833. if (o.points[0] == o.points[1]) return;
  5834. this.points = o.points;
  5835. this.type = o.type || 'line';
  5836. if (this.type == 'line') {
  5837. var oldLine = lines.find(line => line.points.includes(o.points[0]) && line.points.includes(o.points[1]));
  5838. if (oldLine) {
  5839. o.id != void 0 && oldLine.ids.push(o.id);
  5840. return oldLine;
  5841. }
  5842. this.id = o.id == void 0 ? "line" + lineLen++ : o.id;
  5843. this.ids = [this.id];
  5844. o.dontWriteToPoint || this.points.forEach(point => {
  5845. point.lines.push(this);
  5846. });
  5847. o.isChild || lines.push(this);
  5848. this.searchTime = 0; // 最多两次
  5849. }
  5850. this.children = []; //分割
  5851. this.parents = []; //分割
  5852. this.match = [];
  5853. }
  5854. getAngleInfo() {
  5855. var angleInfo = getAngleInfo(this.points);
  5856. this.angle = angleInfo.angle;
  5857. this.reverse = angleInfo.reverse;
  5858. }
  5859. getIntersectWithLine(line, precision) {
  5860. var joint = line.points.find(point => this.points.includes(point));
  5861. if (joint) return {
  5862. point: joint,
  5863. type: "joint"
  5864. };
  5865. var intersect = math.isLineIntersect(line.points, this.points, false, precision);
  5866. if (intersect) return {
  5867. point: intersect,
  5868. type: "intersect"
  5869. };
  5870. }
  5871. writeToPoint() {
  5872. this.points.forEach(point => {
  5873. point.lines.includes(this) || point.lines.push(this);
  5874. });
  5875. }
  5876. checkIfParent(line) {
  5877. if (this == line) {
  5878. return true; //原因就是slice的点和端点很近 误差导致
  5879. } else return this.parents.find(e => e.checkIfParent(line));
  5880. }
  5881. splitByPoint(point) {
  5882. var line1 = new Line$1({
  5883. points: [point, this.points[0]],
  5884. dontWriteToPoint: true,
  5885. hasntsure: true
  5886. });
  5887. var line2 = new Line$1({
  5888. points: [point, this.points[1]],
  5889. dontWriteToPoint: true,
  5890. hasntsure: true
  5891. });
  5892. if (!line1.points || !line2.points) {
  5893. //有至少一个是点相同的,没写到group.lines里
  5894. console.warn('splitByPoint 线有点相同');
  5895. return;
  5896. }
  5897. if (this.checkIfParent(line1) || this.checkIfParent(line2) || line1.checkIfParent(this) || line2.checkIfParent(this)) {
  5898. console.warn("splitByPoint 发现parent和children一样"); //,请检查getSliceWalls,尤其 if(math.closeTo(line1.angle,line2.angle)){ 处
  5899. return;
  5900. }
  5901. var deal = line => {
  5902. this.children.push(line);
  5903. line.parents.push(this);
  5904. if (!lines.includes(line)) lines.push(line);
  5905. line.writeToPoint();
  5906. };
  5907. deal(line1);
  5908. deal(line2);
  5909. var index = this.points[0].lines.indexOf(this);
  5910. index > -1 && this.points[0].lines.splice(index, 1);
  5911. var index = this.points[1].lines.indexOf(this);
  5912. index > -1 && this.points[1].lines.splice(index, 1);
  5913. return [line1, line2];
  5914. }
  5915. splitByPoints(points) {
  5916. points = points.map(point => {
  5917. return {
  5918. dis: point.distanceTo(this.points[0]),
  5919. point: point
  5920. };
  5921. });
  5922. points.sort((point1, point2) => {
  5923. return point1.dis - point2.dis;
  5924. });
  5925. var children = [];
  5926. points.forEach((point, index) => {
  5927. var line1 = new Line$1({
  5928. points: [point.point, index == 0 ? this.points[0] : points[index - 1].point],
  5929. group: this.group,
  5930. dontWriteToPoint: true,
  5931. hasntsure: true
  5932. });
  5933. children.push(line1);
  5934. });
  5935. var line2 = new Line$1({
  5936. points: [points[points.length - 1].point, this.points[1]],
  5937. group: this.group,
  5938. dontWriteToPoint: true,
  5939. hasntsure: true
  5940. });
  5941. children.push(line2);
  5942. var a = children.find(line => !line.points || this.checkIfParent(line) || line.checkIfParent(this));
  5943. if (a) {
  5944. console.error("splitByPoints return");
  5945. return;
  5946. }
  5947. children.forEach(line => {
  5948. this.children.push(line);
  5949. line.parents.push(this);
  5950. if (!lines.includes(line)) lines.push(line);
  5951. line.writeToPoint();
  5952. line.writeToPoint();
  5953. });
  5954. var index = this.points[0].lines.indexOf(this);
  5955. index > -1 && this.points[0].lines.splice(index, 1);
  5956. var index = this.points[1].lines.indexOf(this);
  5957. index > -1 && this.points[1].lines.splice(index, 1);
  5958. }
  5959. getAllSlices() {
  5960. //如果有被分割的片段 就返回片段,否则返回自身
  5961. var children = [];
  5962. var _traverse = function traverse(elem) {
  5963. if (elem.children.length == 0) children.push(elem);else elem.children.forEach(_traverse);
  5964. };
  5965. _traverse(this);
  5966. return children;
  5967. }
  5968. getVector() {
  5969. return this.points[1].clone().sub(this.points[0]);
  5970. }
  5971. getLength() {
  5972. return this.points[0].distanceTo(this.points[1]);
  5973. }
  5974. getCenter() {
  5975. return this.points[1].clone().add(this.points[0]).multiplyScalar(.5);
  5976. }
  5977. }
  5978. var getMixedSet = function getMixedSet(arr1, arr2) {
  5979. //交集
  5980. return arr1.filter(item => arr2.includes(item));
  5981. };
  5982. var getUnionSet = function getUnionSet(arr1, arr2) {
  5983. //并集
  5984. return arr1.concat(arr2.filter(item => !arr1.includes(item)));
  5985. };
  5986. var getDifferenceSet = function getDifferenceSet(arr1, arr2) {
  5987. //差集
  5988. var arr11 = arr1.filter(item => !arr2.includes(item));
  5989. var arr22 = arr2.filter(item => !arr1.includes(item));
  5990. return arr11.concat(arr22);
  5991. };
  5992. var getDifferenceSetMuti = function getDifferenceSetMuti(arr) {
  5993. //收集绝对没有重复的元素,也就是判断出现次数=1的
  5994. var set = [];
  5995. arr.forEach(arr1 => {
  5996. arr1.forEach(item => {
  5997. var index = set.indexOf(item);
  5998. if (index > -1) {
  5999. set.splice(index, 1);
  6000. } else {
  6001. set.push(item);
  6002. }
  6003. });
  6004. });
  6005. return set;
  6006. };
  6007. function DoorAtWhichLine(points, lines) {
  6008. var mid = points[0].clone().add(points[1]).multiplyScalar(0.5);
  6009. lines = lines.filter(line => math.ifPointAtLineBound(mid, line.points, precision));
  6010. if (lines.length == 0) return;
  6011. var result = {
  6012. line: null,
  6013. dis: Infinity
  6014. };
  6015. lines.forEach(line => {
  6016. var foot = math.getFootPoint(mid, line.points[0], line.points[1]);
  6017. var dis = foot.distanceTo(mid);
  6018. if (dis < result.dis) {
  6019. result.line = line;
  6020. result.dis = dis;
  6021. }
  6022. });
  6023. return result;
  6024. }
  6025. var ringLen = 0;
  6026. class Ring {
  6027. constructor(o) {
  6028. this.id = ringLen++;
  6029. this.type = o.type || 'normal';
  6030. this.points = o.points;
  6031. this.lines = o.lines;
  6032. rings.push(this);
  6033. this.child = []; //包含的环
  6034. this.parent = []; //被包含的环
  6035. this.smallNeibours = []; //相邻最小环(存在和它有一个以上的相同边的最小环)
  6036. var area = math.getArea(this.points);
  6037. this.area = Math.abs(area);
  6038. this.isClockwise = area < 0; //是否逆时针。一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  6039. }
  6040. }
  6041. var findLine = function findLine(p1, p2) {
  6042. return lines.find(line => line.points.includes(p1) && line.points.includes(p2));
  6043. };
  6044. var ifSamePart = function ifSamePart(checkPart, part) {
  6045. //checkPart中所包含的part片段是否和基准part的顺序一样(逆序也可以, 中间有其他数也可以,起始不同也行。比如 01234和204一样的)
  6046. var axis,
  6047. startIndex,
  6048. newCheckPart = [];
  6049. for (var j = 0, len1 = checkPart.length; j < len1; j++) {
  6050. //将checkPart中比part多的数除去,使两个数组中包含的数完全相同。
  6051. if (part.indexOf(checkPart[j]) > -1) newCheckPart.push(checkPart[j]);
  6052. }
  6053. for (var i = 0, len = part.length; i < len; i++) {
  6054. var index = newCheckPart.indexOf(part[i]);
  6055. if (index == -1) return false;
  6056. if (i == 0) startIndex = index; //标记第一个查找点对应的index
  6057. else if (i == 1) {
  6058. //标记查找顺序是正还是逆
  6059. axis = index - startIndex;
  6060. if (axis == len - 1) axis = -1; //刚好是首和尾
  6061. else if (axis == 1 - len) axis = 1;
  6062. if (axis != -1 && axis != 1) {
  6063. return false;
  6064. }
  6065. } else {
  6066. //判断是否是按顺序的
  6067. if (index != (startIndex + axis * i + len) % len) return false;
  6068. }
  6069. }
  6070. return {
  6071. sameAxis: axis > 0
  6072. }; //如果一样的话返回正逆是否相同
  6073. };
  6074. //或者判断是否有相同边(但是相同点是可以组成不同环)
  6075. var ifSameRing = function ifSameRing(ring1, ring2) {
  6076. //判断两个环是否相等。 除了可以逆向外顺序要对
  6077. if (ring1 instanceof Ring) ring1 = ring1.points;
  6078. if (ring2 instanceof Ring) ring2 = ring2.points;
  6079. if (ring1.length != ring2.length) return false;
  6080. if (ring1.lines && ring2.lines) {
  6081. if (getDifferenceSet(ring1.lines, ring2.lines).length == 0) return true; //差集个数为0
  6082. } else {
  6083. if (ifSamePart(ring1, ring2)) return true;
  6084. }
  6085. };
  6086. var _atWhichChildLine = function atWhichChildLine(point, line, precision) {
  6087. if (line.children.length == 0) {
  6088. //这里可能要放低精度 保证能找到
  6089. if (math.ifPointAtLineBound(point, line.points, precision)) return line;
  6090. } else {
  6091. for (var i = 0; i < line.children.length; i++) {
  6092. var at = _atWhichChildLine(point, line.children[i], precision);
  6093. if (at) return at;
  6094. }
  6095. }
  6096. };
  6097. function getSliceLines() {
  6098. var len = lines.length;
  6099. var _deal = function deal(line1, line2) {
  6100. if (line1 == line2) return;
  6101. if (line1.angle == void 0) line1.getAngleInfo();
  6102. if (line2.angle == void 0) line2.getAngleInfo();
  6103. var intersect = line1.getIntersectWithLine(line2, precision);
  6104. if (intersect) {
  6105. var point; //得到交点
  6106. if (intersect.type == "intersect") {
  6107. point = getPoint(intersect.point, "whenGetSliceLines");
  6108. var line1_ = _atWhichChildLine(point, line1);
  6109. var line2_ = _atWhichChildLine(point, line2);
  6110. //重合的情况还没考虑(平行)
  6111. if (!line1_) line1_ = _atWhichChildLine(point, line1, precision); //降低精度
  6112. if (!line1_) line1_ = _atWhichChildLine(point, line1, precision * 2); //降低精度
  6113. if (!line2_) line2_ = _atWhichChildLine(point, line2, precision);
  6114. if (!line2_) line2_ = _atWhichChildLine(point, line2, precision * 2); //降低精度
  6115. //拆分线条:
  6116. //如果还报错,找不到ChildLine,就直接返回吧 或者搞个循环 逐渐降低精度
  6117. if (!line1_ || !line2_) {
  6118. console.warn("atWhichChildLine仍旧找不到 :" + line1.id + ',' + line2.id + ", pointId: " + point.id);
  6119. line1_ || console.warn("找不到line1");
  6120. line2_ || console.warn("找不到line2");
  6121. return;
  6122. }
  6123. if (line1_.points.find(p => p == point) && line2_.points.find(p => p == point)) {//这个点是line1_、 line2_端点,不做处理
  6124. //console.log("joint型 "+point.id)
  6125. } else if (line1_.points.find(p => p == point)) {
  6126. //T型交叉
  6127. line2_.splitByPoint(point); //加入到母线中,之后还先用母线判断交点
  6128. //console.log("T型交叉1 "+point.id)
  6129. } else if (line2_.points.find(p => p == point)) {
  6130. //T型交叉
  6131. line1_.splitByPoint(point);
  6132. //console.log("T型交叉2 "+point.id)
  6133. } else {
  6134. //十字交叉
  6135. line1_.splitByPoint(point);
  6136. line2_.splitByPoint(point);
  6137. }
  6138. } else {
  6139. point = intersect.point; //交点是端点
  6140. if (math.closeTo(line1.angle, line2.angle)) {
  6141. //重合一部分
  6142. var children1 = line1.getAllSlices();
  6143. var children2 = line2.getAllSlices();
  6144. if (children1.length > 1 || children2.length > 1) {
  6145. //使用最小分割片段来比较
  6146. children1.forEach(child1 => {
  6147. children2.forEach(child2 => {
  6148. _deal(child1, child2);
  6149. });
  6150. });
  6151. return;
  6152. }
  6153. var anotherPoint1 = line1.points.find(point_ => point_ != point);
  6154. var anotherPoint2 = line2.points.find(point_ => point_ != point);
  6155. if (math.ifPointAtLineBound(anotherPoint1, line2.points)) {
  6156. line2.splitByPoint(anotherPoint1);
  6157. } else if (math.ifPointAtLineBound(anotherPoint2, line1.points)) {
  6158. line1.splitByPoint(anotherPoint2);
  6159. }
  6160. }
  6161. }
  6162. } else if (math.closeTo(line1.angle, line2.angle)) {
  6163. var vec1 = line1.getVector();
  6164. var vec = line1.points[0].clone().sub(line2.points[0]);
  6165. var cos = math.getVec2Cos(vec1, vec);
  6166. if (math.closeTo(cos, -1, 1e-4) || math.closeTo(cos, 1, 1e-4)) {
  6167. //共线
  6168. var children1 = line1.getAllSlices();
  6169. var children2 = line2.getAllSlices();
  6170. if (children1.length > 1 || children2.length > 1) {
  6171. //使用最小分割片段来比较
  6172. children1.forEach(child1 => {
  6173. children2.forEach(child2 => {
  6174. _deal(child1, child2);
  6175. });
  6176. });
  6177. return;
  6178. }
  6179. //判断是否重叠
  6180. var A = line1.points[0];
  6181. var C = line1.reverse == line2.reverse ? line2.points[0] : line2.points[1];
  6182. var B = line1.points[1];
  6183. var D = line1.reverse == line2.reverse ? line2.points[1] : line2.points[0];
  6184. var BC = C.clone().sub(B);
  6185. var AD = D.clone().sub(A);
  6186. if (BC.length() < AD.length()) {
  6187. var BA = A.clone().sub(B);
  6188. if (math.getVec2Angle(BC, BA) >= 1.57) return; //没有重叠部分
  6189. } else {
  6190. var AB = B.clone().sub(A);
  6191. if (math.getVec2Angle(AD, AB) >= 1.57) return;
  6192. }
  6193. var f = function f(line1, line2) {
  6194. var one = math.ifPointAtLineBound(line1.points[0], line2.points);
  6195. var two = math.ifPointAtLineBound(line1.points[1], line2.points);
  6196. if (one && two) {
  6197. //line1在line2上
  6198. line2.splitByPoints(line1.points);
  6199. return true;
  6200. } else if (one || two) {
  6201. //错开
  6202. var point1 = one ? line1.points[0] : line1.points[1];
  6203. var anotherPoint1 = one ? line1.points[1] : line1.points[0];
  6204. var dis1 = line2.points[0].distanceTo(anotherPoint1);
  6205. var dis2 = line2.points[1].distanceTo(anotherPoint1);
  6206. var point2 = dis1 < dis2 ? line2.points[0] : line2.points[1];
  6207. line1.splitByPoint(point2);
  6208. line2.splitByPoint(point1);
  6209. return true;
  6210. }
  6211. };
  6212. f(line1, line2) || f(line2, line1);
  6213. }
  6214. }
  6215. };
  6216. for (var i = 0; i < len; i++) {
  6217. var line1 = lines[i];
  6218. for (var j = i + 1; j < len; j++) {
  6219. var line2 = lines[j];
  6220. _deal(line1, line2);
  6221. }
  6222. }
  6223. //console.log("原有线条个数:"+len)
  6224. //lines = lines.filter((line)=>{return line.children.length == 0})
  6225. //console.log("现有线条个数:"+lines.length)
  6226. }
  6227. var bound = new Box2();
  6228. var build = function build(o) {
  6229. //融合了相近点
  6230. //根据bound 处理precision
  6231. o.points.forEach(p => {
  6232. bound.expandByPoint(new Vector2(p.x, p.y));
  6233. });
  6234. if (o.precision != void 0) {
  6235. precision = o.precision;
  6236. } else {
  6237. var boundSize = bound.getSize(new Vector2());
  6238. precision = MathUtils.clamp(Math.max(boundSize.x, boundSize.y) / 70, 0.2, 2);
  6239. }
  6240. o.points.forEach(point => getPoint(point)); //{x:..,y:..}
  6241. o.lines.forEach(line => {
  6242. //{p1:id1. p2:id2}
  6243. new Line$1({
  6244. points: [getPoint(line.p1), getPoint(line.p2)],
  6245. id: line.id
  6246. });
  6247. });
  6248. //注意:不能出现一条线的两个点坐标一致,否则寻路时方向出错。 所以手动融合下相近点。
  6249. };
  6250. var searchRings = function searchRings() {
  6251. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  6252. points = [];
  6253. lines = [];
  6254. rings = [];
  6255. lineLen = ringLen = 0;
  6256. o.points = o.points || [];
  6257. o.lines = o.lines || [];
  6258. build(o);
  6259. if (!o.dontSliceLines) {
  6260. getSliceLines();
  6261. }
  6262. //查找最小回路:
  6263. //参考: 引入方向因子的最小回路、最大回路搜索算法.pdf
  6264. //方法: 逆时针寻找(标记)最外层大环 -->从走过的点开始逆时针寻找最小环(直到所有可走的路被走过两次)-->逆时针寻找最外层大环(直到所有可走的路被走过两次)-->..
  6265. //其中找大环时选择方向因子最小的路, 而小环则相反(但只有开始第一条路是一样的, 都是选择最左边的点的因子最小的路)。
  6266. //标记方法: 每条线需要被搜索两次才算完毕。搜索完毕的线退出搜索。(依据:搜索完全部最小回路后 , 在无向图中删除搜索过 2 次的边及孤立节点得到退化图 , 恰好构成最大回路。)
  6267. var searchTime = 0;
  6268. var addRingJudgeCount = 0;
  6269. var addRingJudge = function addRingJudge(ring, lines, connectedLines, type) {
  6270. // 处理拣出的片段
  6271. addRingJudgeCount++;
  6272. //console.log("addRingJudge points("+ type+"):"+ ring.map(point=>point.id) )
  6273. if (o.onlyGetOutRing && type == "small") return;
  6274. if (type == "small" || o.onlyGetOutRing) {
  6275. //挑出回路:
  6276. var newRings = [];
  6277. while (ring.length) {
  6278. var road = [];
  6279. var turnBack = false;
  6280. for (var i = 0; i < ring.length; i++) {
  6281. if (road.includes(ring[i])) {
  6282. //如果走到方才的点,可能形成回路。 无论是不是回路都要摘去这段。
  6283. var index = road.indexOf(ring[i]);
  6284. var pointArr = ring.slice(index, i);
  6285. var linesArr = lines.slice(index, i);
  6286. ring.splice(index, i - index);
  6287. lines.splice(index, i - index);
  6288. if (pointArr.length > 2) {
  6289. // 如果只有两个数,代表原路返回, 如 1->2(->1)
  6290. if (!rings.find(ring_ => ifSameRing(pointArr, ring_))) newRings.push(new Ring({
  6291. points: pointArr,
  6292. lines: linesArr
  6293. }));
  6294. }
  6295. turnBack = true;
  6296. break;
  6297. } else {
  6298. road.push(ring[i]);
  6299. turnBack = false;
  6300. }
  6301. }
  6302. if (!turnBack) {
  6303. //没有重复的点,那么就直接处理整条。
  6304. if (ring.length > 2) {
  6305. // 如果只有两个数,代表原路返回, 如 1->2(->1)
  6306. if (!rings.find(ring_ => ifSameRing(ring, ring_))) newRings.push(new Ring({
  6307. points: ring,
  6308. lines
  6309. }));
  6310. }
  6311. break;
  6312. }
  6313. }
  6314. if (type != 'small') {
  6315. newRings.forEach(e => e.isOutRing = true);
  6316. }
  6317. //console.log(newRings)
  6318. } else {
  6319. return ring;
  6320. }
  6321. };
  6322. var _search = function search(point2d, comeRoad, type, connectedLines) {
  6323. searchTime++;
  6324. var goLine;
  6325. var direction;
  6326. if (type.includes("big")) {
  6327. if (!comeRoad) {
  6328. if (type.includes("Left")) {
  6329. //逆时针
  6330. direction = new Vector2(1, 0);
  6331. } else {
  6332. direction = new Vector2(-1, 0);
  6333. }
  6334. goLine = point2d.searchLineByFactor(direction, "min");
  6335. } else {
  6336. var lastPoint = comeRoad.points[comeRoad.points.length - 1];
  6337. direction = point2d.clone().sub(lastPoint);
  6338. goLine = point2d.searchLineByFactor(direction, "min", findLine(point2d, lastPoint));
  6339. }
  6340. } else {
  6341. if (!comeRoad) {
  6342. //似乎找最小环时,第一条线也是找最小的因子,这样才能保证逆时针(除非只有顺时针一条路)
  6343. direction = new Vector2(1, 0);
  6344. goLine = point2d.searchLineByFactor(direction, "min");
  6345. } else {
  6346. var lastPoint = comeRoad.points[comeRoad.points.length - 1];
  6347. direction = point2d.clone().sub(lastPoint);
  6348. goLine = point2d.searchLineByFactor(direction, "max", findLine(point2d, lastPoint));
  6349. }
  6350. }
  6351. if (!goLine) return;
  6352. goLine.searchTime++;
  6353. connectedLines.includes(goLine) || connectedLines.push(goLine);
  6354. var nextPoint = goLine.points.find(point => point2d != point);
  6355. //if( comeRoad && comeRoad.points[comeRoad.points.length - 1] == nextPoint ) return;//不能查找来时的方向(反方向)
  6356. //走不通就原路返回
  6357. var roadPoints = comeRoad ? comeRoad.points.concat([point2d]) : [point2d]; //每个分叉都能构成一条新的road
  6358. var roadLines = comeRoad ? comeRoad.lines.concat([goLine]) : [goLine];
  6359. //走到第一个点就算停止,这时候可能得到一个环、或者一段走了两遍的线、或者一条线上带了些环。
  6360. if (nextPoint == roadPoints[0]) return addRingJudge(roadPoints, roadLines, connectedLines, type); //形成环
  6361. else {
  6362. /* var len = roadPoints.indexOf(nextPoint);
  6363. if( len > -1){ //走到走过的路的某一点 构成这段路的回路
  6364. var points = roadPoints.slice(len, roadPoints.length);
  6365. var lines = roadLines.slice(len, roadPoints.length);
  6366. addRingJudge(points, lines)
  6367. }else{ */
  6368. return _search(nextPoint, {
  6369. lines: roadLines,
  6370. points: roadPoints
  6371. }, type, connectedLines); //继续寻路
  6372. //}
  6373. }
  6374. };
  6375. while (1) {
  6376. //搜寻一次大环
  6377. var connectedLines = []; //被搜寻过的且searchTime<2的线。一旦全部搜完就说明该连通区域搜寻完毕,继续查下一个连通区域。
  6378. var startPoint = null;
  6379. points.forEach(point => {
  6380. //找出x最小的点
  6381. if (!point.lines.find(line => line.searchTime < 2)) return;
  6382. if (!startPoint) startPoint = point;else if (point.x < startPoint.x) startPoint = point;
  6383. });
  6384. if (!startPoint) break; //说明全部找完
  6385. var ring = _search(startPoint, null, "bigLeft", connectedLines); //逆时针
  6386. //search(startPoint, null, "bigRight", connectedLines);//顺时针(为了防止最外层不是回路之前写了顺时针,但如果是回路就会走重复。后来发现只要逆时针即可,因为走完后剩下的可以再次找大环)
  6387. connectedLines = connectedLines.filter(line => line.searchTime < 2);
  6388. var _loop = function _loop() {
  6389. //目标是顺着connectedLines把所有连通的小环都找到
  6390. var points_ = []; //connectedLines中所有的点
  6391. connectedLines.forEach(line => line.points.forEach(point => {
  6392. if (!points_.includes(point)) points_.push(point);
  6393. }));
  6394. startPoint = null;
  6395. points_.forEach(point => {
  6396. //找出x最小的点
  6397. if (!point.lines.find(line => line.searchTime < 2)) return;
  6398. if (!startPoint) startPoint = point;else if (point.x < startPoint.x) startPoint = point;
  6399. });
  6400. if (!startPoint) return 1; // break
  6401. _search(startPoint, null, "small", connectedLines);
  6402. connectedLines = connectedLines.filter(line => line.searchTime < 2);
  6403. },
  6404. startPoint;
  6405. while (connectedLines.length > 0) {
  6406. if (_loop()) break;
  6407. }
  6408. }
  6409. /* if(o.onlyGetOutRing){
  6410. rings = rings.filter(e=>e.isOutRing)
  6411. } */
  6412. //console.log("searchTime "+searchTime + ", addRingJudgeCount " +addRingJudgeCount)
  6413. //找出所有的相邻关系,包括公共边
  6414. var len = rings.length;
  6415. for (var i = 0; i < len; i++) {
  6416. var ring1 = rings[i];
  6417. for (var j = i + 1; j < len; j++) {
  6418. var ring2 = rings[j];
  6419. var bothHasLines = getMixedSet(ring1.lines, ring2.lines);
  6420. if (bothHasLines.length) {
  6421. //ring1oíring2?àáú
  6422. ring1.smallNeibours.push(ring2);
  6423. ring2.smallNeibours.push(ring1);
  6424. } else {}
  6425. }
  6426. }
  6427. rings.forEach(ring1 => {
  6428. for (var _i = 0; _i < len; _i++) {
  6429. var ring2 = rings[_i];
  6430. if (ring1 == ring2 || ring1.smallNeibours.includes(ring2)) continue;
  6431. var inside = void 0;
  6432. for (var u = 0; u < ring1.points.length; u++) {
  6433. inside = math.isPointInArea(ring2.points, null, ring1.points[u]);
  6434. if (!inside) break;else if (inside && !inside.atLine) {
  6435. break;
  6436. }
  6437. }
  6438. if (inside) {
  6439. //只要其中一个点在ring2内,就说明ring1是内环
  6440. if (inside.atLine) {
  6441. //(还是会存在点全在线上的情况,这时候判断中心点)
  6442. var center = math.getCenterOfGravityPoint(ring1.points);
  6443. var inside1 = math.isPointInArea(ring2.points, null, center);
  6444. if (!inside1) {
  6445. continue;
  6446. }
  6447. }
  6448. ring2.child.push(ring1);
  6449. ring1.parent.push(ring2);
  6450. }
  6451. }
  6452. });
  6453. //去除非最小的ring 是否应该检测parent child?
  6454. /*
  6455. like this:
  6456. |———————————————————————|
  6457. |———|———————|———————| |
  6458. | | | | |
  6459. | |———————|———————| |
  6460. |———————————————————————|
  6461. */
  6462. var wiseRings = rings.filter(r => !r.isClockwise); //一般都是逆时针得到的,如果是顺时针,可能是贪吃蛇的情况,可能不是最小环,需要去掉。
  6463. if (wiseRings.length > 0) {
  6464. //console.log('%c存在非最小的ring! 进行处理:',"color:#00f");
  6465. wiseRings.forEach(ring => {
  6466. //(此案例验证出smallNeibours就是它的最小构成,可以再看看别的案例)
  6467. if (ring.smallNeibours.length > 0) {
  6468. //另:如果内部只有一个,说明它是最小环,不需要处理
  6469. var is = false;
  6470. var difference = getDifferenceSet(ring.lines, getDifferenceSetMuti(ring.smallNeibours.concat(ring.child).map(ring => ring.lines))); //获取所有smallNeibours和child的边中没有重复过的边(就是outline) 和该ring的线比较
  6471. is = difference.every(line => ring.child.find(r => r.lines.includes(line))); //多出的线只能是child中的线
  6472. if (is) {
  6473. console.log('%c删除非最小环 ring' + ring.id, "color:#00f");
  6474. console.log(ring);
  6475. rings.splice(rings.indexOf(ring), 1);
  6476. ring.child.forEach(c => {
  6477. var index = c.parent.indexOf(ring);
  6478. index > -1 && c.parent.splice(index, 1);
  6479. });
  6480. ring.parent.forEach(c => {
  6481. var index = c.child.indexOf(ring);
  6482. index > -1 && c.child.splice(index, 1);
  6483. });
  6484. ring.smallNeibours.forEach(c => {
  6485. var index = c.smallNeibours.indexOf(ring);
  6486. index > -1 && c.smallNeibours.splice(index, 1);
  6487. });
  6488. }
  6489. }
  6490. });
  6491. }
  6492. /* rings = rings.filter(ring=>{
  6493. rings = rings.filter(ring=>{
  6494. var enoughSize = ring.area > 0.5
  6495. if(!enoughSize){console.log('因面积过小去除ring '+ring.id + " , area: "+ring.area)}
  6496. return enoughSize
  6497. })
  6498. rings.forEach(ring=>{
  6499. if(ring.closetChilds){
  6500. ring.closetChilds = ring.closetChilds.filter(e=>rings.includes(e))
  6501. }
  6502. })
  6503. return rings
  6504. }) */ //在dealRings前不能随意删除rings,因为判断是否是最小环时需要全部的环
  6505. rings.forEach(ring => {
  6506. //这里和cad中的不太一样, cad中双数个parent算外环,单数内环; 这里不分内外, 只看有无parent child
  6507. if (ring.parent.length) {
  6508. ring.closetParent = ring.parent.find(ring_ => ring_.parent.length == ring.parent.length - 1); //最近一层的大环就是比它的parent个数少一的
  6509. ring.closetParent.closetChilds || (ring.closetParent.closetChilds = []); //内环可能多个
  6510. ring.closetParent.closetChilds.push(ring);
  6511. }
  6512. });
  6513. //console.log(rings)
  6514. var _ring = rings.map(ring => {
  6515. var data = {
  6516. id: ring.id,
  6517. points: ring.points.map(point => {
  6518. return {
  6519. id: point.ids[0],
  6520. x: point.x,
  6521. y: point.y
  6522. };
  6523. }),
  6524. /* doors : o.doors.filter(door=>{
  6525. if(ring.closetChilds){
  6526. var childOutLines = getDifferenceSetMuti(ring.closetChilds.map(ring=>ring.lines)) //最近子环的外边
  6527. return ring.lines.concat(childOutLines).includes(door.atLine)
  6528. }else{
  6529. return ring.lines.includes(door.atLine)
  6530. }
  6531. }), */
  6532. area: ring.area,
  6533. closetParent: ring.closetParent && ring.closetParent.id,
  6534. closetChilds: ring.closetChilds && ring.closetChilds.map(e => e.id)
  6535. };
  6536. return data;
  6537. });
  6538. //console.log(JSON.stringify(_ring))
  6539. return _ring;
  6540. };
  6541. var easing = {};
  6542. //渐变曲线函数,反应加速度的变化
  6543. //currentTime:x轴当前时间(从0-到duration), startY:起始点, duration:总时长, wholeY:路程 (即endY-startY)
  6544. //参数基本是 x, 0, 1, 1
  6545. /*
  6546. easeOut 基本是y= m * (x-dur)^k + n, 若k为偶数,m<0, 若k为奇数,m>0; (因为偶数的话必须开口向下才能获得斜率递减的递增的那段,而奇数是对称的,单调递增. )
  6547. 根据x=0时y=0, x=dur时y=S , 得 n = S,m = -S/(-dur)^k
  6548. */
  6549. easing.getEaseOut = function (k) {
  6550. // k 是>=2的整数. 越大变化率越大, 相同初始速度所需要时间越久
  6551. var easeFun;
  6552. k = Math.round(k);
  6553. if (k < 2) {
  6554. k = Math.PI / 2;
  6555. easeFun = easing.easeOutSine;
  6556. } else {
  6557. easeFun = function easeFun(currentTime, startY, wholeY, duration) {
  6558. if (k > 2) {
  6559. console.log(k);
  6560. }
  6561. return -wholeY / Math.pow(-duration, k) * Math.pow(currentTime - duration, k) + wholeY;
  6562. };
  6563. }
  6564. return {
  6565. k,
  6566. easeFun
  6567. };
  6568. };
  6569. easing.linearTween = function (currentTime, startY, wholeY, duration) {
  6570. return wholeY * currentTime / duration + startY;
  6571. }, easing.easeInQuad = function (currentTime, startY, wholeY, duration) {
  6572. return currentTime /= duration, wholeY * currentTime * currentTime + startY;
  6573. }, easing.easeOutQuad = function (currentTime, startY, wholeY, duration) {
  6574. // 如套上实际的距离S和时长dur, y = - S / dur *(x^2-2x) 当s为1,dur为1时,是 y = -(x-1)^2 + 1 , 在0-1中是斜率递减的递增函数. 导数- S / dur *(2x-2 ) 可求出实时速度 故在0这一时刻,速度为 2S/dur
  6575. return currentTime /= duration, -wholeY * currentTime * (currentTime - 2) + startY;
  6576. }, easing.easeInOutQuad = function (currentTime, startY, wholeY, duration) {
  6577. return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime + startY : (currentTime--, -wholeY / 2 * (currentTime * (currentTime - 2) - 1) + startY);
  6578. }, easing.easeInCubic = function (currentTime, startY, wholeY, duration) {
  6579. return currentTime /= duration, wholeY * currentTime * currentTime * currentTime + startY;
  6580. }, easing.easeOutCubic = function (currentTime, startY, wholeY, duration) {
  6581. // y = S / dur^3 *(x-dur)^3 + S,对称中心是(dur,S),从0-dur是 斜率递减的递增函数,导数为3S/dur^3 * (x-dur)^2, 0时速度为3S/dur
  6582. return currentTime /= duration, currentTime--, wholeY * (currentTime * currentTime * currentTime + 1) + startY;
  6583. }, easing.easeInOutCubic = function (currentTime, startY, wholeY, duration) {
  6584. return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime + startY : (currentTime -= 2, wholeY / 2 * (currentTime * currentTime * currentTime + 2) + startY);
  6585. }, easing.easeInQuart = function (currentTime, startY, wholeY, duration) {
  6586. return currentTime /= duration, wholeY * currentTime * currentTime * currentTime * currentTime + startY;
  6587. }, easing.easeOutQuart = function (currentTime, startY, wholeY, duration) {
  6588. //根据上面的计算,估计0时速度应该是4S/dur吧……
  6589. return currentTime /= duration, currentTime--, -wholeY * (currentTime * currentTime * currentTime * currentTime - 1) + startY;
  6590. }, easing.easeInOutQuart = function (currentTime, startY, wholeY, duration) {
  6591. return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2, -wholeY / 2 * (currentTime * currentTime * currentTime * currentTime - 2) + startY);
  6592. }, easing.easeInQuint = function (currentTime, startY, wholeY, duration) {
  6593. return currentTime /= duration, wholeY * currentTime * currentTime * currentTime * currentTime * currentTime + startY;
  6594. }, easing.easeOutQuint = function (currentTime, startY, wholeY, duration) {
  6595. return currentTime /= duration, currentTime--, wholeY * (currentTime * currentTime * currentTime * currentTime * currentTime + 1) + startY;
  6596. }, easing.easeInOutQuint = function (currentTime, startY, wholeY, duration) {
  6597. return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * currentTime * currentTime * currentTime * currentTime * currentTime + startY : (currentTime -= 2, wholeY / 2 * (currentTime * currentTime * currentTime * currentTime * currentTime + 2) + startY);
  6598. }, easing.easeInSine = function (currentTime, startY, wholeY, duration) {
  6599. return -wholeY * Math.cos(currentTime / duration * (Math.PI / 2)) + wholeY + startY;
  6600. }, easing.easeOutSine = function (currentTime, startY, wholeY, duration) {
  6601. // y' = S * PI / 2 / dur * cos(PI/2/dur * x)
  6602. return wholeY * Math.sin(currentTime / duration * (Math.PI / 2)) + startY;
  6603. }, easing.easeInOutSine = function (currentTime, startY, wholeY, duration) {
  6604. return -wholeY / 2 * (Math.cos(Math.PI * currentTime / duration) - 1) + startY;
  6605. }, easing.easeInExpo = function (currentTime, startY, wholeY, duration) {
  6606. return wholeY * Math.pow(2, 10 * (currentTime / duration - 1)) + startY;
  6607. }, easing.easeOutExpo = function (currentTime, startY, wholeY, duration) {
  6608. return wholeY * (-Math.pow(2, -10 * currentTime / duration) + 1) + startY;
  6609. }, easing.easeInOutExpo = function (currentTime, startY, wholeY, duration) {
  6610. return currentTime /= duration / 2, currentTime < 1 ? wholeY / 2 * Math.pow(2, 10 * (currentTime - 1)) + startY : (currentTime--, wholeY / 2 * (-Math.pow(2, -10 * currentTime) + 2) + startY);
  6611. }, easing.easeInCirc = function (currentTime, startY, wholeY, duration) {
  6612. return currentTime /= duration, -wholeY * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY;
  6613. }, easing.easeOutCirc = function (currentTime, startY, wholeY, duration) {
  6614. return currentTime /= duration, currentTime--, wholeY * Math.sqrt(1 - currentTime * currentTime) + startY;
  6615. }, easing.easeInOutCirc = function (currentTime, startY, wholeY, duration) {
  6616. return currentTime /= duration / 2, currentTime < 1 ? -wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) - 1) + startY : (currentTime -= 2, wholeY / 2 * (Math.sqrt(1 - currentTime * currentTime) + 1) + startY);
  6617. }, easing.easeInElastic = function (currentTime, startY, wholeY, duration) {
  6618. var r = 1.70158,
  6619. o = 0,
  6620. a = wholeY;
  6621. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), -(a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY);
  6622. }, easing.easeOutElastic = function (currentTime, startY, wholeY, duration) {
  6623. var r = 1.70158,
  6624. o = 0,
  6625. a = wholeY;
  6626. return 0 === currentTime ? startY : 1 === (currentTime /= duration) ? startY + wholeY : (o || (o = .3 * duration), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), a * Math.pow(2, -10 * currentTime) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) + wholeY + startY);
  6627. }, easing.easeInOutElastic = function (currentTime, startY, wholeY, duration) {
  6628. var r = 1.70158,
  6629. o = 0,
  6630. a = wholeY;
  6631. return 0 === currentTime ? startY : 2 === (currentTime /= duration / 2) ? startY + wholeY : (o || (o = duration * (.3 * 1.5)), a < Math.abs(wholeY) ? (a = wholeY, r = o / 4) : r = o / (2 * Math.PI) * Math.asin(wholeY / a), currentTime < 1 ? -.5 * (a * Math.pow(2, 10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o)) + startY : a * Math.pow(2, -10 * (currentTime -= 1)) * Math.sin((currentTime * duration - r) * (2 * Math.PI) / o) * .5 + wholeY + startY);
  6632. }, easing.easeInBack = function (currentTime, startY, wholeY, duration, r) {
  6633. return void 0 === r && (r = 1.70158), wholeY * (currentTime /= duration) * currentTime * ((r + 1) * currentTime - r) + startY;
  6634. }, easing.easeOutBack = function (currentTime, startY, wholeY, duration, r) {
  6635. return void 0 === r && (r = 1.70158), wholeY * ((currentTime = currentTime / duration - 1) * currentTime * ((r + 1) * currentTime + r) + 1) + startY;
  6636. }, easing.easeInOutBack = function (currentTime, startY, wholeY, duration, r) {
  6637. return void 0 === r && (r = 1.70158), (currentTime /= duration / 2) < 1 ? wholeY / 2 * (currentTime * currentTime * (((r *= 1.525) + 1) * currentTime - r)) + startY : wholeY / 2 * ((currentTime -= 2) * currentTime * (((r *= 1.525) + 1) * currentTime + r) + 2) + startY;
  6638. }, easing.easeOutBounce = function (currentTime, startY, wholeY, duration) {
  6639. return (currentTime /= duration) < 1 / 2.75 ? wholeY * (7.5625 * currentTime * currentTime) + startY : currentTime < 2 / 2.75 ? wholeY * (7.5625 * (currentTime -= 1.5 / 2.75) * currentTime + .75) + startY : currentTime < 2.5 / 2.75 ? wholeY * (7.5625 * (currentTime -= 2.25 / 2.75) * currentTime + .9375) + startY : wholeY * (7.5625 * (currentTime -= 2.625 / 2.75) * currentTime + .984375) + startY;
  6640. }, easing.easeInBounce = function (currentTime, startY, wholeY, r) {
  6641. return wholeY - easing.easeOutBounce(r - currentTime, 0, wholeY, r) + startY;
  6642. }, easing.easeInOutBounce = function (currentTime, startY, wholeY, r) {
  6643. return currentTime < r / 2 ? .5 * easing.easeInBounce(2 * currentTime, 0, wholeY, r) + startY : .5 * easing.easeOutBounce(x, 2 * currentTime - r, 0, wholeY, r) + .5 * wholeY + startY;
  6644. };
  6645. var lerp = {
  6646. /* vector: function(currentTime, startY, f) {//xzw change, add f
  6647. var wholeY = currentTime.clone();
  6648. return startY = startY.clone(),
  6649. function(duration) {
  6650. currentTime.set(wholeY.x * (1 - duration) + startY.x * duration, wholeY.y * (1 - duration) + startY.y * duration, wholeY.z * (1 - duration) + startY.z * duration)
  6651. f && f(currentTime,duration);
  6652. }
  6653. },
  6654. quaternion: function(currentTime, startY, f) {//xzw change, add f
  6655. var wholeY = currentTime.clone();
  6656. return function(duration) {
  6657. currentTime.copy(wholeY).slerp(startY, duration);
  6658. f && f(currentTime,duration);
  6659. }
  6660. },
  6661. property: function(currentTime, startY, wholeY, duration) {
  6662. var r = currentTime[startY];
  6663. return function(o) {
  6664. currentTime[startY] = r * (1 - o) + wholeY * o,
  6665. duration && duration(currentTime[startY])
  6666. }
  6667. },
  6668. uniform: function(currentTime, startY, wholeY) {
  6669. var duration = currentTime.material.uniforms[startY].value;
  6670. return function(r) {
  6671. try{
  6672. currentTime.material.uniforms[startY] && (currentTime.material.uniforms[startY].value = duration * (1 - r) + wholeY * r)
  6673. }catch(currentTime){
  6674. console.log(1)
  6675. }
  6676. }
  6677. },
  6678. matrix4: function(currentTime, startY) {
  6679. var wholeY = currentTime.clone();
  6680. return function(duration) {
  6681. for (var r = currentTime.elements, o = wholeY.elements, a = startY.elements, s = 0; s < 16; s++)
  6682. r[s] = o[s] * (1 - duration) + a[s] * duration
  6683. }
  6684. },
  6685. allUniforms: function(currentTime, startY, wholeY) {
  6686. var duration = currentTime.map(function(currentTime) {
  6687. return this.uniform(currentTime, startY, wholeY)
  6688. }
  6689. .bind(this));
  6690. return function(currentTime) {
  6691. duration.forEach(function(startY) {
  6692. startY(currentTime)
  6693. })
  6694. }
  6695. } */
  6696. vector: function vector(t, i, f) {
  6697. //xzw change, add f
  6698. var n = t.clone();
  6699. return i = i.clone(), function (e, delta) {
  6700. t.set(n.x * (1 - e) + i.x * e, n.y * (1 - e) + i.y * e, n.z * (1 - e) + i.z * e);
  6701. f && f(t, e, delta);
  6702. };
  6703. },
  6704. quaternion: function quaternion(t, i, f) {
  6705. //xzw change, add f
  6706. var n = t.clone();
  6707. return function (e) {
  6708. t.copy(n).slerp(i, e);
  6709. f && f(t, e);
  6710. };
  6711. },
  6712. property: function property(t, i, n, r) {
  6713. var o = t[i];
  6714. return function (e) {
  6715. t[i] = o * (1 - e) + n * e, r && r(t[i]);
  6716. };
  6717. },
  6718. uniform: function uniform(t, i, n) {
  6719. var r = t.material.uniforms[i].value;
  6720. return function (e) {
  6721. t.material.uniforms[i] && (t.material.uniforms[i].value = r * (1 - e) + n * e);
  6722. };
  6723. },
  6724. matrix4: function matrix4(o, a) {
  6725. var s = o.clone();
  6726. return function (e) {
  6727. for (var t = o.elements, i = s.elements, n = a.elements, r = 0; r < 16; r++) t[r] = i[r] * (1 - e) + n[r] * e;
  6728. };
  6729. },
  6730. allUniforms: function allUniforms(e, t, i) {
  6731. var n = e.map(function (e) {
  6732. return this.uniform(e, t, i);
  6733. }.bind(this));
  6734. return function (t) {
  6735. n.forEach(function (e) {
  6736. e(t);
  6737. });
  6738. };
  6739. }
  6740. };
  6741. /*
  6742. 渐变
  6743. */
  6744. var transitions = {
  6745. globalDone: null,
  6746. funcs: [],
  6747. counter: 0,
  6748. uniqueID: 0,
  6749. start: function start(func, duration, done, delay, ease, name, id, cancelFun) {
  6750. var ignoreFirstFrame = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : true;
  6751. return delay = delay || 0, this.funcs.push({
  6752. func: func,
  6753. current: -delay * Math.abs(duration),
  6754. //当前时间
  6755. duration: (1 - Math.max(delay, 0)) * Math.abs(duration),
  6756. //总时长
  6757. done: done,
  6758. easing: ease || easing.linearTween,
  6759. //渐变曲线
  6760. cycling: duration < 0,
  6761. running: !0,
  6762. debug: delay < 0,
  6763. name: name || "T" + this.counter,
  6764. id: void 0 === id ? this.counter : id,
  6765. paused: !1,
  6766. cancelFun: cancelFun,
  6767. //取消时执行的函数
  6768. updateCount: 0,
  6769. ignoreFirstFrame
  6770. }), func(0, 16), this.counter += 1, func;
  6771. },
  6772. trigger: function trigger(e) {
  6773. var t = void 0 === e.delayRatio ? 0 : e.delayRatio,
  6774. u = e.func || function () {},
  6775. r = void 0 === e.duration ? 0 : e.duration;
  6776. void 0 !== e.cycling && e.cycling && (r = -Math.abs(r));
  6777. var o = e.done || null,
  6778. a = e.easing || easing.linearTween,
  6779. s = e.name || "R" + this.counter,
  6780. l = void 0 === e.id ? this.counter : e.id;
  6781. return this.start(u, r, o, t, a, s, l);
  6782. },
  6783. setTimeout: function setTimeout(e, t, u) {
  6784. var duration = void 0 === u ? this.counter : u;
  6785. return this.trigger({
  6786. done: e,
  6787. duration: void 0 === t ? 0 : t,
  6788. name: "O" + this.counter,
  6789. id: duration
  6790. });
  6791. },
  6792. pause: function pause() {
  6793. this.paused = !0;
  6794. },
  6795. resume: function resume() {
  6796. this.paused = !1;
  6797. },
  6798. update: function update(e) {
  6799. this.funcs.forEach(function (t) {
  6800. if (t.updateCount++ == 0 && t.ignoreFirstFrame) return; //add start可能发生在一帧中任意时刻,而每次update的是在一帧中的固定时刻,所以从start到第一次update的时间并不是所传入的delta,该delta 是上一帧的update到这一帧的update的耗时。 故去掉了第一次的update,相当于延迟一帧再update.
  6801. if (!(t.paused || (t.current += 1e3 * e, t.current < 0))) {
  6802. if (t.current >= t.duration && !t.cycling) {
  6803. var u = t.easing(1, 0, 1, 1);
  6804. t.func(u, 1e3 * e), t.done && t.done(), t.running = !1;
  6805. } else {
  6806. var duration = t.easing(t.current % t.duration / t.duration, 0, 1, 1),
  6807. r = t.func(duration, 1e3 * e) || !1;
  6808. r && (t.done && t.done(), t.running = !1);
  6809. }
  6810. }
  6811. });
  6812. var t = this.funcs.length;
  6813. this.funcs = this.funcs.filter(function (e) {
  6814. return e.running;
  6815. });
  6816. var u = this.funcs.length;
  6817. if (t > 0 && 0 === u && this.globalDone) {
  6818. var duration = this.globalDone;
  6819. this.globalDone = null, duration();
  6820. }
  6821. },
  6822. adjustSpeed: function adjustSpeed(e, t) {
  6823. for (var u = this.getById(e), duration = 0; duration < u.length; duration++) {
  6824. var r = u[duration];
  6825. r.duration /= t, r.current /= t;
  6826. }
  6827. },
  6828. getById: function getById(e) {
  6829. return this.funcs.filter(function (t) {
  6830. return e === t.id;
  6831. });
  6832. },
  6833. get: function get(e) {
  6834. for (var t = 0; t < this.funcs.length; t += 1) if (this.funcs[t].func === e) return this.funcs[t];
  6835. return null;
  6836. },
  6837. isRunning: function isRunning(e) {
  6838. var t = this.get(e);
  6839. return null !== t && t.running;
  6840. },
  6841. countActive: function countActive() {
  6842. for (var e = 0, t = 0; t < this.funcs.length; t += 1) e += this.funcs[t].running;
  6843. return e;
  6844. },
  6845. listActive: function listActive() {
  6846. for (var e = [], t = 0; t < this.funcs.length; t += 1) this.funcs[t].running && e.push(this.funcs[t].name);
  6847. return e;
  6848. },
  6849. done: function done(e) {
  6850. this.globalDone = e;
  6851. },
  6852. cancelById: function cancelById(e, dealCancelFun) {
  6853. //xzw add dealDone
  6854. var t = void 0 === e ? 0 : e;
  6855. var cancels = [];
  6856. this.funcs = this.funcs.filter(function (e) {
  6857. var is = e.id == t;
  6858. if (is && dealCancelFun) {
  6859. e.cancelFun && cancels.push(e.cancelFun);
  6860. //e.cancelFun && e.cancelFun()
  6861. }
  6862. return !is;
  6863. });
  6864. cancels.forEach(e => {
  6865. e();
  6866. }); //先从funcs中去除后再执行
  6867. },
  6868. cancel: function cancel(e) {
  6869. this.funcs = this.funcs.filter(function (t) {
  6870. return t.func !== e;
  6871. });
  6872. },
  6873. getUniqueId: function getUniqueId() {
  6874. return this.uniqueID -= 1, this.uniqueID;
  6875. }
  6876. };
  6877. //THREE.Vector2.name2 = 'Common'
  6878. var Common = {
  6879. sortByScore: function sortByScore(list, request, rank) {
  6880. var i = request ? Common.filterAll(list, request) : list;
  6881. return 0 === i.length ? [] : i = i.map(function (e) {
  6882. var results = rank.map(function (f) {
  6883. return f(e);
  6884. });
  6885. var scores = results.map(e => e.score != void 0 ? e.score : e);
  6886. var logs = results.map(e => e.log);
  6887. return {
  6888. item: e,
  6889. scores,
  6890. logs,
  6891. score: scores.reduce(function (t, i) {
  6892. //总分
  6893. return t + i;
  6894. }, 0)
  6895. };
  6896. }).sort(function (e, t) {
  6897. return t.score - e.score;
  6898. });
  6899. },
  6900. filterAll: function filterAll(e, t) {
  6901. return e.filter(function (e) {
  6902. return t.every(function (t) {
  6903. return t(e);
  6904. });
  6905. });
  6906. },
  6907. //---------------
  6908. find: function find(list, request, rank, sortByScore) {
  6909. if (sortByScore) {
  6910. var r = this.sortByScore(list, request, rank);
  6911. return r[0] && r[0].item;
  6912. } else {
  6913. var i = request ? Common.filterAll(list, request) : list;
  6914. return 0 === i.length ? null : (rank && rank.forEach(function (e) {
  6915. i = Common.stableSort(i, e);
  6916. }), i[0]);
  6917. }
  6918. },
  6919. stableSort: function stableSort(e, f) {
  6920. //用到排序函数,涉及到两个item相减
  6921. return e.map(function (e, i) {
  6922. return {
  6923. value: e,
  6924. index: i
  6925. };
  6926. }).sort(function (e, u) {
  6927. var n = f(e.value, u.value);
  6928. return 0 !== n ? n : e.index - u.index; //似乎就是加多了这一步:若差距为0,按照原顺序
  6929. }).map(function (e) {
  6930. return e.value;
  6931. });
  6932. },
  6933. average: function average(e, t) {
  6934. if (0 === e.length) return null;
  6935. for (var i = 0, n = 0, r = 0; r < e.length; r++) {
  6936. var o = t ? e[r][t] : e[r];
  6937. i += o, n++;
  6938. }
  6939. return i / n;
  6940. },
  6941. //---------------------------
  6942. getMixedSet: function getMixedSet(arr1, arr2) {
  6943. //交集
  6944. return arr1.filter(item => arr2.includes(item));
  6945. },
  6946. getUnionSet: function getUnionSet(arr1, arr2) {
  6947. //并集
  6948. return arr1.concat(arr2.filter(item => !arr1.includes(item)));
  6949. },
  6950. getDifferenceSet: function getDifferenceSet(arr1, arr2) {
  6951. //差集 不能识别重复的,如getDifferenceSet([1,2,2],[1,1,2]) 为空
  6952. var arr11 = arr1.filter(item => !arr2.includes(item));
  6953. var arr22 = arr2.filter(item => !arr1.includes(item));
  6954. return arr11.concat(arr22);
  6955. },
  6956. getDifferenceSetMuti: function getDifferenceSetMuti(arr) {
  6957. //收集绝对没有重复的元素,也就是判断出现次数=1的
  6958. var set = [];
  6959. arr.forEach(arr1 => {
  6960. arr1.forEach(item => {
  6961. var index = set.indexOf(item);
  6962. if (index > -1) {
  6963. set.splice(index, 1);
  6964. } else {
  6965. set.push(item);
  6966. }
  6967. });
  6968. });
  6969. return set;
  6970. },
  6971. CloneJson: function CloneJson(data) {
  6972. var str = JSON.stringify(data);
  6973. return JSON.parse(str);
  6974. },
  6975. CloneObject: function CloneObject(copyObj, isSimpleCopy) {
  6976. var simpleCopyList = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  6977. var judgeSimpleCopyFun = arguments.length > 3 ? arguments[3] : undefined;
  6978. //isSimpleCopy 只复制最外层
  6979. //复制json result的可能:普通数字或字符串、普通数组、复杂对象
  6980. judgeSimpleCopyFun || (judgeSimpleCopyFun = () => {});
  6981. if (!copyObj || typeof copyObj == 'number' || typeof copyObj == 'string' || copyObj.isObject3D || copyObj instanceof Function || simpleCopyList.some(className => copyObj instanceof className) || judgeSimpleCopyFun(copyObj)) {
  6982. return copyObj;
  6983. }
  6984. if (copyObj instanceof Array) {
  6985. return copyObj.map(e => {
  6986. return this.CloneObject(e, isSimpleCopy, simpleCopyList, judgeSimpleCopyFun);
  6987. });
  6988. } else {
  6989. if (copyObj.clone instanceof Function) {
  6990. //解决一部分
  6991. return copyObj.clone();
  6992. }
  6993. }
  6994. var result = {};
  6995. for (var key in copyObj) {
  6996. if (copyObj[key] instanceof Object && !isSimpleCopy) result[key] = this.CloneObject(copyObj[key], isSimpleCopy, simpleCopyList, judgeSimpleCopyFun);else result[key] = copyObj[key];
  6997. //如果是函数类同基本数据,即复制引用
  6998. }
  6999. return result;
  7000. },
  7001. CloneClassObject: function CloneClassObject(copyObj) {
  7002. var {
  7003. ignoreList = [],
  7004. simpleCopyList = []
  7005. } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  7006. //复杂类对象
  7007. var newobj = new copyObj.constructor();
  7008. this.CopyClassObject(newobj, copyObj, {
  7009. ignoreList,
  7010. simpleCopyList
  7011. });
  7012. return newobj;
  7013. },
  7014. CopyClassObject: function CopyClassObject(targetObj, copyObj) {
  7015. var {
  7016. ignoreList = [],
  7017. simpleCopyList = []
  7018. } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  7019. //复杂类对象
  7020. for (var i in copyObj) {
  7021. if (i in copyObj.__proto__) break; //到函数了跳出
  7022. if (ignoreList.includes(i)) {
  7023. continue;
  7024. } else if (simpleCopyList.includes(i)) {
  7025. targetObj[i] = copyObj[i];
  7026. } else {
  7027. targetObj[i] = this.CloneObject(copyObj[i], false, simpleCopyList);
  7028. }
  7029. /* else if(copyObj[i].clone instanceof Function ){
  7030. targetObj[i] = copyObj[i].clone()
  7031. }else{
  7032. targetObj[i] = copyObj[i];
  7033. } */
  7034. }
  7035. },
  7036. ifSame: function ifSame(object1, object2) {
  7037. var simpleEqualClass = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  7038. //对于复杂的类对象,若能简单判断就直接写进simpleEqualClass
  7039. if (object1 == object2) return true; // 0 != undefined , 0 == ''
  7040. else if (!object1 || !object2) return false;else if (object1.constructor != object2.constructor) {
  7041. return false;
  7042. } else if (simpleEqualClass.some(className => object1 instanceof className)) {
  7043. return object1 == object2;
  7044. } else if (object1 instanceof Array) {
  7045. if (object1.length != object2.length) return false;
  7046. var _object2 = object2.slice(0);
  7047. var _loop = function _loop(i) {
  7048. u = _object2.find(e => Common.ifSame(object1[i], e, simpleEqualClass));
  7049. if (u == void 0 && !_object2.includes(u) && !object1.includes(u)) return {
  7050. v: false
  7051. };else {
  7052. var index = _object2.indexOf(u);
  7053. _object2.splice(index, 1);
  7054. }
  7055. },
  7056. u,
  7057. _ret;
  7058. for (var i = 0; i < object1.length; i++) {
  7059. _ret = _loop(i);
  7060. if (_ret) return _ret.v;
  7061. }
  7062. return true;
  7063. } else if (object1.equals instanceof Function) {
  7064. //复杂数据仅支持这种,其他的可能卡住?
  7065. return object1.equals(object2);
  7066. } else if (typeof object1 == 'number' || typeof object1 == 'string') {
  7067. if (isNaN(object1) && isNaN(object2)) return true;else return object1 == object2;
  7068. } else if (typeof object1 == "object") {
  7069. var keys1 = Object.keys(object1);
  7070. var keys2 = Object.keys(object2);
  7071. if (!Common.ifSame(keys1, keys2, simpleEqualClass)) return false;
  7072. for (var _i in object1) {
  7073. var same = Common.ifSame(object1[_i], object2[_i], simpleEqualClass);
  7074. if (!same) return false;
  7075. }
  7076. return true;
  7077. } else {
  7078. console.log('isSame出现例外');
  7079. }
  7080. },
  7081. downloadFile: function downloadFile(data, filename, cb) {
  7082. var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
  7083. save_link.href = data;
  7084. save_link.download = filename;
  7085. var event = document.createEvent('MouseEvents');
  7086. event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  7087. save_link.dispatchEvent(event);
  7088. cb && cb();
  7089. },
  7090. replaceAll: function replaceAll(str, f, e) {
  7091. //f全部替换成e
  7092. var reg = new RegExp(f, "g"); //创建正则RegExp对象
  7093. return str.replace(reg, e);
  7094. },
  7095. dealURL(url) {
  7096. var urlNew = this.replaceAll(url, "\\+", "%2B"); // 浏览器似乎不支持访问带+的地址
  7097. urlNew = this.replaceAll(urlNew, "/.//", "/"); //去除双斜杠(/.//)
  7098. return urlNew;
  7099. },
  7100. getNameFromURL(url) {
  7101. if (!url) return '';
  7102. var get = e => {
  7103. return e.split('/').pop();
  7104. };
  7105. if (url instanceof Array) {
  7106. return url.map(e => get(e));
  7107. }
  7108. return get(url);
  7109. },
  7110. //---------------------------
  7111. intervalTool: {
  7112. //延时update,防止卡顿
  7113. list: [],
  7114. /* isWaiting:function(name, func, delayTime){
  7115. if(!this.list.includes(name)){ //如果没有该项, 则开始判断
  7116. var needWait = func(); //触发了改变,则等待一段时间后再自动判断
  7117. if(needWait){
  7118. this.list.push(name);
  7119. setTimeout(()=>{
  7120. var a = this.list.indexOf(name);
  7121. this.list.splice(a,1);
  7122. this.isWaiting(name, func, delayTime) //循环
  7123. },delayTime)
  7124. }
  7125. }
  7126. }, */
  7127. isWaiting: function isWaiting(name, func, delayTime /* , autoCycle */) {
  7128. var item = this.list.find(e => e.name == name);
  7129. if (!item) {
  7130. //如果没有该项, 则加入循环
  7131. var ifContinue = func();
  7132. item = {
  7133. name,
  7134. func,
  7135. delayTime
  7136. };
  7137. this.list.push(item);
  7138. setTimeout(() => {
  7139. var a = this.list.indexOf(item);
  7140. this.list.splice(a, 1);
  7141. var {
  7142. func,
  7143. delayTime
  7144. } = item;
  7145. if (item.requestUpdate || ifContinue) this.isWaiting(name, func, delayTime); //循环
  7146. }, delayTime);
  7147. } else {
  7148. //如果有该项,说明现在请求下一次继续更新
  7149. //if(delayTime == 0){//想立刻更新一次
  7150. // func()
  7151. //}else{
  7152. //更新属性
  7153. item.func = func;
  7154. item.delayTime = delayTime;
  7155. item.requestUpdate = true;
  7156. //}
  7157. }
  7158. }
  7159. },
  7160. pushToGroupAuto: function pushToGroupAuto(items, groups, recognizeFunction, recognizeGroup) {
  7161. //自动分组。 items是将分到一起的组合。items.length = 1 or 2.
  7162. recognizeFunction = recognizeFunction || function () {};
  7163. if (recognizeGroup) {
  7164. //有更复杂的识别处理,直接传递整个组
  7165. var atGroups = groups.filter(group => recognizeGroup(group, items));
  7166. } else {
  7167. var atGroups = groups.filter(group => group.find(item => items[0] == item || recognizeFunction(item, items[0]) || items[1] == item || items[1] && recognizeFunction(item, items[1])));
  7168. }
  7169. if (atGroups.length) {
  7170. //在不同组
  7171. //因为items是一组的,所以先都放入组1
  7172. items.forEach(item => {
  7173. if (!atGroups[0].includes(item)) atGroups[0].push(item);
  7174. });
  7175. if (atGroups.length > 1) {
  7176. //如果在不同组,说明这两个组需要合并
  7177. var combineGroup = [];
  7178. atGroups.forEach(group => {
  7179. combineGroup = Common.getUnionSet(combineGroup, group);
  7180. groups.splice(groups.indexOf(group), 1);
  7181. });
  7182. groups.push(combineGroup);
  7183. }
  7184. } else {
  7185. //直接加入为一组
  7186. groups.push(items);
  7187. }
  7188. },
  7189. getBestCount: function () {
  7190. var lastCount = {};
  7191. return function (name) {
  7192. var minCount = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  7193. var maxCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6;
  7194. var durBound1 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1.2;
  7195. var durBound2 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 10;
  7196. var ifLog = arguments.length > 5 ? arguments[5] : undefined;
  7197. var maxHistory = arguments.length > 6 ? arguments[6] : undefined;
  7198. var timeStamp = performance.getEntriesByName("loop-start");
  7199. var count;
  7200. if (timeStamp.length) {
  7201. var dur = performance.now() - timeStamp[timeStamp.length - 1].startTime; //dur在iphoneX中静止有7,pc是2
  7202. count = Math.round(math.linearClamp(dur, [durBound1, durBound2], [maxCount, minCount]));
  7203. if (maxHistory) {
  7204. if (!lastCount[name]) lastCount[name] = [];
  7205. if (count == 0 && lastCount[name].length > maxHistory - 1 && !lastCount[name].some(e => e > 0)) {
  7206. count = 1;
  7207. }
  7208. lastCount[name].push(count);
  7209. if (lastCount[name].length > maxHistory) lastCount[name].splice(0, 1);
  7210. }
  7211. if (ifLog) {
  7212. //注意,console.log本身用时挺高, 降4倍时可能占用0.5毫秒
  7213. name && count && console.log(name, count, ' ,dur:', dur.toFixed(3));
  7214. }
  7215. } else {
  7216. count = maxCount; // ?
  7217. }
  7218. //主要在手机端有效果。
  7219. return count;
  7220. };
  7221. }(),
  7222. batchHandling: {
  7223. //分批处理
  7224. lists: [],
  7225. getSlice: function getSlice(name, items, _ref) {
  7226. var {
  7227. stopWhenAllUsed,
  7228. min = 5,
  7229. max = 100,
  7230. durBound1,
  7231. durBound2,
  7232. useEquals,
  7233. maxUseCount
  7234. } = _ref;
  7235. if (items.length == 0 || (maxUseCount = maxUseCount == void 0 ? Common.getBestCount(name, min, max, durBound1, durBound2 /* , true */) : maxUseCount, !maxUseCount) //本次最多可以使用的个数
  7236. ) {
  7237. return {
  7238. list: []
  7239. };
  7240. }
  7241. if (!this.lists[name]) this.lists[name] = {
  7242. list: []
  7243. };
  7244. //更新列表项目,但不变原来的顺序
  7245. var list = this.lists[name].list.filter(a => items.some(item => useEquals ? a.item.equals(item) : a.item == item)); //去掉已经不在items里的项目
  7246. this.lists[name].list = list;
  7247. items.forEach(item => {
  7248. //增加新的项目。
  7249. if (!list.some(a => useEquals ? a.item.equals(item) : a.item == item)) {
  7250. list.push({
  7251. item,
  7252. count: 0
  7253. });
  7254. }
  7255. });
  7256. //至此,在后排的都是未使用的
  7257. var unUsed = list.filter(e => e.count == 0); //未使用的项目(count为0)优先
  7258. var result = [];
  7259. unUsed.slice(0, maxUseCount).forEach(e => {
  7260. result.push(e.item);
  7261. e.count++;
  7262. });
  7263. if (unUsed.length > maxUseCount) {
  7264. //还是剩有未使用的项目,等待下一次
  7265. } else {
  7266. //所有项目都能使用一次
  7267. if (!stopWhenAllUsed) {
  7268. //若不是全部使用就停止
  7269. var wholeCount = Math.min(items.length, maxUseCount);
  7270. var restCount = wholeCount - result.length; //补齐
  7271. list.slice(0, restCount).forEach(e => {
  7272. result.push(e.item);
  7273. e.count++;
  7274. });
  7275. }
  7276. list.forEach(e => e.count--); //复原,等待新的循环
  7277. }
  7278. /* result.forEach((e,i)=>{//有重复的
  7279. if( result.slice(0,i).some(a=>a.equals(e)) || result.slice(i+1).some(a=>a.equals(e)) ) {
  7280. console.log(e)
  7281. }
  7282. }) */
  7283. return {
  7284. list: result
  7285. };
  7286. }
  7287. },
  7288. getRootWindow() {
  7289. //获取包含Potree的根window
  7290. var win = window;
  7291. try {
  7292. while (win.parent != win && win.parent.Potree) {
  7293. win = win.parent;
  7294. }
  7295. if (window != win) return win;
  7296. } catch (e) {
  7297. //console.log(e) //可能跨域,从而win.parent.Potree报错
  7298. console.log('getRootWindow 跨域');
  7299. return;
  7300. }
  7301. },
  7302. watch: function watch(object, propName, initialValue) {
  7303. //监听某个属性的变化
  7304. var v = initialValue;
  7305. Object.defineProperty(object, propName, {
  7306. get: function get() {
  7307. return v;
  7308. },
  7309. set: function set(e) {
  7310. console.warn('watch:', propName, e);
  7311. v = e;
  7312. }
  7313. });
  7314. },
  7315. imgAddLabel: function imgAddLabel(img, labelImg) {
  7316. var labelInfo = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  7317. //图上加另一张小图,用于添加水印
  7318. var canvas;
  7319. if (img instanceof Image) {
  7320. canvas = document.createElement('canvas');
  7321. } else {
  7322. canvas = img;
  7323. }
  7324. var context = canvas.getContext('2d');
  7325. var marginLeft = labelInfo.bgMargin && labelInfo.bgMargin.left || 0;
  7326. var marginRight = labelInfo.bgMargin && labelInfo.bgMargin.right || 0;
  7327. var marginTop = labelInfo.bgMargin && labelInfo.bgMargin.top || 0;
  7328. var marginBottom = labelInfo.bgMargin && labelInfo.bgMargin.bottom || 0;
  7329. if (img instanceof Image) {
  7330. //如果img是canvas,说明已绘制在canvas上了就不用绘制了
  7331. var width = img.width + marginLeft + marginRight;
  7332. var height = img.height + marginTop + marginBottom;
  7333. canvas.width = width;
  7334. canvas.height = height;
  7335. if (labelInfo.bgColor) {
  7336. context.fillStyle = 'rgba(' + labelInfo.bgColor.r + ',' + labelInfo.bgColor.g + ',' + labelInfo.bgColor.b + ',' + labelInfo.bgColor.a + ')';
  7337. context.fillRect(0, 0, width, height);
  7338. }
  7339. context.drawImage(img, marginLeft, marginTop, img.width, img.height);
  7340. }
  7341. var labelWidth = labelInfo.widthRatioToImg ? img.width * labelInfo.widthRatioToImg : labelImg.width; //widthRatioToImg:label的width占img的width的比例
  7342. var labelHeight = labelWidth * labelImg.height / labelImg.width;
  7343. if (labelInfo.leftRatioToImg == void 0 && labelInfo.rightRatioToImg != void 0) {
  7344. labelInfo.leftRatioToImg = 1 - labelInfo.rightRatioToImg - (labelInfo.widthRatioToImg || labelImg.width / img.width);
  7345. }
  7346. if (labelInfo.topRatioToImg == void 0 && labelInfo.bottomRatioToImg != void 0) {
  7347. labelInfo.topRatioToImg = 1 - labelInfo.bottomRatioToImg - labelHeight / img.height;
  7348. }
  7349. var labelLeft = img.width * labelInfo.leftRatioToImg + marginLeft; //leftRatioToImg:label的left占img的width的比例
  7350. var labelTop = img.height * labelInfo.topRatioToImg + marginTop; //topRatioToImg:label的top占img的height的比例
  7351. context.globalAlpha = labelInfo.opacity != void 0 ? labelInfo.opacity : 1;
  7352. context.drawImage(labelImg, labelLeft, labelTop, labelWidth, labelHeight);
  7353. if (labelInfo.outputCanvas) {
  7354. return canvas;
  7355. }
  7356. var dataUrl = canvas.toDataURL('image/png', labelInfo.compressRatio);
  7357. //Common.downloadFile(dataUrl, 'screenshot.png')
  7358. context.clearRect(0, 0, canvas.width, canvas.height);
  7359. return dataUrl;
  7360. },
  7361. changeShaderToWebgl2(vs, fs, matType) {
  7362. var otherReplaces = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  7363. //部分shader要根据webgl版本作更改
  7364. if (!Potree.settings.isWebgl2) return {
  7365. vs,
  7366. fs
  7367. };
  7368. var turnTo300 = matType != 'ShaderMaterial' && (vs.includes('gl_FragDepthEXT') || fs.includes('gl_FragDepthEXT'));
  7369. var addV300 = turnTo300 && matType != 'RawShaderMaterial'; // RawShaderMaterial直接material.glslVersion = '300 es' 以加在define之前
  7370. var change = (shader, shaderType) => {
  7371. var newShader = shader;
  7372. if (turnTo300) {
  7373. //非shaderMaterial需要手动改为300 es的写法
  7374. addV300 && (newShader = '#version 300 es \n' + newShader); //需要加 #version 300 es。 three.js自带的渲染会自动加所以不用
  7375. newShader = newShader.replaceAll('varying ', shaderType == 'vs' ? 'out ' : 'in ');
  7376. newShader = newShader.replaceAll('attribute ', 'in ');
  7377. if (shaderType == 'fs') {
  7378. newShader = newShader.replaceAll('gl_FragColor', 'fragColor');
  7379. newShader = newShader.replace('void main', 'out vec4 fragColor;\n void main'); //在void main前加入这个声明
  7380. }
  7381. newShader = newShader.replaceAll('gl_FragDepthEXT', 'gl_FragDepth');
  7382. newShader = newShader.replaceAll('texture2D', 'texture');
  7383. newShader = newShader.replaceAll('textureCube', 'texture');
  7384. }
  7385. newShader = newShader.replace('#extension GL_EXT_frag_depth : enable', '');
  7386. newShader = newShader.replaceAll('defined(GL_EXT_frag_depth) &&', '');
  7387. otherReplaces.forEach(_ref2 => {
  7388. var {
  7389. oldStr,
  7390. newStr
  7391. } = _ref2;
  7392. newShader = newShader.replaceAll(oldStr, newStr);
  7393. });
  7394. return newShader;
  7395. };
  7396. vs = change(vs, 'vs');
  7397. fs = change(fs, 'fs');
  7398. //console.log('成功替换为webgl2' )
  7399. return {
  7400. vs,
  7401. fs
  7402. };
  7403. } //three.js的shaderMaterial也有替换功能,搜 '#define gl_FragDepthEXT gl_FragDepth',
  7404. };
  7405. Potree.Common = Common;
  7406. class View {
  7407. //base
  7408. constructor() {
  7409. this.position = new Vector3(0, 0, 0);
  7410. this.yaw = Math.PI / 4;
  7411. this._pitch = -Math.PI / 4;
  7412. this.radius = 1;
  7413. this.maxPitch = Math.PI / 2;
  7414. this.minPitch = -Math.PI / 2;
  7415. }
  7416. clone() {
  7417. var c = new View();
  7418. c.yaw = this.yaw;
  7419. c._pitch = this.pitch;
  7420. c.radius = this.radius;
  7421. c.maxPitch = this.maxPitch;
  7422. c.minPitch = this.minPitch;
  7423. return c;
  7424. }
  7425. get pitch() {
  7426. return this._pitch;
  7427. }
  7428. set pitch(angle) {
  7429. this._pitch = Math.max(Math.min(angle, this.maxPitch), this.minPitch);
  7430. }
  7431. get direction() {
  7432. var dir = new Vector3(0, 1, 0);
  7433. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  7434. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  7435. return dir;
  7436. }
  7437. set direction(dir) {
  7438. dir = dir.clone().normalize(); //add
  7439. if (dir.x === 0 && dir.y === 0) {
  7440. this.pitch = Math.PI / 2 * Math.sign(dir.z);
  7441. //this.yaw = 0 //add:还是要指定一下, 否则不统一
  7442. } else {
  7443. var yaw = Math.atan2(dir.y, dir.x) - Math.PI / 2;
  7444. var pitch = Math.atan2(dir.z, Math.sqrt(dir.x * dir.x + dir.y * dir.y));
  7445. this.yaw = yaw;
  7446. this.pitch = pitch;
  7447. }
  7448. }
  7449. lookAt(t) {
  7450. //setPivot
  7451. var V;
  7452. if (arguments.length === 1) {
  7453. V = new Vector3().subVectors(t, this.position);
  7454. } else if (arguments.length === 3) {
  7455. V = new Vector3().subVectors(new Vector3(...arguments), this.position);
  7456. }
  7457. var radius = V.length();
  7458. var dir = V.normalize();
  7459. this.radius = radius;
  7460. this.direction = dir;
  7461. }
  7462. getPivot() {
  7463. return new Vector3().addVectors(this.position, this.direction.multiplyScalar(this.radius));
  7464. }
  7465. getSide() {
  7466. var side = new Vector3(1, 0, 0);
  7467. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  7468. return side;
  7469. }
  7470. pan(x, y) {
  7471. var dir = new Vector3(0, 1, 0);
  7472. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  7473. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  7474. // let side = new THREE.Vector3(1, 0, 0);
  7475. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  7476. var side = this.getSide();
  7477. var up = side.clone().cross(dir);
  7478. var pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  7479. this.position = this.position.add(pan);
  7480. // this.target = this.target.add(pan);
  7481. }
  7482. translate(x, y, z) {
  7483. var dir = new Vector3(0, 1, 0);
  7484. dir.applyAxisAngle(new Vector3(1, 0, 0), this.pitch);
  7485. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  7486. var side = new Vector3(1, 0, 0);
  7487. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw);
  7488. var up = side.clone().cross(dir);
  7489. var t = side.multiplyScalar(x).add(dir.multiplyScalar(y)).add(up.multiplyScalar(z));
  7490. this.position = this.position.add(t);
  7491. }
  7492. translateWorld(x, y, z) {
  7493. this.position.x += x;
  7494. this.position.y += y;
  7495. this.position.z += z;
  7496. }
  7497. setView(position, target) {
  7498. var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  7499. var callback = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null;
  7500. var endPosition = null;
  7501. if (position instanceof Array) {
  7502. endPosition = new Vector3(...position);
  7503. } else if (position.x != null) {
  7504. endPosition = position.clone();
  7505. }
  7506. var endTarget = null;
  7507. if (target instanceof Array) {
  7508. endTarget = new Vector3(...target);
  7509. } else if (target.x != null) {
  7510. endTarget = target.clone();
  7511. }
  7512. var startPosition = this.position.clone();
  7513. var startTarget = this.getPivot();
  7514. //const endPosition = position.clone();
  7515. //const endTarget = target.clone();
  7516. var easing = TWEEN.Easing.Quartic.Out;
  7517. if (duration === 0) {
  7518. this.position.copy(endPosition);
  7519. this.lookAt(endTarget);
  7520. } else {
  7521. var value = {
  7522. x: 0
  7523. };
  7524. var tween = new TWEEN.Tween(value).to({
  7525. x: 1
  7526. }, duration);
  7527. tween.easing(easing);
  7528. //this.tweens.push(tween);
  7529. tween.onUpdate(() => {
  7530. var t = value.x;
  7531. //console.log(t);
  7532. var pos = new Vector3((1 - t) * startPosition.x + t * endPosition.x, (1 - t) * startPosition.y + t * endPosition.y, (1 - t) * startPosition.z + t * endPosition.z);
  7533. var target = new Vector3((1 - t) * startTarget.x + t * endTarget.x, (1 - t) * startTarget.y + t * endTarget.y, (1 - t) * startTarget.z + t * endTarget.z);
  7534. this.position.copy(pos);
  7535. this.lookAt(target);
  7536. });
  7537. tween.start();
  7538. tween.onComplete(() => {
  7539. if (callback) {
  7540. callback();
  7541. }
  7542. });
  7543. }
  7544. }
  7545. }
  7546. ;
  7547. var sid = 0;
  7548. class ExtendView extends View {
  7549. constructor() {
  7550. super();
  7551. this.yaw = 0; //Math.PI / 4; // = 4dkk lon + 90
  7552. this._pitch = 0; //-Math.PI / 4; //上下旋转 = 4dkk lat
  7553. this.sid = sid++;
  7554. this.LookTransition = 'LookTransition' + this.sid;
  7555. this.FlyTransition = 'FlyTransition' + this.sid;
  7556. }
  7557. //add------
  7558. applyToCamera(camera) {
  7559. camera.position.copy(this.position);
  7560. camera.rotation.copy(this.rotation);
  7561. camera.updateMatrix();
  7562. camera.updateMatrixWorld();
  7563. //camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
  7564. }
  7565. get rotation() {
  7566. var rotation = new Euler();
  7567. rotation.order = "ZXY";
  7568. rotation.x = Math.PI / 2 + this.pitch;
  7569. rotation.z = this.yaw;
  7570. return rotation;
  7571. }
  7572. set rotation(rotation) {
  7573. if (rotation.y != 0) {
  7574. //因为 rotation的y不一定是0 , 所以不能直接逆着get rotation写。
  7575. //console.error('set rotation y不为0!!!!?', rotation ) //过渡时因为quaternion lerp所以不为0。没办法了orz
  7576. this.direction = new Vector3(0, 0, -1).applyEuler(rotation); //转回direction有损耗,在俯视时的(dir.x==dir.y==0), 丢失yaw信息从而 yaw无法获取(希望不要遇到这种情况,如果有的话,考虑先计算yaw,似乎好像可以算)
  7577. } else {
  7578. //尽量不用direction
  7579. this.pitch = rotation.x - Math.PI / 2;
  7580. this.yaw = rotation.z;
  7581. }
  7582. }
  7583. get quaternion() {
  7584. return new Quaternion().setFromEuler(this.rotation);
  7585. }
  7586. set quaternion(q) {
  7587. this.rotation = new Euler().setFromQuaternion(q);
  7588. }
  7589. copy(a) {
  7590. Common.CopyClassObject(this, a, {
  7591. ignoreList: ['_listeners']
  7592. });
  7593. }
  7594. clone() {
  7595. return Common.CloneClassObject(this, {
  7596. ignoreList: ['_listeners']
  7597. });
  7598. }
  7599. //----------
  7600. setCubeView(dir) {
  7601. switch (dir) {
  7602. case "front":
  7603. this.yaw = 0;
  7604. this.pitch = 0;
  7605. break;
  7606. case "back":
  7607. this.yaw = Math.PI;
  7608. this.pitch = 0;
  7609. break;
  7610. case "left":
  7611. this.yaw = -Math.PI / 2;
  7612. this.pitch = 0;
  7613. break;
  7614. case "right":
  7615. this.yaw = Math.PI / 2;
  7616. this.pitch = 0;
  7617. break;
  7618. case "top":
  7619. this.yaw = 0;
  7620. this.pitch = -Math.PI / 2;
  7621. break;
  7622. case "bottom":
  7623. this.yaw = -Math.PI;
  7624. this.pitch = Math.PI / 2;
  7625. break;
  7626. }
  7627. }
  7628. /* pan (x, y) {
  7629. let dir = new THREE.Vector3(0, 1, 0);
  7630. dir.applyAxisAngle(new THREE.Vector3(1, 0, 0), this.pitch);
  7631. dir.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  7632. // let side = new THREE.Vector3(1, 0, 0);
  7633. // side.applyAxisAngle(new THREE.Vector3(0, 0, 1), this.yaw);
  7634. let side = this.getSide();
  7635. let up = side.clone().cross(dir);
  7636. let pan = side.multiplyScalar(x).add(up.multiplyScalar(y));
  7637. this.position = this.position.add(pan);
  7638. // this.target = this.target.add(pan);
  7639. } */
  7640. pan(x, y) {
  7641. //发现pan其实就是translate
  7642. this.translate(x, 0, y);
  7643. }
  7644. translate(x, y, z, forceHorizon) {
  7645. //相机方向
  7646. var dir = new Vector3(0, 1, 0);
  7647. dir.applyAxisAngle(new Vector3(1, 0, 0), forceHorizon ? 0 : this.pitch); //上下角度
  7648. dir.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //水平角度
  7649. var side = new Vector3(1, 0, 0);
  7650. side.applyAxisAngle(new Vector3(0, 0, 1), this.yaw); //垂直于相机当前水平朝向的 左右方向
  7651. var up = side.clone().cross(dir); //垂直于相机当前水平朝向的 向上方向
  7652. var t = side.multiplyScalar(x) //x影响 左右分量
  7653. .add(dir.multiplyScalar(y)) //y影响 前后分量
  7654. .add(up.multiplyScalar(z)); //z影响 上下分量
  7655. this.position = this.position.add(t);
  7656. if ((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos') {
  7657. this.cancelFlying('pos');
  7658. }
  7659. this.restrictPos();
  7660. }
  7661. translateWorld(x, y, z) {
  7662. super.translateWorld(x, y, z);
  7663. if ((!math.closeTo(x, 0, 1e-2) || !math.closeTo(y, 0, 1e-2) || !math.closeTo(z, 0, 1e-2)) && Potree.settings.displayMode != 'showPanos') {
  7664. this.cancelFlying('pos');
  7665. }
  7666. this.restrictPos();
  7667. }
  7668. restrictPos(position) {
  7669. //add
  7670. if (this.limitBound) {
  7671. (position || this.position).clamp(this.limitBound.min, this.limitBound.max);
  7672. }
  7673. }
  7674. isFlying() {
  7675. var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all';
  7676. var a = transitions.getById(this.FlyTransition).length > 0;
  7677. var b = transitions.getById(this.LookTransition).length > 0;
  7678. return type == 'pos' ? a : type == 'rotate' ? b : a || b;
  7679. }
  7680. cancelFlying() {
  7681. var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'all';
  7682. var dealCancel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  7683. //外界只能通过这个来cancel
  7684. type == 'pos' ? transitions.cancelById(this.FlyTransition, dealCancel) : type == 'rotate' ? transitions.cancelById(this.LookTransition, dealCancel) : (transitions.cancelById(this.FlyTransition, dealCancel), transitions.cancelById(this.LookTransition, dealCancel));
  7685. //console.log('cancelFlying ' , this.sid, type)
  7686. }
  7687. setView() {
  7688. var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  7689. // position, target, duration = 0, callback = null, onUpdate = null, Easing='', cancelFun
  7690. this.cancelFlying();
  7691. var posWaitDone, rotWaitDone, dir;
  7692. var posDone = () => {
  7693. rotWaitDone || done();
  7694. posWaitDone = false;
  7695. };
  7696. var rotDone = () => {
  7697. if (endTarget) {
  7698. this.lookAt(endTarget); //compute radius for orbitcontrol
  7699. } else if (endQuaternion) {
  7700. this.rotation = new Euler().setFromQuaternion(endQuaternion);
  7701. } else if (endYaw != void 0) {
  7702. this.yaw = endYaw, this.pitch = endPitch;
  7703. }
  7704. //if(dir.x == 0 && dir.y == 0)this.yaw = 0 //统一一下 朝上的话是正的。朝下的一般不是0,会保留一个接近0的小数所以不用管
  7705. posWaitDone || done();
  7706. rotWaitDone = false;
  7707. };
  7708. var done = () => {
  7709. //一定要旋转和位移都结束了才能执行
  7710. var f = () => {
  7711. this.position.copy(endPosition); //因为延时1后control的update会导致位置改变
  7712. info.callback && info.callback();
  7713. this.dispatchEvent('flyingDone');
  7714. };
  7715. if (info.duration) {
  7716. setTimeout(f, 1); //延迟是为了使isFlying先为false
  7717. } else {
  7718. f(); //有的需要迅速执行回调
  7719. }
  7720. };
  7721. var endPosition = new Vector3().copy(info.position);
  7722. var startPosition = this.position.clone();
  7723. var startQuaternion,
  7724. endQuaternion,
  7725. endTarget = info.target && new Vector3().copy(info.target),
  7726. endYaw,
  7727. startYaw,
  7728. endPitch,
  7729. startPitch;
  7730. this.restrictPos(endPosition);
  7731. if (info.endYaw == void 0) {
  7732. if (info.target) {
  7733. endQuaternion = math.getQuaFromPosAim(endPosition, endTarget); //若为垂直,会自动偏向x负的方向
  7734. } else if (info.quaternion) {
  7735. endQuaternion = info.quaternion.clone();
  7736. }
  7737. if (endQuaternion && math.closeTo(Math.abs(this.direction.z), 1, 1e-4)) {
  7738. //在垂直的视角下的quaternion刚开始突变的厉害,这时候可能渐变yaw比较好(如俯视时点击测量线)
  7739. var a = this.clone();
  7740. a.quaternion = endQuaternion;
  7741. info.endYaw = a.yaw;
  7742. info.endPitch = a.pitch;
  7743. //console.log('turn to yaw')
  7744. }
  7745. }
  7746. if (info.endYaw != void 0) {
  7747. startPitch = this.pitch;
  7748. endPitch = info.endPitch;
  7749. startYaw = this.yaw;
  7750. endYaw = info.endYaw;
  7751. if (Math.abs(startYaw - endYaw) > Math.PI) {
  7752. //如果差距大于半个圆,就要反个方向转(把大的那个数字减去360度)
  7753. startYaw > endYaw ? startYaw -= Math.PI * 2 : endYaw -= Math.PI * 2;
  7754. }
  7755. //console.log('startYaw', startYaw, 'endYaw', endYaw)
  7756. }
  7757. if (endQuaternion) {
  7758. startQuaternion = this.quaternion;
  7759. }
  7760. if (!info.duration) {
  7761. this.position.copy(endPosition);
  7762. this.restrictPos();
  7763. posWaitDone = true, rotWaitDone = true;
  7764. info.onUpdate && info.onUpdate(1);
  7765. posDone();
  7766. rotDone();
  7767. } else {
  7768. info.onUpdate && info.onUpdate(0); //初始化progress
  7769. var posChange = !this.position.equals(endPosition);
  7770. if (posChange) {
  7771. posWaitDone = true;
  7772. transitions.start(lerp.vector(this.position, endPosition, (pos, progress, delta) => {
  7773. info.onUpdate && info.onUpdate(progress, delta);
  7774. }), info.duration, posDone, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine, null, this.FlyTransition, () => {
  7775. //中途取消
  7776. if (endTarget) {
  7777. /* endPosition = new THREE.Vector3().copy(this.position)//更改旋转的endQuaternion
  7778. endQuaternion = math.getQuaFromPosAim(endPosition,endTarget) */
  7779. //直接改变endQuaternion会突变,所以还是cancel吧
  7780. this.cancelFlying('rotate');
  7781. }
  7782. posWaitDone = false;
  7783. info.cancelFun && info.cancelFun();
  7784. }, info.ignoreFirstFrame);
  7785. }
  7786. if (endQuaternion || endYaw != void 0) {
  7787. rotWaitDone = true;
  7788. transitions.start((progress, delta) => {
  7789. if (endYaw != void 0) {
  7790. this.yaw = startYaw * (1 - progress) + endYaw * progress;
  7791. this.pitch = startPitch * (1 - progress) + endPitch * progress;
  7792. } else {
  7793. var quaternion = new Quaternion().copy(startQuaternion);
  7794. lerp.quaternion(quaternion, endQuaternion)(progress); //在垂直的视角下的角度突变的厉害,这时候可能渐变yaw比较好
  7795. this.quaternion = quaternion;
  7796. //console.log(quaternion,this.yaw)
  7797. }
  7798. posChange || info.onUpdate && info.onUpdate(progress, delta);
  7799. }, info.duration, rotDone, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine, null, this.LookTransition, () => {
  7800. //中途取消
  7801. rotWaitDone = false;
  7802. info.cancelFun && info.cancelFun();
  7803. }, info.ignoreFirstFrame);
  7804. }
  7805. /* transitions.start(lerp.vector(this.position, endPosition, (pos, progress)=>{
  7806. let t = progress
  7807. if(endQuaternion){
  7808. let quaternion = (new THREE.Quaternion()).copy(startQuaternion)
  7809. lerp.quaternion(quaternion, endQuaternion)(progress),
  7810. this.rotation = new THREE.Euler().setFromQuaternion(quaternion)
  7811. }
  7812. this.restrictPos()
  7813. //console.log('setView flying')
  7814. info.onUpdate && info.onUpdate(t)//add
  7815. }), info.duration, done, 0, info.Easing ? easing[info.Easing] : easing.easeInOutSine ,null, this.LookTransition, info.cancelFun); //easeInOutQuad
  7816. */
  7817. }
  7818. }
  7819. //平移Ortho相机
  7820. moveOrthoCamera(viewport, info, duration, easeName) {
  7821. //boundSize优先于endZoom。
  7822. var camera = info.camera || viewport.camera;
  7823. var startZoom = camera.zoom;
  7824. var endPosition = info.endPosition;
  7825. var boundSize = info.boundSize;
  7826. var endZoom = info.endZoom;
  7827. var margin = info.margin || {
  7828. x: 0,
  7829. y: 0
  7830. }; /* 200 */ //像素
  7831. var _onUpdate = info.onUpdate;
  7832. if (info.bound) {
  7833. //需要修改boundSize以适应相机的旋转,当相机不在xy水平面上朝向z时
  7834. endPosition = endPosition || info.bound.getCenter(new Vector3());
  7835. var matrixRot = new Matrix4().makeRotationFromEuler(this.rotation).invert();
  7836. var boundingBox = info.bound.clone().applyMatrix4(matrixRot);
  7837. boundSize = boundingBox.getSize(new Vector3());
  7838. }
  7839. if (boundSize && boundSize.x == 0 && boundSize.y == 0) {
  7840. boundSize.set(1, 1); //避免infinity
  7841. }
  7842. this.setView(Object.assign(info, {
  7843. position: endPosition,
  7844. duration,
  7845. onUpdate: (progress, delta) => {
  7846. if (boundSize || endZoom) {
  7847. if (boundSize) {
  7848. var aspect = boundSize.x / boundSize.y;
  7849. var w, h;
  7850. if (camera.aspect > aspect) {
  7851. //视野更宽则用bound的纵向来决定
  7852. h = boundSize.y;
  7853. endZoom = (viewport.resolution.y - margin.y) / h; //注意,要在resolution不为0时执行
  7854. } else {
  7855. w = boundSize.x;
  7856. endZoom = (viewport.resolution.x - margin.x) / w;
  7857. }
  7858. //onUpdate时更新endzoom是因为画布大小可能更改
  7859. }
  7860. this.zoom = camera.zoom = endZoom * progress + startZoom * (1 - progress); //view里也加一下,有些地方需要记录,如截图
  7861. camera.updateProjectionMatrix();
  7862. _onUpdate && _onUpdate(progress, delta);
  7863. }
  7864. },
  7865. Easing: easeName
  7866. }));
  7867. }
  7868. zoomOrthoCamera(camera, endZoom, pointer, duration, onProgress) {
  7869. //定点缩放
  7870. var startZoom = camera.zoom;
  7871. var pointerPos = new Vector3(pointer.x, pointer.y, 0.5);
  7872. transitions.start(progress => {
  7873. var oldPos = pointerPos.clone().unproject(camera);
  7874. this.zoom = camera.zoom = endZoom * progress + startZoom * (1 - progress);
  7875. camera.updateProjectionMatrix();
  7876. var newPos = pointerPos.clone().unproject(camera);
  7877. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  7878. var moveVec = new Vector3().subVectors(newPos, oldPos);
  7879. camera.position.sub(moveVec);
  7880. this.position.copy(camera.position);
  7881. onProgress && onProgress();
  7882. }, duration, null /* done */, 0, easing.easeInOutSine, null, "zoomInView" /* , info.cancelFun */);
  7883. }
  7884. tranCamera(viewport, info, duration, easeName) {
  7885. viewport.camera = info.midCamera;
  7886. //viewport.camera.matrixWorld = info.endCamera.matrixWorld
  7887. //viewer.setCameraMode(CameraMode.ORTHOGRAPHIC)
  7888. info.midCamera.projectionMatrix.copy(info.startCamera.projectionMatrix);
  7889. var onUpdate = info.onUpdate;
  7890. info.onUpdate = (progress, delta) => {
  7891. lerp.matrix4(info.midCamera.projectionMatrix, info.endCamera.projectionMatrix)(progress);
  7892. onUpdate && onUpdate(progress, delta);
  7893. };
  7894. var callback = info.callback;
  7895. info.callback = () => {
  7896. viewport.camera = info.endCamera;
  7897. viewer.scene.measurements.forEach(e => {
  7898. Potree.Utils.updateVisible(e, 'tranCamera', true);
  7899. });
  7900. this.applyToCamera(viewport.camera);
  7901. viewer.dispatchEvent({
  7902. type: 'camera_changed',
  7903. viewport: viewer.mainViewport,
  7904. changeInfo: {}
  7905. }); //update sprite
  7906. callback && callback();
  7907. };
  7908. //info.forbitCancel = true
  7909. info.camera = info.endCamera;
  7910. if (info.camera.type == "OrthographicCamera") {
  7911. this.moveOrthoCamera(viewport, info, duration, easeName);
  7912. } else {
  7913. this.setView(Object.assign(info, {
  7914. duration
  7915. }));
  7916. }
  7917. }
  7918. }
  7919. ;
  7920. var math = {
  7921. getBaseLog(x, y) {
  7922. //返回以 x 为底 y 的对数(即 logx y) . Math.log 返回一个数的自然对数
  7923. return Math.log(y) / Math.log(x);
  7924. },
  7925. convertVector: {
  7926. ZupToYup: function ZupToYup(e) {
  7927. //navvis -> 4dkk
  7928. return new Vector3(e.x, e.z, -e.y);
  7929. },
  7930. YupToZup: function YupToZup(e) {
  7931. //4dkk -> navvis
  7932. return new Vector3(e.x, -e.z, e.y);
  7933. }
  7934. },
  7935. convertQuaternion: {
  7936. ZupToYup: function ZupToYup(e) {
  7937. //navvis -> 4dkk //不同于convertVisionQuaternion
  7938. var rotation = new Euler(-Math.PI / 2, 0, 0);
  7939. var quaternion = new Quaternion().setFromEuler(rotation);
  7940. return e.clone().premultiply(quaternion);
  7941. //return new THREE.Quaternion(e.x,e.z,-e.y,e.w).multiply((new THREE.Quaternion).setFromAxisAngle(new THREE.Vector3(1,0,0), THREE.Math.degToRad(90)))
  7942. },
  7943. YupToZup: function YupToZup(e) {
  7944. //4dkk -> navvis
  7945. var rotation = new Euler(Math.PI / 2, 0, 0);
  7946. var quaternion = new Quaternion().setFromEuler(rotation);
  7947. return e.clone().premultiply(quaternion);
  7948. }
  7949. },
  7950. convertVisionQuaternion: function convertVisionQuaternion(e) {
  7951. return new Quaternion(e.x, e.z, -e.y, e.w).multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), MathUtils.degToRad(90)));
  7952. },
  7953. invertVisionQuaternion: function invertVisionQuaternion(e) {
  7954. //反转给算法部
  7955. var a = e.clone().multiply(new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), MathUtils.degToRad(-90)));
  7956. return new Quaternion(a.x, -a.z, a.y, a.w);
  7957. },
  7958. //------------
  7959. getVec2Angle: function getVec2Angle(dir1, dir2) {
  7960. return Math.acos(MathUtils.clamp(this.getVec2Cos(dir1, dir2), -1, 1));
  7961. },
  7962. getVec2Cos: function getVec2Cos(dir1, dir2) {
  7963. return dir1.dot(dir2) / dir1.length() / dir2.length();
  7964. },
  7965. getAngle: function getAngle(vec1, vec2) {
  7966. var axis = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'z';
  7967. //带方向的角度 vector3
  7968. if (!vec1.isVector3) {
  7969. vec1 = new Vector3(vec1.x, vec1.y, 0);
  7970. vec2 = new Vector3(vec2.x, vec2.y, 0);
  7971. }
  7972. var angle = vec1.angleTo(vec2);
  7973. var axis_ = vec1.clone().cross(vec2);
  7974. if (typeof axis == 'string') {
  7975. if (axis_[axis] < 0) {
  7976. angle *= -1;
  7977. }
  7978. } else {
  7979. //vector3
  7980. if (axis_.dot(axis) < 0) {
  7981. angle *= -1;
  7982. }
  7983. }
  7984. return angle;
  7985. },
  7986. closeTo: function closeTo(a, b) {
  7987. var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1e-6;
  7988. var f = (a, b) => {
  7989. return Math.abs(a - b) < precision;
  7990. };
  7991. if (typeof a == 'number') {
  7992. return f(a, b);
  7993. } else {
  7994. var judge = name => {
  7995. if (a[name] == void 0) return true; //有值就判断,没值就不判断
  7996. else return f(a[name], b[name]);
  7997. };
  7998. return judge('x') && judge('y') && judge('z') && judge('w');
  7999. }
  8000. },
  8001. toPrecision: function toPrecision(e, t) {
  8002. //xzw change 保留小数
  8003. var f = function f(e, t) {
  8004. var i = Math.pow(10, t);
  8005. return Math.round(e * i) / i;
  8006. };
  8007. if (e instanceof Array) {
  8008. for (var s = 0; s < e.length; s++) {
  8009. e[s] = f(e[s], t);
  8010. }
  8011. return e;
  8012. } else if (e instanceof Object) {
  8013. for (var s in e) {
  8014. e[s] = f(e[s], t);
  8015. }
  8016. return e;
  8017. } else if (typeof e == 'number') {
  8018. return f(e, t);
  8019. } else {
  8020. return e;
  8021. }
  8022. },
  8023. isEmptyQuaternion: function isEmptyQuaternion(e) {
  8024. return 0 === Math.abs(e.x) && 0 === Math.abs(e.y) && 0 === Math.abs(e.z) && 0 === Math.abs(e.w);
  8025. },
  8026. projectPositionToCanvas: function projectPositionToCanvas(e, t, i) {
  8027. i = i || new Vector3(), i.copy(e);
  8028. var r = .5 * $('#player').width(),
  8029. o = .5 * $('#player').height();
  8030. return i.project(t), i.x = i.x * r + r, i.y = -(i.y * o) + o, i;
  8031. },
  8032. handelPadResize: false,
  8033. /* handelPadding : function () { //去除player左边和上面的宽高,因为pc的player左上有其他element 许钟文
  8034. var pads = [];//记录下来避免反复计算
  8035. var index = [];
  8036. var resetPad = function(){
  8037. pads = [];
  8038. index = [];
  8039. math.handelPadResize = false; //switchview时resized为true
  8040. }
  8041. if(config.isEdit && !config.isMobile){
  8042. window.addEventListener('resize',resetPad);
  8043. }
  8044. return function(x, y, domE){
  8045. if(!config.isEdit || config.isMobile) {
  8046. return {
  8047. x: x,
  8048. y: y
  8049. }
  8050. }
  8051. if(this.handelPadResize)resetPad();
  8052. domE = domE || $('#player')[0];
  8053. var pad;
  8054. var i = index.indexOf(domE);
  8055. if (i == -1){
  8056. index.push(domE);
  8057. pad = {
  8058. x: this.getOffset("left", domE),
  8059. y: this.getOffset("top", domE)
  8060. }
  8061. pads.push(pad)
  8062. }
  8063. else pad = pads[i];
  8064. return {
  8065. x: x - pad.x,
  8066. y: y - pad.y
  8067. }
  8068. }
  8069. }(), */
  8070. getOffset: function getOffset(type, element, parent) {
  8071. //获取元素的边距 许钟文
  8072. var offset = type == "left" ? element.offsetLeft : element.offsetTop;
  8073. if (!parent) parent = $("body")[0];
  8074. while (element = element.offsetParent) {
  8075. if (element == parent) break;
  8076. offset += type == "left" ? element.offsetLeft : element.offsetTop;
  8077. }
  8078. return offset;
  8079. },
  8080. constrainedTurn: function constrainedTurn(e) {
  8081. var t = e % (2 * Math.PI);
  8082. return t = t > Math.PI ? t -= 2 * Math.PI : t < -Math.PI ? t += 2 * Math.PI : t;
  8083. },
  8084. getFOVDotThreshold: function getFOVDotThreshold(e) {
  8085. return Math.cos(MathUtils.degToRad(e / 2));
  8086. },
  8087. transform2DForwardVectorByCubeFace: function transform2DForwardVectorByCubeFace(e, t, i, n) {
  8088. switch (e) {
  8089. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  8090. i.set(1, t.y, t.x);
  8091. break;
  8092. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  8093. i.set(-1, t.y, -t.x);
  8094. break;
  8095. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  8096. i.set(-t.x, 1, -t.y);
  8097. break;
  8098. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  8099. i.set(-t.x, -1, t.y);
  8100. break;
  8101. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  8102. i.set(-t.x, t.y, 1);
  8103. break;
  8104. case GLCubeFaces.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  8105. i.set(t.x, t.y, -1);
  8106. }
  8107. n && i.normalize();
  8108. },
  8109. getFootPoint: function getFootPoint(oldPos, p1, p2, restricInline) {
  8110. //找oldPos在线段p1, p2上的垂足
  8111. /* if(isWorld){//输出全局坐标 需要考虑meshGroup.position
  8112. p1 = p1.clone();
  8113. p2 = p2.clone();
  8114. p1.y += mainDesign.meshGroup.position.y;
  8115. p2.y += mainDesign.meshGroup.position.y;
  8116. } */
  8117. if (p1.equals(p2)) return p1.clone();
  8118. var op1 = oldPos.clone().sub(p1);
  8119. var p1p2 = p1.clone().sub(p2);
  8120. var p1p2Len = p1p2.length();
  8121. var leftLen = op1.dot(p1p2) / p1p2Len;
  8122. var pos = p1.clone().add(p1p2.multiplyScalar(leftLen / p1p2Len));
  8123. if (restricInline && pos.clone().sub(p1).dot(pos.clone().sub(p2)) > 0) {
  8124. //foot不在线段上
  8125. if (pos.distanceTo(p1) < pos.distanceTo(p2)) pos = p1.clone();else pos = p2.clone();
  8126. }
  8127. return pos;
  8128. },
  8129. /**
  8130. * 计算多边形的重心
  8131. * @param {*} points
  8132. */
  8133. getCenterOfGravityPoint: function getCenterOfGravityPoint(mPoints) {
  8134. var area = 0.0; //多边形面积
  8135. var Gx = 0.0,
  8136. Gy = 0.0; // 重心的x、y
  8137. for (var i = 1; i <= mPoints.length; i++) {
  8138. var ix = mPoints[i % mPoints.length].x;
  8139. var iy = mPoints[i % mPoints.length].y;
  8140. var nx = mPoints[i - 1].x;
  8141. var ny = mPoints[i - 1].y;
  8142. var temp = (ix * ny - iy * nx) / 2.0;
  8143. area += temp;
  8144. Gx += temp * (ix + nx) / 3.0;
  8145. Gy += temp * (iy + ny) / 3.0;
  8146. }
  8147. Gx = Gx / area;
  8148. Gy = Gy / area;
  8149. return {
  8150. x: Gx,
  8151. y: Gy
  8152. };
  8153. },
  8154. getBound: function getBound(ring) {
  8155. var bound = new Box2();
  8156. for (var j = 0, len = ring.length; j < len; j++) {
  8157. bound.expandByPoint(ring[j]);
  8158. }
  8159. return bound;
  8160. },
  8161. isPointInArea: function isPointInArea(ring, holes, point, ifAtLine) {
  8162. //判断点是否在某个环内, 若传递了holes代表还要不能在内环内
  8163. var bound = this.getBound(ring);
  8164. if (point.x < bound.min.x || point.x > bound.max.x || point.y < bound.min.y || point.y > bound.max.y) return false;
  8165. var inside = false;
  8166. var x = point.x,
  8167. y = point.y;
  8168. for (var i = 0, j = ring.length - 1; i < ring.length; j = i++) {
  8169. var xi = ring[i].x,
  8170. yi = ring[i].y;
  8171. var xj = ring[j].x,
  8172. yj = ring[j].y;
  8173. if ((xi - x) * (yj - y) == (xi - x) * (yi - y) && x >= Math.min(xi, xj) && x <= Math.max(xi, xj) //xzw add
  8174. && y >= Math.min(yi, yj) && y <= Math.max(yi, yj)) {
  8175. //return !!ifAtLine;//在线段上,则判断为…… (默认在外)
  8176. return {
  8177. atLine: true
  8178. };
  8179. }
  8180. if (yi > y != yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi) {
  8181. inside = !inside;
  8182. }
  8183. }
  8184. if (inside && holes) {
  8185. return !holes.some(ring => this.isPointInArea(ring, null, point, ifAtLine)); //不能存在于任何一个二级内环内
  8186. } else {
  8187. return inside;
  8188. }
  8189. },
  8190. getArea: function getArea(ring) {
  8191. //求面积 顺时针为正 来自three shape
  8192. for (var t = ring.length, i = 0, n = t - 1, r = 0; r < t; n = r++) i += ring[n].x * ring[r].y - ring[r].x * ring[n].y;
  8193. return -.5 * i;
  8194. },
  8195. getVolume: function getVolume(faceArr) {//求三角多面体的体积。和求面积同理都用鞋带计算法 https://blog.csdn.net/weixin_43414513/article/details/123758897
  8196. //问题:怎么确定方向
  8197. //每个三角形的顺序必须是右手螺旋法则指向物体外(外向里看为逆时针),分别为ABC,则每个三角形和原点O构成的三棱锥体积为 (OA cross OB) dot(OC) / 6 . 结果一般朝向原点的为负,反之为正
  8198. },
  8199. isInBetween: function isInBetween(a, b, c, precision) {
  8200. // 如果b几乎等于a或c,返回false.为了避免浮点运行时两值几乎相等,但存在相差0.00000...0001的这种情况出现使用下面方式进行避免
  8201. /* if (Math.abs(a - b) < 0.000001 || Math.abs(b - c) < 0.000001) {
  8202. return false;
  8203. }
  8204. return (a <= b && b <= c) || (c <= b && b <= a);*/
  8205. //更改:如果b和a或c中一个接近 就算在a和c之间
  8206. return a <= b && b <= c || c <= b && b <= a || this.closeTo(a, b, precision) || this.closeTo(b, c, precision);
  8207. },
  8208. ifPointAtLineBound: function ifPointAtLineBound(point, linePoints, precision) {
  8209. //待验证 横线和竖线比较特殊
  8210. return math.isInBetween(linePoints[0].x, point.x, linePoints[1].x, precision) && math.isInBetween(linePoints[0].y, point.y, linePoints[1].y, precision);
  8211. },
  8212. isLineIntersect: function isLineIntersect(line1, line2, notSegment, precision) {
  8213. //线段和线段是否有交点. notSegment代表是直线而不是线段
  8214. var a1 = line1[1].y - line1[0].y;
  8215. var b1 = line1[0].x - line1[1].x;
  8216. var c1 = a1 * line1[0].x + b1 * line1[0].y;
  8217. //转换成一般式: Ax+By = C
  8218. var a2 = line2[1].y - line2[0].y;
  8219. var b2 = line2[0].x - line2[1].x;
  8220. var c2 = a2 * line2[0].x + b2 * line2[0].y;
  8221. // 计算交点
  8222. var d = a1 * b2 - a2 * b1;
  8223. // 当d==0时,两线平行
  8224. if (d == 0) {
  8225. return false;
  8226. } else {
  8227. var x = (b2 * c1 - b1 * c2) / d;
  8228. var y = (a1 * c2 - a2 * c1) / d;
  8229. // 检测交点是否在两条线段上
  8230. /* if (notSegment || (isInBetween(line1[0].x, x, line1[1].x) || isInBetween(line1[0].y, y, line1[1].y)) &&
  8231. (isInBetween(line2[0].x, x, line2[1].x) || isInBetween(line2[0].y, y, line2[1].y))) {
  8232. return {x,y};
  8233. } */
  8234. if (notSegment || math.ifPointAtLineBound({
  8235. x,
  8236. y
  8237. }, line1, precision) && math.ifPointAtLineBound({
  8238. x,
  8239. y
  8240. }, line2, precision)) {
  8241. return {
  8242. x,
  8243. y
  8244. };
  8245. }
  8246. }
  8247. },
  8248. getNormal2d: function getNormal2d() {
  8249. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  8250. //获取二维法向量 方向向内
  8251. var x, y, x1, y1;
  8252. //line2d的向量
  8253. if (o.vec) {
  8254. x1 = o.vec.x;
  8255. y1 = o.vec.y;
  8256. } else {
  8257. x1 = o.p1.x - o.p2.x;
  8258. y1 = o.p1.y - o.p2.y;
  8259. }
  8260. //假设法向量的x或y固定为1或-1
  8261. if (y1 != 0) {
  8262. x = 1;
  8263. y = -(x1 * x) / y1;
  8264. } else if (x1 != 0) {
  8265. //y如果为0,正常情况x不会是0
  8266. y = 1;
  8267. x = -(y1 * y) / x1;
  8268. } else {
  8269. console.log("两个点一样");
  8270. return null;
  8271. }
  8272. //判断方向里或者外:
  8273. var vNormal = new Vector3(x, 0, y);
  8274. var vLine = new Vector3(x1, 0, y1);
  8275. var vDir = vNormal.cross(vLine);
  8276. if (vDir.y > 0) {
  8277. x *= -1;
  8278. y *= -1;
  8279. }
  8280. return new Vector2(x, y).normalize();
  8281. },
  8282. getQuaBetween2Vector: function getQuaBetween2Vector(oriVec, newVec, upVec) {
  8283. //获取从oriVec旋转到newVec可以应用的quaternion
  8284. var angle = oriVec.angleTo(newVec);
  8285. var axis = oriVec.clone().cross(newVec).normalize(); //两个up之间
  8286. if (axis.length() == 0) {
  8287. //当夹角为180 或 0 度时,得到的axis为(0,0,0),故使用备用的指定upVec
  8288. return new Quaternion().setFromAxisAngle(upVec, angle);
  8289. }
  8290. return new Quaternion().setFromAxisAngle(axis, angle);
  8291. },
  8292. /*
  8293. getQuaBetween2Vector2 : function(oriVec, newVec ){//not camera
  8294. var _ = (new THREE.Matrix4).lookAt( oriVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  8295. var aimQua = (new THREE.Quaternion).setFromRotationMatrix(_)
  8296. var _2 = (new THREE.Matrix4).lookAt( newVec, new THREE.Vector3, new THREE.Vector3(0,1,0))
  8297. var aimQua2 = (new THREE.Quaternion).setFromRotationMatrix(_2)
  8298. return aimQua2.multiply(aimQua.clone().inverse())
  8299. } */
  8300. getQuaByAim: function getQuaByAim(aim) {
  8301. var center = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3();
  8302. var forward = new Vector3(0, 1, 0);
  8303. var qua1 = new Quaternion().setFromUnitVectors(forward, aim.clone().sub(center).normalize());
  8304. /* var _ = (new THREE.Matrix4).lookAt(center,aim, new THREE.Vector3(0,1,0));
  8305. let qua2 = (new THREE.Quaternion).setFromRotationMatrix(_);
  8306. let rot1 = new THREE.Euler().setFromQuaternion(qua1)
  8307. let rot2 = new THREE.Euler().setFromQuaternion(qua2) //奇怪,qua2怎么都不对
  8308. console.log(rot1,rot2) */
  8309. return qua1;
  8310. },
  8311. getAimByQua: function getAimByQua(quaternion) {
  8312. var center = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Vector3();
  8313. return new Vector3(0, 0, -1).applyQuaternion(quaternion).add(center);
  8314. },
  8315. getScaleForConstantSize: function () {
  8316. //获得规定二维大小的mesh的scale值。可以避免因camera的projection造成的mesh视觉大小改变。 来源:tag.updateDisc
  8317. var w;
  8318. var i = new Vector3(),
  8319. o = new Vector3(),
  8320. l = new Vector3(),
  8321. c = new Vector3(),
  8322. h = new Vector3();
  8323. return function () {
  8324. var op = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  8325. if (op.width2d) w = op.width2d; //如果恒定二维宽度
  8326. else {
  8327. //否则考虑上距离,加一丢丢近大远小的效果
  8328. var currentDis, nearBound, farBound;
  8329. if (op.camera.type == "OrthographicCamera") {
  8330. currentDis = 200 / op.camera.zoom; //(op.camera.right - op.camera.left) / op.camera.zoom
  8331. } else {
  8332. currentDis = op.position.distanceTo(op.camera.position);
  8333. }
  8334. w = op.maxSize - (op.maxSize - op.minSize) * MathUtils.smoothstep(currentDis, op.nearBound, op.farBound);
  8335. //maxSize : mesh要表现的最大像素宽度; nearBound: 最近距离,若比nearBound近,则使用maxSize
  8336. }
  8337. i.copy(op.position).project(op.camera); //tag中心在屏幕上的二维坐标
  8338. o.set(op.resolution.x / 2, op.resolution.y / 2, 1).multiply(i); //转化成px -w/2 到 w/2的范围
  8339. l.set(w / 2, 0, 0).add(o); //加上tag宽度的一半
  8340. c.set(2 / op.resolution.x, 2 / op.resolution.y, 1).multiply(l); //再转回 -1 到 1的范围
  8341. h.copy(c).unproject(op.camera); //再转成三维坐标,求得tag边缘的位置
  8342. var g = h.distanceTo(op.position); //就能得到tag的三维半径
  8343. //这里使用的都是resolution2, 好处是手机端不会太小, 坏处是pc更改网页显示百分比时显示的大小会变(或许可以自己算出设备真实的deviceRatio, 因window.screen是不会改变的),但考虑到用户可以自行调节字大小也许是好的
  8344. return g; //可能NAN 当相机和position重叠时
  8345. };
  8346. }(),
  8347. //W , H, left, top分别是rect的宽、高、左、上
  8348. getCrossPointAtRect: function getCrossPointAtRect(p1, aim, W, H, left, top) {
  8349. //求射线p1-aim在rect边界上的交点,其中aim在rect范围内,p1则不一定(交点在aim这边的延长线上)
  8350. var x, y, borderX;
  8351. var r = (aim.x - p1.x) / (aim.y - p1.y); //根据相似三角形原理先求出这个比值
  8352. var getX = function getX(y) {
  8353. return r * (y - p1.y) + p1.x;
  8354. };
  8355. var getY = function getY(x) {
  8356. return 1 / r * (x - p1.x) + p1.y;
  8357. };
  8358. if (aim.x >= p1.x) {
  8359. borderX = W + left;
  8360. } else {
  8361. borderX = left;
  8362. }
  8363. x = borderX;
  8364. y = getY(x);
  8365. if (y < top || y > top + H) {
  8366. if (y < top) {
  8367. y = top;
  8368. } else {
  8369. y = top + H;
  8370. }
  8371. x = getX(y);
  8372. }
  8373. return new Vector2(x, y);
  8374. },
  8375. getDirFromUV: function getDirFromUV(uv) {
  8376. //获取dir 反向计算 - - 二维转三维比较麻烦
  8377. var dirB; //所求 单位向量
  8378. var y = Math.cos(uv.y * Math.PI); //uv中纵向可以直接确定y, 根据上面getUVfromDir的反向计算
  8379. // 故 uv.y * Math.PI 就是到垂直线(向上)的夹角
  8380. var angle = 2 * Math.PI * uv.x - Math.PI; //x/z代表的是角度
  8381. var axisX, axisZ; //axis为1代表是正,-1是负数
  8382. if (-Math.PI <= angle && angle < 0) {
  8383. axisX = -1; //下半圆
  8384. } else {
  8385. axisX = 1; //上半圆
  8386. }
  8387. if (-Math.PI / 2 <= angle && angle < Math.PI / 2) {
  8388. axisZ = 1; //右半圆
  8389. } else {
  8390. axisZ = -1; //左半圆
  8391. }
  8392. var XDivideZ = Math.tan(angle);
  8393. var z = Math.sqrt((1 - y * y) / (1 + XDivideZ * XDivideZ));
  8394. var x = XDivideZ * z;
  8395. if (z * axisZ < 0) {
  8396. //异号
  8397. z *= -1;
  8398. x *= -1;
  8399. if (x * axisX < 0) {
  8400. // console.log("wrong!!!!!??????????")
  8401. }
  8402. }
  8403. x *= -1; //计算完成后这里不能漏掉 *= -1
  8404. dirB = this.convertVector.YupToZup(new Vector3(x, y, z));
  8405. //理想状态下x和z和anotherDir相同
  8406. return dirB;
  8407. },
  8408. getUVfromDir: function getUVfromDir(dir) {
  8409. //获取UV 同shader里的计算
  8410. var dir = this.convertVector.ZupToYup(dir);
  8411. dir.x *= -1; //计算前这里不能漏掉 *= -1 见shader
  8412. var tx = Math.atan2(dir.x, dir.z) / (Math.PI * 2.0) + 0.5; //atan2(y,x) 返回从 X 轴正向逆时针旋转到点 (x,y) 时经过的角度。区间是-PI 到 PI 之间的值
  8413. var ty = Math.acos(dir.y) / Math.PI;
  8414. return new Vector2(tx, ty);
  8415. //理想状态下tx相同
  8416. },
  8417. getDirByLonLat: function getDirByLonLat(lon, lat) {
  8418. var dir = new Vector3();
  8419. var phi = MathUtils.degToRad(90 - lat);
  8420. var theta = MathUtils.degToRad(lon);
  8421. dir.x = Math.sin(phi) * Math.cos(theta);
  8422. dir.y = Math.cos(phi);
  8423. dir.z = Math.sin(phi) * Math.sin(theta);
  8424. return dir;
  8425. } //0,0 => (1,0,0) 270=>(0,0,-1)
  8426. ,
  8427. projectPointAtPlane: function projectPointAtPlane() {
  8428. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  8429. //获取一个点在一个面上的投影 {facePoints:[a,b,c], point:}
  8430. var plane = new Plane().setFromCoplanarPoints(...o.facePoints);
  8431. return plane.projectPoint(o.point, new Vector3());
  8432. },
  8433. getPolygonsMixedRings: function getPolygonsMixedRings(polygons, onlyGetOutRing) {
  8434. //{points:[vector2,...],holes:[[],[]]}
  8435. var points = [];
  8436. var lines = [];
  8437. var i = 0;
  8438. polygons.forEach(e => points.push(...e.map(a => new Vector2().copy(a))));
  8439. polygons.forEach((ps, j) => {
  8440. var length = ps.length;
  8441. var index = 0;
  8442. while (index < length) {
  8443. lines.push({
  8444. p1: index + i,
  8445. p2: (index + 1) % length + i
  8446. });
  8447. index++;
  8448. }
  8449. i += length;
  8450. });
  8451. points.forEach((p, j) => {
  8452. p.id = j;
  8453. });
  8454. var rings = searchRings({
  8455. points,
  8456. lines,
  8457. onlyGetOutRing
  8458. });
  8459. //console.log(rings)
  8460. rings = rings.filter(e => e.closetParent == void 0); // 子环不加,被外环包含了
  8461. return rings;
  8462. },
  8463. getQuaFromPosAim(position, target) {
  8464. /* let matrix = (new THREE.Matrix4).lookAt(position, target, new THREE.Vector3(0,0,1)) //这里垂直的话会默认给一个右向所以不这么写
  8465. return (new THREE.Quaternion).setFromRotationMatrix(matrix) */
  8466. var view = new ExtendView();
  8467. view.direction = new Vector3().subVectors(target, position);
  8468. return view.quaternion;
  8469. },
  8470. getBoundByPoints(points, minSize) {
  8471. var bound = new Box3();
  8472. points.forEach(point => {
  8473. bound.expandByPoint(point);
  8474. });
  8475. var center = bound.getCenter(new Vector3());
  8476. if (minSize) {
  8477. var minBound = new Box3().setFromCenterAndSize(center, minSize);
  8478. bound.union(minBound);
  8479. }
  8480. return {
  8481. bounding: bound,
  8482. size: bound.getSize(new Vector3()),
  8483. center
  8484. };
  8485. },
  8486. /* linearClamp(value, x1,x2, y1, y2){//x为bound.min, bound.max
  8487. value = THREE.Math.clamp(value, x1,x2)
  8488. return y1 + ( y2 - y1) * (value - x1) / (x2 - x1)
  8489. } */
  8490. linearClamp(value, xArr, yArr) {
  8491. //xArr需要按顺序从小到大,yArr对应xArr中的值
  8492. var len = xArr.length;
  8493. if (value <= xArr[0]) return yArr[0];
  8494. if (value >= xArr[len - 1]) return yArr[len - 1];
  8495. var i = 0;
  8496. while (++i < len) {
  8497. if (value < xArr[i]) {
  8498. var x1 = xArr[i - 1],
  8499. x2 = xArr[i],
  8500. y1 = yArr[i - 1],
  8501. y2 = yArr[i];
  8502. value = y1 + (y2 - y1) * (value - x1) / (x2 - x1);
  8503. break;
  8504. }
  8505. }
  8506. return value;
  8507. }
  8508. };
  8509. /*
  8510. 如何将若干个点拟合出线段
  8511. // 假设你有一个点数组,每个点表示为一个包含x和y坐标的对象
  8512. const points = [
  8513. { x: 1, y: 2 },
  8514. { x: 2, y: 3 },
  8515. { x: 3, y: 4 },
  8516. { x: 4, y: 5 },
  8517. // ... 更多点
  8518. ];
  8519. // 定义用于计算最小二乘法参数的函数
  8520. function leastSquares( ) {
  8521. let sumX = 0;
  8522. let sumY = 0;
  8523. let sumXY = 0;
  8524. let sumX2 = 0;
  8525. let n = points.length;
  8526. for (const point of points) {
  8527. sumX += point.x;
  8528. sumY += point.y;
  8529. sumXY += point.x * point.y;
  8530. sumX2 += point.x * point.x;
  8531. }
  8532. const k = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX); //不知道为何这样算,自己解不出来(使点到直线距离之和平方最小),但测了下似乎是准的
  8533. const b = (sumY - k * sumX) / n;
  8534. return { k, b };
  8535. }
  8536. // 使用上述函数计算拟合直线的参数
  8537. const { k, b } = leastSquares(points);
  8538. // 现在你可以使用这些参数来表示拟合出的线段
  8539. console.log(`拟合线段的方程为: y = ${k}x + ${b}`);
  8540. */
  8541. Potree.math = math;
  8542. function mobileVersion(e, t) {
  8543. //ios的版本
  8544. var i = window.navigator.userAgent,
  8545. n = i.match(e);
  8546. return n = n ? n[1].split(t) : [], {
  8547. major: parseInt(n[0]) || 0,
  8548. minor: parseInt(n[1]) || 0,
  8549. patch: parseInt(n[2]) || 0
  8550. };
  8551. }
  8552. var browser = {
  8553. isFullscreen: function isFullscreen() {
  8554. return document.fullscreenElement || document.mozFullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement || document.msFullscreenElement;
  8555. },
  8556. supportsFullscreen: function supportsFullscreen() {
  8557. return document.fullscreenEnabled || document.mozFullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled || document.msFullscreenEnabled;
  8558. },
  8559. isPointerLocked: function isPointerLocked() {
  8560. return document.pointerLockElement || document.mozPointerLockElement || document.webkitPointerLockElement;
  8561. },
  8562. requestFullscreen: function requestFullscreen(dom, t) {
  8563. dom.requestFullscreen ? dom.requestFullscreen() : dom.mozRequestFullScreen ? dom.mozRequestFullScreen() : dom.webkitRequestFullscreen ? dom.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT) : dom.msRequestFullscreen && dom.msRequestFullscreen(), t && $(document).on("fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange", browser.requestPointerLock);
  8564. },
  8565. requestPointerLock: function requestPointerLock() {
  8566. var e;
  8567. if (document.fullscreenElement) e = document.fullscreenElement();else if (document.mozFullscreenElement) e = document.mozFullscreenElement();else if (document.mozFullScreenElement) e = document.mozFullScreenElement();else {
  8568. if (!document.webkitFullscreenElement) return;
  8569. e = document.webkitFullscreenElement();
  8570. }
  8571. ;
  8572. e.requestPointerLock = e.requestPointerLock || e.mozRequestPointerLock || e.webkitRequestPointerLock, e.requestPointerLock(), $(document).off("fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange", this);
  8573. },
  8574. exitPointerLock: function exitPointerLock() {
  8575. ;
  8576. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock, document.exitPointerLock();
  8577. },
  8578. exitFullscreen: function exitFullscreen() {
  8579. document.exitFullscreen ? document.exitFullscreen() : document.msExitFullscreen ? document.msExitFullscreen() : document.mozCancelFullScreen ? document.mozCancelFullScreen() : document.webkitExitFullscreen && document.webkitExitFullscreen();
  8580. },
  8581. details: function details() {
  8582. var e = navigator.userAgent.match("(Firefox|Chrome|Safari)/([\\d]+)");
  8583. return e ? {
  8584. name: e[1],
  8585. version: parseInt(e[2]),
  8586. platform: navigator.platform
  8587. } : {};
  8588. },
  8589. is: function is(e) {
  8590. return this.details() && this.details().name === e;
  8591. },
  8592. inIframe: function inIframe() {
  8593. return window.parent !== window;
  8594. },
  8595. aspectRatio: function aspectRatio($elem) {
  8596. $elem = $elem || $("#player");
  8597. var e = $elem.width() / $elem.height();
  8598. return isFinite(e) ? e : 0;
  8599. },
  8600. userAgent: function userAgent() {
  8601. return window.navigator.userAgent;
  8602. },
  8603. isMobile: function isMobile() {
  8604. var e = navigator.userAgent || navigator.vendor || window.opera;
  8605. return /(android|bb\d+|meego).+mobile|android|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0, 4));
  8606. },
  8607. isLandscape: function isLandscape() {
  8608. return this.isMobile && this.aspectRatio() > 1;
  8609. },
  8610. isSmallScreen: function isSmallScreen() {
  8611. var e = screen.width / window.devicePixelRatio;
  8612. return e < 240;
  8613. },
  8614. detectIE: function detectIE() {
  8615. var e = window.navigator.userAgent,
  8616. t = e.indexOf("MSIE ");
  8617. return t !== -1 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
  8618. },
  8619. detectSafari: function detectSafari() {
  8620. var e = window.navigator.userAgent,
  8621. t = e.indexOf("Safari");
  8622. return t !== -1 && !this.detectOpera() && !this.detectChrome(); //xzw add detectOpera
  8623. },
  8624. detectFirefox: function detectFirefox() {
  8625. var e = window.navigator.userAgent;
  8626. return e.indexOf("Firefox") !== -1;
  8627. },
  8628. detectChrome: function detectChrome() {
  8629. var e = window.navigator.userAgent;
  8630. return e.indexOf("Chrome") !== -1 && !this.detectOpera();
  8631. },
  8632. detectOpera: function detectOpera() {
  8633. var e = window.navigator.userAgent;
  8634. return e.indexOf("OPR") !== -1;
  8635. },
  8636. detectIOS: function detectIOS() {
  8637. return this.detectIPhone() || this.detectIPad() || this.detectIPod();
  8638. },
  8639. detectIPad: function detectIPad() {
  8640. var e = window.navigator.userAgent,
  8641. t = /iPad/;
  8642. return t.test(e);
  8643. },
  8644. detectIPod: function detectIPod() {
  8645. var e = window.navigator.userAgent,
  8646. t = /iPod/;
  8647. return t.test(e);
  8648. },
  8649. detectIPhone: function detectIPhone() {
  8650. var e = window.navigator.userAgent,
  8651. t = /iPhone/;
  8652. return t.test(e);
  8653. },
  8654. detectAndroid: function detectAndroid() {
  8655. var e = window.navigator.userAgent;
  8656. return e.indexOf("Android") !== -1;
  8657. },
  8658. detectAndroidMobile: function detectAndroidMobile() {
  8659. var e = window.navigator.userAgent;
  8660. return this.detectAndroid() && e.indexOf("Mobile") !== -1;
  8661. },
  8662. detectSamsungNative: function detectSamsungNative() {
  8663. var e = window.navigator.userAgent;
  8664. return e.indexOf("SM-G900H") !== -1 || e.indexOf("GT-I9500") !== -1 || e.indexOf("SM-N900") !== -1;
  8665. },
  8666. detectSamsungS6: function detectSamsungS6() {
  8667. var e = window.navigator.userAgent;
  8668. return e.indexOf("SM-G92") !== -1;
  8669. },
  8670. /************************************************************徐世廷*************************************************************/
  8671. detectHUAWEI5X: function detectHUAWEI5X() {
  8672. return -1 !== window.navigator.userAgent.indexOf("KIW-TL00H");
  8673. },
  8674. /*******************************************************************************************************************************/
  8675. detectWebVR: function detectWebVR() {
  8676. return !(!window.navigator.getVRDisplays || !window.VRDisplay);
  8677. },
  8678. getVRDisplay: function getVRDisplay() {
  8679. var e = $.Deferred();
  8680. return this.detectWebVR() ? (navigator.getVRDisplays().then(function (t) {
  8681. t.length >= 1 && e.resolve(t[0]), e.reject(null);
  8682. }), e) : e.reject(null);
  8683. },
  8684. iosVersion: function iosVersion() {
  8685. if (!this.detectIOS()) throw new DeviceMismatchException("Did not detect an iDevice");
  8686. var e = /((?:\d+\_?){1,3}) like Mac OS/,
  8687. t = "_";
  8688. return mobileVersion(e, t);
  8689. },
  8690. androidVersion: function androidVersion() {
  8691. if (!this.detectAndroid()) throw new DeviceMismatchException("Did not detect an Android based device");
  8692. var e = /Android ((?:\d+\.?){1,3})/,
  8693. t = ".";
  8694. return mobileVersion(e, t);
  8695. },
  8696. valueFromCookie: function valueFromCookie(e, t) {
  8697. var i = new RegExp(e + "=([0-9a-f]+)(; ?|$)").exec(document.cookie);
  8698. if (!i) return t;
  8699. var n = i[1];
  8700. return "boolean" == typeof t ? "true" === n || "1" === n : "number" == typeof t ? parseFloat(n) : n;
  8701. },
  8702. valueFromHash: function valueFromHash(e, t) {
  8703. var i = new RegExp("[#&?]" + e + "=([^#&?]*)"),
  8704. n = i.exec(window.location.href);
  8705. if (!n) return t;
  8706. var r = n[1];
  8707. return "boolean" == typeof t ? "true" === r || "1" === r : "number" == typeof t ? parseFloat(r) : window.decodeURIComponent(r);
  8708. },
  8709. //-------许钟文:-------------------------------------------------
  8710. getProjectNum: function getProjectNum() {
  8711. //获取场景projectNum
  8712. if (window.__ProjectNum && window.__ProjectNum != "__ProjectNum__") {
  8713. return window.__ProjectNum;
  8714. }
  8715. var number = window.location.href.substring(window.location.href.indexOf("=") + 1);
  8716. if (number.indexOf("&") != -1) {
  8717. number = number.substring(0, number.indexOf("&"));
  8718. }
  8719. if (number.indexOf("#") != -1) {
  8720. number = number.substring(0, number.indexOf("#"));
  8721. }
  8722. return number;
  8723. },
  8724. urlHasValue: function urlHasValue(key, isGetValue) {
  8725. var querys = window.location.search.substr(1).split("&");
  8726. if (isGetValue) {
  8727. for (var i = 0; i < querys.length; i++) {
  8728. var keypair = querys[i].split("=");
  8729. if (keypair.length === 2 && keypair[0] === key) {
  8730. return keypair[1];
  8731. }
  8732. }
  8733. return "";
  8734. } else {
  8735. for (var _i = 0; _i < querys.length; _i++) {
  8736. var _keypair = querys[_i].split("=");
  8737. if (_keypair[0] == key) {
  8738. return true;
  8739. }
  8740. }
  8741. return false;
  8742. }
  8743. },
  8744. /**
  8745. * 获取查询参数的值
  8746. * @param {String} key
  8747. * @returns String
  8748. */
  8749. urlQueryValue(key) {
  8750. return this.urlHasValue(key, true) || "";
  8751. },
  8752. /**
  8753. * 判断是否存在hash
  8754. * @param {String} key
  8755. * @returns Boolean
  8756. */
  8757. urlIsHasHash(key) {
  8758. var querys = window.location.hash.substr(1).replace('/?', '').split("&");
  8759. return querys.includes(key);
  8760. },
  8761. islongPhone: function islongPhone() {
  8762. //是否是刘海全面屏幕 仅仅根据比例判断 - -
  8763. //screen.height == 812 && screen.width == 375)
  8764. var r = screen.height / screen.width; //可能横屏
  8765. return this.isMobile() && (r > 1.99 || r < 0.502512); //18/9=2.165 //???
  8766. },
  8767. detectWeixin: function detectWeixin() {
  8768. //微信 包括PC的微信
  8769. return window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger";
  8770. },
  8771. detectWeixinMiniProgram: function detectWeixinMiniProgram() {
  8772. return window.navigator.userAgent.match("miniProgram");
  8773. },
  8774. detectEdge: function detectEdge() {
  8775. return window.navigator.userAgent.indexOf("Edge") > -1;
  8776. },
  8777. detectApp: function detectApp() {
  8778. return this.urlHasValue("app");
  8779. },
  8780. /**
  8781. * 判断标签页是否切换状态
  8782. */
  8783. isTabHidden: function isTabHidden() {
  8784. var prefixes = ["webkit", "moz", "ms", "o"];
  8785. if ("hidden" in document) return document.hidden;
  8786. for (var i = 0; i < prefixes.length; i++) {
  8787. if (prefixes[i] + "Hidden" in document) return document[prefixes[i] + "Hidden"];
  8788. }
  8789. return false;
  8790. }
  8791. };
  8792. WebGLRenderer.prototype.paramThreeToGL = function (e) {
  8793. var t,
  8794. i = this.extensions,
  8795. r = this.getContext(); //context;
  8796. if (e === RepeatWrapping) return r.REPEAT;
  8797. if (e === ClampToEdgeWrapping) return r.CLAMP_TO_EDGE;
  8798. if (e === MirroredRepeatWrapping) return r.MIRRORED_REPEAT;
  8799. if (e === NearestFilter) return r.NEAREST;
  8800. if (e === NearestMipMapNearestFilter) return r.NEAREST_MIPMAP_NEAREST;
  8801. if (e === NearestMipMapLinearFilter) return r.NEAREST_MIPMAP_LINEAR;
  8802. if (e === LinearFilter) return r.LINEAR;
  8803. if (e === LinearMipMapNearestFilter) return r.LINEAR_MIPMAP_NEAREST;
  8804. if (e === LinearMipMapLinearFilter) return r.LINEAR_MIPMAP_LINEAR;
  8805. if (e === UnsignedByteType) return r.UNSIGNED_BYTE;
  8806. if (e === UnsignedShort4444Type) return r.UNSIGNED_SHORT_4_4_4_4;
  8807. if (e === UnsignedShort5551Type) return r.UNSIGNED_SHORT_5_5_5_1;
  8808. if (e === UnsignedShort565Type) return r.UNSIGNED_SHORT_5_6_5;
  8809. if (e === ByteType) return r.BYTE;
  8810. if (e === ShortType) return r.SHORT;
  8811. if (e === UnsignedShortType) return r.UNSIGNED_SHORT;
  8812. if (e === IntType) return r.INT;
  8813. if (e === UnsignedIntType) return r.UNSIGNED_INT;
  8814. if (e === FloatType) return r.FLOAT;
  8815. if (t = i.get("OES_texture_half_float"), null !== t && e === HalfFloatType) return t.HALF_FLOAT_OES;
  8816. if (e === AlphaFormat) return r.ALPHA;
  8817. if (e === RGBFormat) return r.RGB;
  8818. if (e === RGBAFormat) return r.RGBA;
  8819. if (e === LuminanceFormat) return r.LUMINANCE;
  8820. if (e === LuminanceAlphaFormat) return r.LUMINANCE_ALPHA;
  8821. if (e === AddEquation) return r.FUNC_ADD;
  8822. if (e === SubtractEquation) return r.FUNC_SUBTRACT;
  8823. if (e === ReverseSubtractEquation) return r.FUNC_REVERSE_SUBTRACT;
  8824. if (e === ZeroFactor) return r.ZERO;
  8825. if (e === OneFactor) return r.ONE;
  8826. if (e === SrcColorFactor) return r.SRC_COLOR;
  8827. if (e === OneMinusSrcColorFactor) return r.ONE_MINUS_SRC_COLOR;
  8828. if (e === SrcAlphaFactor) return r.SRC_ALPHA;
  8829. if (e === OneMinusSrcAlphaFactor) return r.ONE_MINUS_SRC_ALPHA;
  8830. if (e === DstAlphaFactor) return r.DST_ALPHA;
  8831. if (e === OneMinusDstAlphaFactor) return r.ONE_MINUS_DST_ALPHA;
  8832. if (e === DstColorFactor) return r.DST_COLOR;
  8833. if (e === OneMinusDstColorFactor) return r.ONE_MINUS_DST_COLOR;
  8834. if (e === SrcAlphaSaturateFactor) return r.SRC_ALPHA_SATURATE;
  8835. if (t = i.get("WEBGL_compressed_texture_s3tc"), null !== t) {
  8836. if (e === RGB_S3TC_DXT1_Format) return t.COMPRESSED_RGB_S3TC_DXT1_EXT;
  8837. if (e === RGBA_S3TC_DXT1_Format$1) return t.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  8838. if (e === RGBA_S3TC_DXT3_Format) return t.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  8839. if (e === RGBA_S3TC_DXT5_Format$1) return t.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  8840. }
  8841. if (t = i.get("WEBGL_compressed_texture_pvrtc"), null !== t) {
  8842. if (e === RGB_PVRTC_4BPPV1_Format) return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  8843. if (e === RGB_PVRTC_2BPPV1_Format) return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  8844. if (e === RGBA_PVRTC_4BPPV1_Format) return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  8845. if (e === RGBA_PVRTC_2BPPV1_Format) return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  8846. }
  8847. if (t = i.get("WEBGL_compressed_texture_etc1"), null !== t && e === RGB_ETC1_Format) return t.COMPRESSED_RGB_ETC1_WEBGL;
  8848. if (t = i.get("EXT_blend_minmax"), null !== t) {
  8849. if (e === MinEquation) return t.MIN_EXT;
  8850. if (e === MaxEquation) return t.MAX_EXT;
  8851. }
  8852. return 0;
  8853. };
  8854. EventDispatcher.prototype.addEventListener = function (type, listener) {
  8855. var {
  8856. importance = 0,
  8857. once
  8858. } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  8859. //add importance
  8860. if (this._listeners === undefined) this._listeners = {};
  8861. var listeners = this._listeners;
  8862. if (listeners[type] === undefined) {
  8863. listeners[type] = [];
  8864. }
  8865. /* if(type == 'flyingDone'){
  8866. console.log('addEventListener flyingDone')
  8867. } */
  8868. if (!listeners[type].some(e => e.listener == listener)) {
  8869. listeners[type].push({
  8870. listener,
  8871. importance,
  8872. once
  8873. });
  8874. listeners[type] = listeners[type].sort((e, a) => a.importance - e.importance); //add
  8875. }
  8876. };
  8877. EventDispatcher.prototype.hasEventListener = function (type, listener) {
  8878. if (this._listeners === undefined) return false;
  8879. var listeners = this._listeners;
  8880. return listeners[type] !== undefined && listeners[type].some(e => e.listener == listener);
  8881. };
  8882. EventDispatcher.prototype.removeEventListener = function (type, listener) {
  8883. if (this._listeners === undefined) return;
  8884. var listeners = this._listeners;
  8885. var listenerArray = listeners[type];
  8886. if (listenerArray !== undefined) {
  8887. /* const index = listenerArray.indexOf( listener );
  8888. if ( index !== - 1 ) {
  8889. listenerArray.splice( index, 1 );
  8890. } */
  8891. var item = listenerArray.find(e => e.listener == listener);
  8892. item && listenerArray.splice(listenerArray.indexOf(item), 1);
  8893. }
  8894. };
  8895. EventDispatcher.prototype.removeEventListeners = function (type) {
  8896. //add
  8897. if (this._listeners && this._listeners[type] !== undefined) {
  8898. delete this._listeners[type];
  8899. }
  8900. };
  8901. EventDispatcher.prototype.removeAllListeners = function () {
  8902. //add
  8903. this._listeners = {};
  8904. };
  8905. EventDispatcher.prototype.dispatchEvent = function (event) {
  8906. if (typeof event == 'string') {
  8907. //add
  8908. event = {
  8909. type: event
  8910. };
  8911. }
  8912. if (this._listeners === undefined) return;
  8913. var listeners = this._listeners;
  8914. var listenerArray = listeners[event.type];
  8915. if (listenerArray !== undefined) {
  8916. event.target = this;
  8917. // Make a copy, in case listeners are removed while iterating.
  8918. for (var {
  8919. listener,
  8920. once
  8921. } of listenerArray.slice(0)) {
  8922. if (once) {
  8923. this.removeEventListener(event.type, listener);
  8924. }
  8925. var result = listener.call(this, event); //add stopContinue
  8926. if (result && result.stopContinue) {
  8927. break;
  8928. }
  8929. }
  8930. }
  8931. };
  8932. EventDispatcher.prototype.traverse = function (callback) {
  8933. var result = callback(this);
  8934. if (result && result.stopContinue) {
  8935. //xzw add
  8936. return;
  8937. }
  8938. var children = this.children;
  8939. if (children) {
  8940. for (var i = 0, l = children.length; i < l; i++) {
  8941. children[i].traverse(callback);
  8942. }
  8943. }
  8944. };
  8945. Object3D.prototype.traverse = function (callback) {
  8946. var result = callback(this);
  8947. if (result && result.stopContinue) {
  8948. //xzw add
  8949. return;
  8950. }
  8951. var children = this.children;
  8952. for (var i = 0, l = children.length; i < l; i++) {
  8953. children[i] && children[i].traverse(callback);
  8954. }
  8955. };
  8956. Material.prototype.setValues = function (values) {
  8957. if (values === undefined) return;
  8958. for (var key in values) {
  8959. var newValue = values[key];
  8960. if (newValue === undefined) {
  8961. console.warn('THREE.Material: \'' + key + '\' parameter is undefined.');
  8962. continue;
  8963. }
  8964. // for backward compatability if shading is set in the constructor
  8965. if (key === 'shading') {
  8966. console.warn('THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.');
  8967. this.flatShading = newValue === FlatShading ? true : false;
  8968. continue;
  8969. }
  8970. var currentValue = this[key];
  8971. /* if ( currentValue === undefined ) { //-----主要删了这段,否则很难和 set 一起使用
  8972. //console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  8973. continue;
  8974. } */
  8975. if (currentValue && currentValue.isColor) {
  8976. currentValue.set(newValue);
  8977. } else if (currentValue && currentValue.isVector3 && newValue && newValue.isVector3) {
  8978. currentValue.copy(newValue);
  8979. } else {
  8980. this[key] = newValue;
  8981. }
  8982. }
  8983. };
  8984. function ascSort$1(a, b) {
  8985. return a.distance - b.distance;
  8986. }
  8987. function intersectObject(object, raycaster, intersects, recursive, ignoreUnvisible) {
  8988. if (ignoreUnvisible && !object.visible) return; //add
  8989. if (object.layers.test(raycaster.layers)) {
  8990. object.raycast(raycaster, intersects);
  8991. }
  8992. if (recursive === true) {
  8993. var children = object.children;
  8994. for (var i = 0, l = children.length; i < l; i++) {
  8995. intersectObject(children[i], raycaster, intersects, true, ignoreUnvisible);
  8996. }
  8997. }
  8998. }
  8999. Raycaster.prototype.intersectObject = function (object, recursive, optionalTarget, ignoreUnvisible) {
  9000. var intersects = optionalTarget || [];
  9001. intersectObject(object, this, intersects, recursive, ignoreUnvisible);
  9002. intersects.sort(ascSort$1);
  9003. return intersects;
  9004. };
  9005. Raycaster.prototype.intersectObjects = function (objects, recursive, optionalTarget, ignoreUnvisible) {
  9006. //add ignoreUnvisible 跳过不可见
  9007. var intersects = optionalTarget || [];
  9008. if (Array.isArray(objects) === false) {
  9009. console.warn('THREE.Raycaster.intersectObjects: objects is not an Array.');
  9010. return intersects;
  9011. }
  9012. for (var i = 0, l = objects.length; i < l; i++) {
  9013. intersectObject(objects[i], this, intersects, recursive, ignoreUnvisible);
  9014. }
  9015. intersects.sort(ascSort$1);
  9016. return intersects;
  9017. };
  9018. Object3D.prototype.realVisible = function () {
  9019. var v = true;
  9020. var parent = this;
  9021. var lastParent;
  9022. while (parent) {
  9023. if (parent.visible === false) {
  9024. v = false;
  9025. break;
  9026. }
  9027. lastParent = parent;
  9028. parent = parent.parent;
  9029. }
  9030. if (v && !(lastParent instanceof Scene)) {
  9031. //已被删除
  9032. v = false;
  9033. }
  9034. return v;
  9035. };
  9036. var MathLight = {};
  9037. MathLight.RADIANS_PER_DEGREE = Math.PI / 180;
  9038. MathLight.DEGREES_PER_RADIAN = 180 / Math.PI;
  9039. MathLight.Vector3 = function (e, t, i) {
  9040. this.x = e || 0, this.y = t || 0, this.z = i || 0;
  9041. };
  9042. MathLight.Matrix4 = function () {
  9043. this.elements = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), arguments.length > 0 && console.error("MathLight.Matrix4: the constructor no longer reads arguments. use .set() instead.");
  9044. };
  9045. MathLight.Matrix4.prototype = {
  9046. identity: function identity() {
  9047. return this.set(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1), this;
  9048. },
  9049. copy: function copy(e) {
  9050. return this.elements.set(e.elements), this;
  9051. },
  9052. applyToVector3: function applyToVector3(e) {
  9053. var t = e.x,
  9054. i = e.y,
  9055. n = e.z,
  9056. r = this.elements;
  9057. return e.x = r[0] * t + r[4] * i + r[8] * n + r[12], e.y = r[1] * t + r[5] * i + r[9] * n + r[13], e.z = r[2] * t + r[6] * i + r[10] * n + r[14], this;
  9058. },
  9059. getInverse: function getInverse(e, t) {
  9060. var i = this.elements,
  9061. n = e.elements,
  9062. r = n[0],
  9063. o = n[1],
  9064. a = n[2],
  9065. s = n[3],
  9066. l = n[4],
  9067. c = n[5],
  9068. h = n[6],
  9069. u = n[7],
  9070. d = n[8],
  9071. p = n[9],
  9072. f = n[10],
  9073. g = n[11],
  9074. m = n[12],
  9075. v = n[13],
  9076. A = n[14],
  9077. y = n[15],
  9078. C = p * A * u - v * f * u + v * h * g - c * A * g - p * h * y + c * f * y,
  9079. I = m * f * u - d * A * u - m * h * g + l * A * g + d * h * y - l * f * y,
  9080. E = d * v * u - m * p * u + m * c * g - l * v * g - d * c * y + l * p * y,
  9081. b = m * p * h - d * v * h - m * c * f + l * v * f + d * c * A - l * p * A,
  9082. w = r * C + o * I + a * E + s * b;
  9083. if (0 === w) {
  9084. var _ = "MathLight.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  9085. if (t) throw new Error(_);
  9086. return console.warn(_), this.identity();
  9087. }
  9088. var T = 1 / w;
  9089. return i[0] = C * T, i[1] = (v * f * s - p * A * s - v * a * g + o * A * g + p * a * y - o * f * y) * T, i[2] = (c * A * s - v * h * s + v * a * u - o * A * u - c * a * y + o * h * y) * T, i[3] = (p * h * s - c * f * s - p * a * u + o * f * u + c * a * g - o * h * g) * T, i[4] = I * T, i[5] = (d * A * s - m * f * s + m * a * g - r * A * g - d * a * y + r * f * y) * T, i[6] = (m * h * s - l * A * s - m * a * u + r * A * u + l * a * y - r * h * y) * T, i[7] = (l * f * s - d * h * s + d * a * u - r * f * u - l * a * g + r * h * g) * T, i[8] = E * T, i[9] = (m * p * s - d * v * s - m * o * g + r * v * g + d * o * y - r * p * y) * T, i[10] = (l * v * s - m * c * s + m * o * u - r * v * u - l * o * y + r * c * y) * T, i[11] = (d * c * s - l * p * s - d * o * u + r * p * u + l * o * g - r * c * g) * T, i[12] = b * T, i[13] = (d * v * a - m * p * a + m * o * f - r * v * f - d * o * A + r * p * A) * T, i[14] = (m * c * a - l * v * a - m * o * h + r * v * h + l * o * A - r * c * A) * T, i[15] = (l * p * a - d * c * a + d * o * h - r * p * h - l * o * f + r * c * f) * T, this;
  9090. },
  9091. makeRotationFromQuaternion: function makeRotationFromQuaternion(e) {
  9092. var t = this.elements,
  9093. i = e.x,
  9094. n = e.y,
  9095. r = e.z,
  9096. o = e.w,
  9097. a = i + i,
  9098. s = n + n,
  9099. l = r + r,
  9100. c = i * a,
  9101. h = i * s,
  9102. u = i * l,
  9103. d = n * s,
  9104. p = n * l,
  9105. f = r * l,
  9106. g = o * a,
  9107. m = o * s,
  9108. v = o * l;
  9109. return t[0] = 1 - (d + f), t[4] = h - v, t[8] = u + m, t[1] = h + v, t[5] = 1 - (c + f), t[9] = p - g, t[2] = u - m, t[6] = p + g, t[10] = 1 - (c + d), t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this;
  9110. }
  9111. };
  9112. MathLight.Quaternion = function (e, t, i, n) {
  9113. this._x = e || 0, this._y = t || 0, this._z = i || 0, this._w = void 0 !== n ? n : 1;
  9114. };
  9115. MathLight.Quaternion.prototype = {
  9116. get x() {
  9117. return this._x;
  9118. },
  9119. set x(e) {
  9120. this._x = e;
  9121. },
  9122. get y() {
  9123. return this._y;
  9124. },
  9125. set y(e) {
  9126. this._y = e;
  9127. },
  9128. get z() {
  9129. return this._z;
  9130. },
  9131. set z(e) {
  9132. this._z = e;
  9133. },
  9134. get w() {
  9135. return this._w;
  9136. },
  9137. set w(e) {
  9138. this._w = e;
  9139. },
  9140. copy: function copy(e) {
  9141. this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w;
  9142. },
  9143. inverse: function inverse() {
  9144. return this.conjugate().normalize();
  9145. },
  9146. conjugate: function conjugate() {
  9147. return this._x *= -1, this._y *= -1, this._z *= -1, this;
  9148. },
  9149. length: function length() {
  9150. return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w);
  9151. },
  9152. normalize: function normalize() {
  9153. var e = this.length();
  9154. return 0 === e ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x = this._x * e, this._y = this._y * e, this._z = this._z * e, this._w = this._w * e), this;
  9155. },
  9156. setFromAxisAngle: function setFromAxisAngle(e, t) {
  9157. var i = t / 2,
  9158. n = Math.sin(i);
  9159. return this._x = e.x * n, this._y = e.y * n, this._z = e.z * n, this._w = Math.cos(i), this;
  9160. },
  9161. setFromUnitVectors: function () {
  9162. var e,
  9163. t,
  9164. i = 1e-6;
  9165. return function (n, o) {
  9166. return void 0 === e && (e = new MathLight.Vector3()), t = MathLight.dot(n, o) + 1, t < i ? (t = 0, Math.abs(n.x) > Math.abs(n.z) ? MathLight.setVector(e, -n.y, n.x, 0) : MathLight.setVector(e, 0, -n.z, n.y)) : MathLight.cross(n, o, e), this._x = e.x, this._y = e.y, this._z = e.z, this._w = t, this.normalize();
  9167. };
  9168. }(),
  9169. multiply: function multiply(e) {
  9170. return this.multiplyQuaternions(this, e);
  9171. },
  9172. premultiply: function premultiply(e) {
  9173. return this.multiplyQuaternions(e, this);
  9174. },
  9175. multiplyQuaternions: function multiplyQuaternions(e, t) {
  9176. var i = e._x,
  9177. n = e._y,
  9178. r = e._z,
  9179. o = e._w,
  9180. a = t._x,
  9181. s = t._y,
  9182. l = t._z,
  9183. c = t._w;
  9184. return this._x = i * c + o * a + n * l - r * s, this._y = n * c + o * s + r * a - i * l, this._z = r * c + o * l + i * s - n * a, this._w = o * c - i * a - n * s - r * l, this;
  9185. }
  9186. };
  9187. MathLight.convertWorkshopVector = function (e) {
  9188. return new MathLight.Vector3(-e.x, e.y, e.z);
  9189. };
  9190. MathLight.convertWorkshopQuaternion = function (e) {
  9191. return new MathLight.Quaternion(-e.x, e.y, e.z, -e.w).multiply(new MathLight.Quaternion(Math.sqrt(2) / 2, Math.sqrt(2) / 2, 0, 0));
  9192. };
  9193. MathLight.convertWorkshopOrthoZoom = function (e) {
  9194. //return e === -1 ? -1 : e / 16 * ($('#player').width() / $('#player').height()) / n.workshopApsect
  9195. return e === -1 ? -1 : e * ($("#player").width() / $("#player").height());
  9196. };
  9197. MathLight.convertWorkshopPanoramaQuaternion = function (e) {
  9198. return new MathLight.Quaternion(e.x, -e.y, -e.z, e.w).normalize().multiply(new MathLight.Quaternion().setFromAxisAngle(new MathLight.Vector3(0, 1, 0), 270 * MathLight.RADIANS_PER_DEGREE));
  9199. };
  9200. MathLight.normalize = function (e) {
  9201. var t = e.x * e.x + e.y * e.y + e.z * e.z,
  9202. i = Math.sqrt(t);
  9203. e.x /= i, e.y /= i, e.z /= i;
  9204. };
  9205. MathLight.dot = function (e, t) {
  9206. return e.x * t.x + e.y * t.y + e.z * t.z;
  9207. };
  9208. MathLight.cross = function (e, t, i) {
  9209. var n = e.x,
  9210. r = e.y,
  9211. o = e.z;
  9212. i.x = r * t.z - o * t.y, i.y = o * t.x - n * t.z, i.z = n * t.y - r * t.x;
  9213. };
  9214. MathLight.setVector = function (e, t, i, n) {
  9215. e.x = t, e.y = i, e.z = n;
  9216. };
  9217. MathLight.copyVector = function (e, t) {
  9218. t.x = e.x, t.y = e.y, t.z = e.z;
  9219. };
  9220. MathLight.addVector = function (e, t) {
  9221. e.x += t.x, e.y += t.y, e.z += t.z;
  9222. };
  9223. MathLight.subVector = function (e, t) {
  9224. e.x -= t.x, e.y -= t.y, e.z -= t.z;
  9225. };
  9226. MathLight.applyQuaternionToVector = function (e, t) {
  9227. var i = t.x,
  9228. n = t.y,
  9229. r = t.z,
  9230. o = e.x,
  9231. a = e.y,
  9232. s = e.z,
  9233. l = e.w,
  9234. c = l * i + a * r - s * n,
  9235. h = l * n + s * i - o * r,
  9236. u = l * r + o * n - a * i,
  9237. d = -o * i - a * n - s * r;
  9238. t.x = c * l + d * -o + h * -s - u * -a, t.y = h * l + d * -a + u * -o - c * -s, t.z = u * l + d * -s + c * -a - h * -o;
  9239. };
  9240. MathLight.angleBetweenVectors = function (e, t) {
  9241. return Math.acos(MathLight.dot(e, t));
  9242. };
  9243. var cameraLight = {
  9244. clampVFOV: function clampVFOV(currentFov, maxHFov, width, height) {
  9245. //限制currentFov, 使之造成的横向fov不大于指定值maxHFov
  9246. var r = cameraLight.getHFOVFromVFOV(currentFov, width, height);
  9247. return r > maxHFov ? cameraLight.getVFOVFromHFOV(maxHFov, width, height) : currentFov;
  9248. },
  9249. getHFOVForCamera: function getHFOVForCamera(camera, getRad) {
  9250. return cameraLight.getHFOVByScreenPrecent(camera.fov, camera.aspect, getRad);
  9251. },
  9252. //add
  9253. getHFOVByScreenPrecent: function getHFOVByScreenPrecent(fov, percent, getRad) {
  9254. //当fov为占比百分百时,percent代表在屏幕上从中心到边缘的占比
  9255. var rad = 2 * Math.atan(percent * Math.tan(fov * MathLight.RADIANS_PER_DEGREE / 2));
  9256. if (getRad) return rad;else return rad * MathLight.DEGREES_PER_RADIAN;
  9257. }
  9258. };
  9259. var XHRFactory = {
  9260. config: {
  9261. withCredentials: false,
  9262. customHeaders: [{
  9263. header: null,
  9264. value: null
  9265. }]
  9266. },
  9267. createXMLHttpRequest: function createXMLHttpRequest() {
  9268. var xhr = new XMLHttpRequest();
  9269. if (this.config.customHeaders && Array.isArray(this.config.customHeaders) && this.config.customHeaders.length > 0) {
  9270. var baseOpen = xhr.open;
  9271. var customHeaders = this.config.customHeaders;
  9272. xhr.open = function () {
  9273. baseOpen.apply(this, [].slice.call(arguments));
  9274. customHeaders.forEach(function (customHeader) {
  9275. if (!!customHeader.header && !!customHeader.value) {
  9276. xhr.setRequestHeader(customHeader.header, customHeader.value);
  9277. }
  9278. });
  9279. };
  9280. }
  9281. return xhr;
  9282. }
  9283. };
  9284. // /**
  9285. class TextSprite$1 extends Object3D {
  9286. //old
  9287. constructor(text) {
  9288. super();
  9289. var texture = new Texture();
  9290. texture.minFilter = LinearFilter;
  9291. texture.magFilter = LinearFilter;
  9292. var spriteMaterial = new SpriteMaterial({
  9293. map: texture,
  9294. depthTest: false,
  9295. depthWrite: false
  9296. });
  9297. this.texture = texture;
  9298. this.material = spriteMaterial;
  9299. //this.material = getRawMaterial(texture);
  9300. this.sprite = new Sprite$1(this.material);
  9301. this.add(this.sprite);
  9302. this.borderThickness = 4;
  9303. this.fontface = 'Arial';
  9304. this.fontsize = 28;
  9305. this.borderColor = {
  9306. r: 0,
  9307. g: 0,
  9308. b: 0,
  9309. a: 1.0
  9310. };
  9311. this.backgroundColor = {
  9312. r: 255,
  9313. g: 255,
  9314. b: 255,
  9315. a: 1.0
  9316. };
  9317. this.textColor = {
  9318. r: 255,
  9319. g: 255,
  9320. b: 255,
  9321. a: 1.0
  9322. };
  9323. this.text = '';
  9324. this.setText(text);
  9325. }
  9326. setText(text) {
  9327. if (this.text !== text) {
  9328. this.text = text;
  9329. this.update();
  9330. }
  9331. }
  9332. setTextColor(color) {
  9333. this.textColor = color;
  9334. this.update();
  9335. }
  9336. setBorderColor(color) {
  9337. this.borderColor = color;
  9338. this.update();
  9339. }
  9340. setBackgroundColor(color) {
  9341. this.backgroundColor = color;
  9342. this.update();
  9343. }
  9344. update() {
  9345. var canvas = document.createElement('canvas');
  9346. var context = canvas.getContext('2d');
  9347. context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface;
  9348. // get size data (height depends only on font size)
  9349. var metrics = context.measureText(this.text);
  9350. var textWidth = metrics.width;
  9351. var margin = 5;
  9352. var spriteWidth = 2 * margin + textWidth + 2 * this.borderThickness;
  9353. var spriteHeight = this.fontsize * 1.4 + 2 * this.borderThickness;
  9354. context.canvas.width = spriteWidth;
  9355. context.canvas.height = spriteHeight;
  9356. context.font = 'Bold ' + this.fontsize + 'px ' + this.fontface;
  9357. // background color
  9358. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  9359. // border color
  9360. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')';
  9361. context.lineWidth = this.borderThickness;
  9362. this.roundRect(context, this.borderThickness / 2, this.borderThickness / 2, textWidth + this.borderThickness + 2 * margin, this.fontsize * 1.4 + this.borderThickness, 6);
  9363. // text color
  9364. context.strokeStyle = 'rgba(0, 0, 0, 1.0)';
  9365. context.strokeText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness);
  9366. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')';
  9367. context.fillText(this.text, this.borderThickness + margin, this.fontsize + this.borderThickness);
  9368. var texture = new Texture(canvas);
  9369. texture.minFilter = LinearFilter;
  9370. texture.magFilter = LinearFilter;
  9371. texture.needsUpdate = true;
  9372. //this.material.needsUpdate = true;
  9373. // { // screen-space sprite
  9374. // let [screenWidth, screenHeight] = [1620, 937];
  9375. // let uniforms = this.sprite.material.uniforms;
  9376. // let aspect = spriteHeight / spriteWidth;
  9377. // let factor = 0.5;
  9378. // let w = spriteWidth / screenWidth;
  9379. // let h = spriteHeight / screenHeight;
  9380. // uniforms.uScale.value = [2 * w, 2 * h];
  9381. // //uniforms.uScale.value = [factor * 1, factor * aspect];
  9382. // this.sprite.material.uniforms.map.value = texture;
  9383. // }
  9384. this.sprite.material.map = texture;
  9385. this.texture = texture;
  9386. this.sprite.scale.set(spriteWidth * 0.01, spriteHeight * 0.01, 1.0);
  9387. }
  9388. roundRect(ctx, x, y, w, h, r) {
  9389. ctx.beginPath();
  9390. ctx.moveTo(x + r, y);
  9391. ctx.lineTo(x + w - r, y);
  9392. ctx.quadraticCurveTo(x + w, y, x + w, y + r);
  9393. ctx.lineTo(x + w, y + h - r);
  9394. ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
  9395. ctx.lineTo(x + r, y + h);
  9396. ctx.quadraticCurveTo(x, y + h, x, y + h - r);
  9397. ctx.lineTo(x, y + r);
  9398. ctx.quadraticCurveTo(x, y, x + r, y);
  9399. ctx.closePath();
  9400. ctx.fill();
  9401. ctx.stroke();
  9402. }
  9403. }
  9404. class Volume extends Object3D {
  9405. constructor() {
  9406. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  9407. super();
  9408. if (this.constructor.name === "Volume") {
  9409. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  9410. }
  9411. //console.log(this);
  9412. //console.log(this.constructor);
  9413. //console.log(this.constructor.name);
  9414. this._clip = args.clip || false;
  9415. this._visible = true;
  9416. this.showVolumeLabel = true;
  9417. this._modifiable = args.modifiable || true;
  9418. this.label = new TextSprite$1('0');
  9419. this.label.setBorderColor({
  9420. r: 0,
  9421. g: 255,
  9422. b: 0,
  9423. a: 0.0
  9424. });
  9425. this.label.setBackgroundColor({
  9426. r: 0,
  9427. g: 255,
  9428. b: 0,
  9429. a: 0.0
  9430. });
  9431. this.label.material.depthTest = false;
  9432. this.label.material.depthWrite = false;
  9433. this.label.material.transparent = true;
  9434. this.label.position.y -= 0.5;
  9435. this.add(this.label);
  9436. this.label.updateMatrixWorld = () => {
  9437. var volumeWorldPos = new Vector3();
  9438. volumeWorldPos.setFromMatrixPosition(this.matrixWorld);
  9439. this.label.position.copy(volumeWorldPos);
  9440. this.label.updateMatrix();
  9441. this.label.matrixWorld.copy(this.label.matrix);
  9442. this.label.matrixWorldNeedsUpdate = false;
  9443. for (var i = 0, l = this.label.children.length; i < l; i++) {
  9444. this.label.children[i].updateMatrixWorld(true);
  9445. }
  9446. };
  9447. {
  9448. // event listeners
  9449. this.addEventListener('select', e => {});
  9450. this.addEventListener('deselect', e => {});
  9451. }
  9452. }
  9453. get visible() {
  9454. return this._visible;
  9455. }
  9456. set visible(value) {
  9457. if (this._visible !== value) {
  9458. this._visible = value;
  9459. this.dispatchEvent({
  9460. type: "visibility_changed",
  9461. object: this
  9462. });
  9463. }
  9464. }
  9465. getVolume() {
  9466. console.warn("override this in subclass");
  9467. }
  9468. update() {}
  9469. raycast(raycaster, intersects) {}
  9470. get clip() {
  9471. return this._clip;
  9472. }
  9473. set clip(value) {
  9474. if (this._clip !== value) {
  9475. this._clip = value;
  9476. this.update();
  9477. this.dispatchEvent({
  9478. type: "clip_changed",
  9479. object: this
  9480. });
  9481. }
  9482. }
  9483. get modifieable() {
  9484. return this._modifiable;
  9485. }
  9486. set modifieable(value) {
  9487. this._modifiable = value;
  9488. this.update();
  9489. }
  9490. }
  9491. ;
  9492. class BoxVolume extends Volume {
  9493. constructor() {
  9494. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  9495. super(args);
  9496. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  9497. this.name = 'box_' + this.constructor.counter;
  9498. var boxGeometry = new BoxGeometry(1, 1, 1);
  9499. boxGeometry.computeBoundingBox();
  9500. var boxFrameGeometry = new Geometry();
  9501. {
  9502. var Vector3$1 = Vector3;
  9503. boxFrameGeometry.vertices.push(
  9504. // bottom
  9505. new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, 0.5),
  9506. // top
  9507. new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, 0.5),
  9508. // sides
  9509. new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5));
  9510. }
  9511. this.material = new MeshBasicMaterial({
  9512. color: 0x00ff00,
  9513. transparent: true,
  9514. opacity: 0.3,
  9515. depthTest: true,
  9516. depthWrite: false
  9517. });
  9518. this.box = new Mesh(boxGeometry, this.material);
  9519. this.box.geometry.computeBoundingBox();
  9520. this.boundingBox = this.box.geometry.boundingBox;
  9521. this.add(this.box);
  9522. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({
  9523. color: 0x000000
  9524. }));
  9525. // this.frame.mode = THREE.Lines;
  9526. this.add(this.frame);
  9527. this.update();
  9528. }
  9529. update() {
  9530. this.boundingBox = this.box.geometry.boundingBox;
  9531. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  9532. if (this._clip) {
  9533. this.box.visible = false;
  9534. this.label.visible = false;
  9535. } else {
  9536. this.box.visible = true;
  9537. this.label.visible = this.showVolumeLabel;
  9538. }
  9539. }
  9540. raycast(raycaster, intersects) {
  9541. var is = [];
  9542. this.box.raycast(raycaster, is);
  9543. if (is.length > 0) {
  9544. var I = is[0];
  9545. intersects.push({
  9546. distance: I.distance,
  9547. object: this,
  9548. point: I.point.clone()
  9549. });
  9550. }
  9551. }
  9552. getVolume() {
  9553. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  9554. }
  9555. }
  9556. ;
  9557. class SphereVolume$1 extends Volume {
  9558. constructor() {
  9559. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  9560. super(args);
  9561. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  9562. this.name = 'sphere_' + this.constructor.counter;
  9563. var sphereGeometry = new SphereGeometry(1, 32, 32);
  9564. sphereGeometry.computeBoundingBox();
  9565. this.material = new MeshBasicMaterial({
  9566. color: 0x00ff00,
  9567. transparent: true,
  9568. opacity: 0.3,
  9569. depthTest: true,
  9570. depthWrite: false
  9571. });
  9572. this.sphere = new Mesh(sphereGeometry, this.material);
  9573. this.sphere.visible = false;
  9574. this.sphere.geometry.computeBoundingBox();
  9575. this.boundingBox = this.sphere.geometry.boundingBox;
  9576. this.add(this.sphere);
  9577. this.label.visible = false;
  9578. var frameGeometry = new Geometry();
  9579. {
  9580. var steps = 64;
  9581. var uSegments = 8;
  9582. var vSegments = 5;
  9583. var r = 1;
  9584. for (var uSegment = 0; uSegment < uSegments; uSegment++) {
  9585. var alpha = uSegment / uSegments * Math.PI * 2;
  9586. var dirx = Math.cos(alpha);
  9587. var diry = Math.sin(alpha);
  9588. for (var i = 0; i <= steps; i++) {
  9589. var v = i / steps * Math.PI * 2;
  9590. var vNext = v + 2 * Math.PI / steps;
  9591. var height = Math.sin(v);
  9592. var xyAmount = Math.cos(v);
  9593. var heightNext = Math.sin(vNext);
  9594. var xyAmountNext = Math.cos(vNext);
  9595. var vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  9596. frameGeometry.vertices.push(vertex);
  9597. var vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  9598. frameGeometry.vertices.push(vertexNext);
  9599. }
  9600. }
  9601. // creates rings at poles, just because it's easier to implement
  9602. for (var vSegment = 0; vSegment <= vSegments + 1; vSegment++) {
  9603. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  9604. var uh = vSegment / (vSegments + 1); // -1 to 1
  9605. uh = (1 - uh) * (-Math.PI / 2) + uh * (Math.PI / 2);
  9606. var _height = Math.sin(uh);
  9607. console.log(uh, _height);
  9608. for (var _i = 0; _i <= steps; _i++) {
  9609. var u = _i / steps * Math.PI * 2;
  9610. var uNext = u + 2 * Math.PI / steps;
  9611. var _dirx = Math.cos(u);
  9612. var _diry = Math.sin(u);
  9613. var dirxNext = Math.cos(uNext);
  9614. var diryNext = Math.sin(uNext);
  9615. var _xyAmount = Math.sqrt(1 - _height * _height);
  9616. var _vertex = new Vector3(_dirx * _xyAmount, _diry * _xyAmount, _height);
  9617. frameGeometry.vertices.push(_vertex);
  9618. var _vertexNext = new Vector3(dirxNext * _xyAmount, diryNext * _xyAmount, _height);
  9619. frameGeometry.vertices.push(_vertexNext);
  9620. }
  9621. }
  9622. }
  9623. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({
  9624. color: 0x000000
  9625. }));
  9626. this.add(this.frame);
  9627. var frameMaterial = new MeshBasicMaterial({
  9628. wireframe: true,
  9629. color: 0x000000
  9630. });
  9631. this.frame = new Mesh(sphereGeometry, frameMaterial);
  9632. //this.add(this.frame);
  9633. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  9634. // this.frame.mode = THREE.Lines;
  9635. //this.add(this.frame);
  9636. this.update();
  9637. }
  9638. update() {
  9639. this.boundingBox = this.sphere.geometry.boundingBox;
  9640. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  9641. //if (this._clip) {
  9642. // this.sphere.visible = false;
  9643. // this.label.visible = false;
  9644. //} else {
  9645. // this.sphere.visible = true;
  9646. // this.label.visible = this.showVolumeLabel;
  9647. //}
  9648. }
  9649. raycast(raycaster, intersects) {
  9650. var is = [];
  9651. this.sphere.raycast(raycaster, is);
  9652. if (is.length > 0) {
  9653. var I = is[0];
  9654. intersects.push({
  9655. distance: I.distance,
  9656. object: this,
  9657. point: I.point.clone()
  9658. });
  9659. }
  9660. }
  9661. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  9662. getVolume() {
  9663. return 4 / 3 * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  9664. }
  9665. }
  9666. ;
  9667. class Profile extends Object3D {
  9668. constructor() {
  9669. super();
  9670. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  9671. this.name = 'Profile_' + this.constructor.counter;
  9672. this.points = [];
  9673. this.spheres = [];
  9674. this.edges = [];
  9675. this.boxes = [];
  9676. this.width = 1;
  9677. this.height = 20;
  9678. this._modifiable = true;
  9679. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  9680. this.color = new Color(0xff0000);
  9681. this.lineColor = new Color(0xff0000);
  9682. }
  9683. createSphereMaterial() {
  9684. var sphereMaterial = new MeshLambertMaterial({
  9685. //shading: THREE.SmoothShading,
  9686. color: 0xff0000,
  9687. depthTest: false,
  9688. depthWrite: false
  9689. });
  9690. return sphereMaterial;
  9691. }
  9692. getSegments() {
  9693. var segments = [];
  9694. for (var i = 0; i < this.points.length - 1; i++) {
  9695. var start = this.points[i].clone();
  9696. var end = this.points[i + 1].clone();
  9697. segments.push({
  9698. start: start,
  9699. end: end
  9700. });
  9701. }
  9702. return segments;
  9703. }
  9704. getSegmentMatrices() {
  9705. var segments = this.getSegments();
  9706. var matrices = [];
  9707. for (var segment of segments) {
  9708. var {
  9709. start,
  9710. end
  9711. } = segment;
  9712. var box = new Object3D();
  9713. var length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  9714. box.scale.set(length, 10000, this.width);
  9715. box.up.set(0, 0, 1);
  9716. var center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  9717. var diff = new Vector3().subVectors(end, start);
  9718. var target = new Vector3(diff.y, -diff.x, 0);
  9719. box.position.set(0, 0, 0);
  9720. box.lookAt(target);
  9721. box.position.copy(center);
  9722. box.updateMatrixWorld();
  9723. matrices.push(box.matrixWorld);
  9724. }
  9725. return matrices;
  9726. }
  9727. addMarker(point) {
  9728. this.points.push(point);
  9729. var sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  9730. this.add(sphere);
  9731. this.spheres.push(sphere);
  9732. // edges & boxes
  9733. if (this.points.length > 1) {
  9734. var lineGeometry = new Geometry();
  9735. lineGeometry.vertices.push(new Vector3(), new Vector3());
  9736. lineGeometry.colors.push(this.lineColor, this.lineColor, this.lineColor);
  9737. var lineMaterial = new LineBasicMaterial({
  9738. vertexColors: VertexColors,
  9739. linewidth: 2,
  9740. transparent: true,
  9741. opacity: 0.4
  9742. });
  9743. lineMaterial.depthTest = false;
  9744. var edge = new Line(lineGeometry, lineMaterial);
  9745. edge.visible = false;
  9746. this.add(edge);
  9747. this.edges.push(edge);
  9748. var boxGeometry = new BoxGeometry(1, 1, 1);
  9749. var boxMaterial = new MeshBasicMaterial({
  9750. color: 0xff0000,
  9751. transparent: true,
  9752. opacity: 0.2
  9753. });
  9754. var box = new Mesh(boxGeometry, boxMaterial);
  9755. box.visible = false;
  9756. this.add(box);
  9757. this.boxes.push(box);
  9758. }
  9759. {
  9760. // event listeners
  9761. var drag = e => {
  9762. var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds);
  9763. if (I) {
  9764. var i = this.spheres.indexOf(e.drag.object);
  9765. if (i !== -1) {
  9766. this.setPosition(i, I.location);
  9767. //this.dispatchEvent({
  9768. // 'type': 'marker_moved',
  9769. // 'profile': this,
  9770. // 'index': i
  9771. //});
  9772. }
  9773. }
  9774. };
  9775. var drop = e => {
  9776. var i = this.spheres.indexOf(e.drag.object);
  9777. if (i !== -1) {
  9778. this.dispatchEvent({
  9779. 'type': 'marker_dropped',
  9780. 'profile': this,
  9781. 'index': i
  9782. });
  9783. }
  9784. };
  9785. var mouseover = e => e.object.material.emissive.setHex(0x888888);
  9786. var mouseleave = e => e.object.material.emissive.setHex(0x000000);
  9787. sphere.addEventListener('drag', drag);
  9788. sphere.addEventListener('drop', drop);
  9789. sphere.addEventListener('mouseover', mouseover);
  9790. sphere.addEventListener('mouseleave', mouseleave);
  9791. }
  9792. var event = {
  9793. type: 'marker_added',
  9794. profile: this,
  9795. sphere: sphere
  9796. };
  9797. this.dispatchEvent(event);
  9798. this.setPosition(this.points.length - 1, point);
  9799. }
  9800. removeMarker(index) {
  9801. this.points.splice(index, 1);
  9802. this.remove(this.spheres[index]);
  9803. var edgeIndex = index === 0 ? 0 : index - 1;
  9804. this.remove(this.edges[edgeIndex]);
  9805. this.edges.splice(edgeIndex, 1);
  9806. this.remove(this.boxes[edgeIndex]);
  9807. this.boxes.splice(edgeIndex, 1);
  9808. this.spheres.splice(index, 1);
  9809. this.update();
  9810. this.dispatchEvent({
  9811. 'type': 'marker_removed',
  9812. 'profile': this
  9813. });
  9814. }
  9815. setPosition(index, position) {
  9816. var point = this.points[index];
  9817. point.copy(position);
  9818. var event = {
  9819. type: 'marker_moved',
  9820. profile: this,
  9821. index: index,
  9822. position: point.clone()
  9823. };
  9824. this.dispatchEvent(event);
  9825. this.update();
  9826. }
  9827. setWidth(width) {
  9828. this.width = width;
  9829. var event = {
  9830. type: 'width_changed',
  9831. profile: this,
  9832. width: width
  9833. };
  9834. this.dispatchEvent(event);
  9835. this.update();
  9836. }
  9837. getWidth() {
  9838. return this.width;
  9839. }
  9840. update() {
  9841. if (this.points.length === 0) {
  9842. return;
  9843. } else if (this.points.length === 1) {
  9844. var point = this.points[0];
  9845. this.spheres[0].position.copy(point);
  9846. return;
  9847. }
  9848. var min = this.points[0].clone();
  9849. var max = this.points[0].clone();
  9850. var centroid = new Vector3();
  9851. var lastIndex = this.points.length - 1;
  9852. for (var i = 0; i <= lastIndex; i++) {
  9853. var _point = this.points[i];
  9854. var sphere = this.spheres[i];
  9855. var leftIndex = i === 0 ? lastIndex : i - 1;
  9856. // let rightIndex = (i === lastIndex) ? 0 : i + 1;
  9857. var leftVertex = this.points[leftIndex];
  9858. // let rightVertex = this.points[rightIndex];
  9859. var leftEdge = this.edges[leftIndex];
  9860. var rightEdge = this.edges[i];
  9861. var leftBox = this.boxes[leftIndex];
  9862. // rightBox = this.boxes[i];
  9863. // let leftEdgeLength = point.distanceTo(leftVertex);
  9864. // let rightEdgeLength = point.distanceTo(rightVertex);
  9865. // let leftEdgeCenter = new THREE.Vector3().addVectors(leftVertex, point).multiplyScalar(0.5);
  9866. // let rightEdgeCenter = new THREE.Vector3().addVectors(point, rightVertex).multiplyScalar(0.5);
  9867. sphere.position.copy(_point);
  9868. if (this._modifiable) {
  9869. sphere.visible = true;
  9870. } else {
  9871. sphere.visible = false;
  9872. }
  9873. if (leftEdge) {
  9874. leftEdge.geometry.vertices[1].copy(_point);
  9875. leftEdge.geometry.verticesNeedUpdate = true;
  9876. leftEdge.geometry.computeBoundingSphere();
  9877. }
  9878. if (rightEdge) {
  9879. rightEdge.geometry.vertices[0].copy(_point);
  9880. rightEdge.geometry.verticesNeedUpdate = true;
  9881. rightEdge.geometry.computeBoundingSphere();
  9882. }
  9883. if (leftBox) {
  9884. var start = leftVertex;
  9885. var end = _point;
  9886. var length = start.clone().setZ(0).distanceTo(end.clone().setZ(0));
  9887. leftBox.scale.set(length, 1000000, this.width);
  9888. leftBox.up.set(0, 0, 1);
  9889. var center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  9890. var diff = new Vector3().subVectors(end, start);
  9891. var target = new Vector3(diff.y, -diff.x, 0);
  9892. leftBox.position.set(0, 0, 0);
  9893. leftBox.lookAt(target);
  9894. leftBox.position.copy(center);
  9895. }
  9896. centroid.add(_point);
  9897. min.min(_point);
  9898. max.max(_point);
  9899. }
  9900. centroid.multiplyScalar(1 / this.points.length);
  9901. for (var _i = 0; _i < this.boxes.length; _i++) {
  9902. var box = this.boxes[_i];
  9903. box.position.z = min.z + (max.z - min.z) / 2;
  9904. }
  9905. }
  9906. raycast(raycaster, intersects) {
  9907. for (var i = 0; i < this.points.length; i++) {
  9908. var sphere = this.spheres[i];
  9909. sphere.raycast(raycaster, intersects);
  9910. }
  9911. // recalculate distances because they are not necessarely correct
  9912. // for scaled objects.
  9913. // see https://github.com/mrdoob/three.js/issues/5827
  9914. // TODO: remove this once the bug has been fixed
  9915. for (var _i2 = 0; _i2 < intersects.length; _i2++) {
  9916. var I = intersects[_i2];
  9917. I.distance = raycaster.ray.origin.distanceTo(I.point);
  9918. }
  9919. intersects.sort(function (a, b) {
  9920. return a.distance - b.distance;
  9921. });
  9922. }
  9923. get modifiable() {
  9924. return this._modifiable;
  9925. }
  9926. set modifiable(value) {
  9927. this._modifiable = value;
  9928. this.update();
  9929. }
  9930. }
  9931. var _box$4 = new Box3();
  9932. var _vector$d = new Vector3();
  9933. class LineSegmentsGeometry extends InstancedBufferGeometry {
  9934. constructor() {
  9935. super();
  9936. this.isLineSegmentsGeometry = true;
  9937. this.type = 'LineSegmentsGeometry';
  9938. var positions = [-1, 2, 0, 1, 2, 0, -1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0, -1, -1, 0, 1, -1, 0];
  9939. var uvs = [-1, 2, 1, 2, -1, 1, 1, 1, -1, -1, 1, -1, -1, -2, 1, -2];
  9940. var index = [0, 2, 1, 2, 3, 1, 2, 4, 3, 4, 5, 3, 4, 6, 5, 6, 7, 5];
  9941. this.setIndex(index);
  9942. this.setAttribute('position', new Float32BufferAttribute(positions, 3));
  9943. this.setAttribute('uv', new Float32BufferAttribute(uvs, 2));
  9944. }
  9945. applyMatrix4(matrix) {
  9946. var start = this.attributes.instanceStart;
  9947. var end = this.attributes.instanceEnd;
  9948. if (start !== undefined) {
  9949. start.applyMatrix4(matrix);
  9950. end.applyMatrix4(matrix);
  9951. start.needsUpdate = true;
  9952. }
  9953. if (this.boundingBox !== null) {
  9954. this.computeBoundingBox();
  9955. }
  9956. if (this.boundingSphere !== null) {
  9957. this.computeBoundingSphere();
  9958. }
  9959. return this;
  9960. }
  9961. setPositions(array) {
  9962. var lineSegments;
  9963. if (array instanceof Float32Array) {
  9964. lineSegments = array;
  9965. } else if (Array.isArray(array)) {
  9966. lineSegments = new Float32Array(array);
  9967. }
  9968. var instanceBuffer = new InstancedInterleavedBuffer(lineSegments, 6, 1); // xyz, xyz
  9969. this.setAttribute('instanceStart', new InterleavedBufferAttribute(instanceBuffer, 3, 0)); // xyz
  9970. this.setAttribute('instanceEnd', new InterleavedBufferAttribute(instanceBuffer, 3, 3)); // xyz
  9971. //
  9972. this.computeBoundingBox();
  9973. this.computeBoundingSphere();
  9974. return this;
  9975. }
  9976. setColors(array) {
  9977. var colors;
  9978. if (array instanceof Float32Array) {
  9979. colors = array;
  9980. } else if (Array.isArray(array)) {
  9981. colors = new Float32Array(array);
  9982. }
  9983. var instanceColorBuffer = new InstancedInterleavedBuffer(colors, 6, 1); // rgb, rgb
  9984. this.setAttribute('instanceColorStart', new InterleavedBufferAttribute(instanceColorBuffer, 3, 0)); // rgb
  9985. this.setAttribute('instanceColorEnd', new InterleavedBufferAttribute(instanceColorBuffer, 3, 3)); // rgb
  9986. return this;
  9987. }
  9988. fromWireframeGeometry(geometry) {
  9989. this.setPositions(geometry.attributes.position.array);
  9990. return this;
  9991. }
  9992. fromEdgesGeometry(geometry) {
  9993. this.setPositions(geometry.attributes.position.array);
  9994. return this;
  9995. }
  9996. fromMesh(mesh) {
  9997. this.fromWireframeGeometry(new WireframeGeometry(mesh.geometry));
  9998. // set colors, maybe
  9999. return this;
  10000. }
  10001. fromLineSegments(lineSegments) {
  10002. var geometry = lineSegments.geometry;
  10003. this.setPositions(geometry.attributes.position.array); // assumes non-indexed
  10004. // set colors, maybe
  10005. return this;
  10006. }
  10007. computeBoundingBox() {
  10008. if (this.boundingBox === null) {
  10009. this.boundingBox = new Box3();
  10010. }
  10011. var start = this.attributes.instanceStart;
  10012. var end = this.attributes.instanceEnd;
  10013. if (start !== undefined && end !== undefined) {
  10014. this.boundingBox.setFromBufferAttribute(start);
  10015. _box$4.setFromBufferAttribute(end);
  10016. this.boundingBox.union(_box$4);
  10017. }
  10018. }
  10019. computeBoundingSphere() {
  10020. if (this.boundingSphere === null) {
  10021. this.boundingSphere = new Sphere();
  10022. }
  10023. if (this.boundingBox === null) {
  10024. this.computeBoundingBox();
  10025. }
  10026. var start = this.attributes.instanceStart;
  10027. var end = this.attributes.instanceEnd;
  10028. if (start !== undefined && end !== undefined) {
  10029. var center = this.boundingSphere.center;
  10030. this.boundingBox.getCenter(center);
  10031. var maxRadiusSq = 0;
  10032. for (var i = 0, il = start.count; i < il; i++) {
  10033. _vector$d.fromBufferAttribute(start, i);
  10034. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$d));
  10035. _vector$d.fromBufferAttribute(end, i);
  10036. maxRadiusSq = Math.max(maxRadiusSq, center.distanceToSquared(_vector$d));
  10037. }
  10038. this.boundingSphere.radius = Math.sqrt(maxRadiusSq);
  10039. if (isNaN(this.boundingSphere.radius)) {
  10040. console.error('THREE.LineSegmentsGeometry.computeBoundingSphere(): Computed radius is NaN. The instanced position data is likely to have NaN values.', this);
  10041. }
  10042. }
  10043. }
  10044. toJSON() {
  10045. // todo
  10046. }
  10047. applyMatrix(matrix) {
  10048. console.warn('THREE.LineSegmentsGeometry: applyMatrix() has been renamed to applyMatrix4().');
  10049. return this.applyMatrix4(matrix);
  10050. }
  10051. }
  10052. /**
  10053. * parameters = {
  10054. * color: <hex>,
  10055. * lineWidth: <float>,
  10056. * dashed: <boolean>,
  10057. * dashScale: <float>,
  10058. * dashSize: <float>,
  10059. * dashOffset: <float>,
  10060. * gapSize: <float>,
  10061. * resolution: <Vector2>, // to be set by renderer
  10062. * }
  10063. */
  10064. UniformsLib.line = {
  10065. /*
  10066. worldUnits: { value: 1 },
  10067. lineWidth: { value: 1 },
  10068. resolution: { value: new Vector2( 1, 1 ) },
  10069. dashOffset: { value: 0 },
  10070. dashScale: { value: 1 },
  10071. dashSize: { value: 1 },
  10072. gapSize: { value: 1 } // todo FIX - maybe change to totalSize
  10073. */
  10074. worldUnits: {
  10075. value: 1
  10076. },
  10077. lineWidth: {
  10078. value: 1
  10079. },
  10080. resolution: {
  10081. value: new Vector2(1, 1)
  10082. },
  10083. viewportOffset: {
  10084. value: new Vector2(0, 0)
  10085. },
  10086. //left, top
  10087. devicePixelRatio: {
  10088. value: window.devicePixelRatio
  10089. },
  10090. dashScale: {
  10091. value: 1
  10092. },
  10093. dashSize: {
  10094. value: 1
  10095. },
  10096. dashOffset: {
  10097. value: 0
  10098. },
  10099. gapSize: {
  10100. value: 1
  10101. },
  10102. opacity: {
  10103. value: 1
  10104. },
  10105. backColor: {
  10106. type: 'v3',
  10107. value: new Color("#ddd")
  10108. },
  10109. clipDistance: {
  10110. type: 'f',
  10111. value: 4
  10112. },
  10113. //消失距离
  10114. occlusionDistance: {
  10115. type: 'f',
  10116. value: 1
  10117. },
  10118. //变为backColor距离
  10119. maxClipFactor: {
  10120. type: 'f',
  10121. value: 1
  10122. },
  10123. //0-1
  10124. maxOcclusionFactor: {
  10125. type: 'f',
  10126. value: 1
  10127. },
  10128. //0-1
  10129. depthTexture: {
  10130. value: null
  10131. },
  10132. nearPlane: {
  10133. value: 0.1
  10134. },
  10135. farPlane: {
  10136. value: 100000
  10137. }
  10138. //uUseOrthographicCamera:{ type: "b", value: false },
  10139. };
  10140. ShaderLib['line'] = {
  10141. uniforms: UniformsUtils.merge([UniformsLib.common, UniformsLib.fog, UniformsLib.line]),
  10142. vertexShader: /* glsl */"\n\t\t#include <common>\n\t\t#include <color_pars_vertex>\n\t\t#include <fog_pars_vertex>\n\t\t#include <logdepthbuf_pars_vertex>\n\t\t#include <clipping_planes_pars_vertex>\n\n\t\tuniform float lineWidth;\n\t\tuniform vec2 resolution;\n uniform float devicePixelRatio; //add\n \n \n\t\tattribute vec3 instanceStart;\n\t\tattribute vec3 instanceEnd;\n\n\t\tattribute vec3 instanceColorStart;\n\t\tattribute vec3 instanceColorEnd;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashScale;\n\t\t\tattribute float instanceDistanceStart;\n\t\t\tattribute float instanceDistanceEnd;\n\t\t\tvarying float vLineDistance;\n\n\t\t#endif\n\n\t\tvoid trimSegment( const in vec4 start, inout vec4 end ) {\n\n\t\t\t// trim end segment so it terminates between the camera plane and the near plane\n\n\t\t\t// conservative estimate of the near plane\n\t\t\tfloat a = projectionMatrix[ 2 ][ 2 ]; // 3nd entry in 3th column\n\t\t\tfloat b = projectionMatrix[ 3 ][ 2 ]; // 3nd entry in 4th column\n\t\t\tfloat nearEstimate = - 0.5 * b / a;\n\n\t\t\tfloat alpha = ( nearEstimate - start.z ) / ( end.z - start.z );\n\n\t\t\tend.xyz = mix( start.xyz, end.xyz, alpha );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#ifdef USE_COLOR\n\n\t\t\t\tvColor.xyz = ( position.y < 0.5 ) ? instanceColorStart : instanceColorEnd;\n\n\t\t\t#endif\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvLineDistance = ( position.y < 0.5 ) ? dashScale * instanceDistanceStart : dashScale * instanceDistanceEnd;\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\tfloat aspect = resolution.x / resolution.y;\n\n\t\t\t// camera space\n\t\t\tvec4 start = modelViewMatrix * vec4( instanceStart, 1.0 );\n\t\t\tvec4 end = modelViewMatrix * vec4( instanceEnd, 1.0 );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\tworldStart = start.xyz;\n\t\t\t\tworldEnd = end.xyz;\n\n\t\t\t#else\n\n\t\t\t\tvUv = uv;\n\n\t\t\t#endif\n\n\t\t\t// special case for perspective projection, and segments that terminate either in, or behind, the camera plane\n\t\t\t// clearly the gpu firmware has a way of addressing this issue when projecting into ndc space\n\t\t\t// but we need to perform ndc-space calculations in the shader, so we must address this issue directly\n\t\t\t// perhaps there is a more elegant solution -- WestLangley\n\n\t\t\tbool perspective = ( projectionMatrix[ 2 ][ 3 ] == - 1.0 ); // 4th entry in the 3rd column\n\n\t\t\tif ( perspective ) {\n\n\t\t\t\tif ( start.z < 0.0 && end.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( start, end );\n\n\t\t\t\t} else if ( end.z < 0.0 && start.z >= 0.0 ) {\n\n\t\t\t\t\ttrimSegment( end, start );\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// clip space\n\t\t\tvec4 clipStart = projectionMatrix * start;\n\t\t\tvec4 clipEnd = projectionMatrix * end;\n\n\t\t\t// ndc space\n\t\t\tvec3 ndcStart = clipStart.xyz / clipStart.w;\n\t\t\tvec3 ndcEnd = clipEnd.xyz / clipEnd.w;\n\n\t\t\t// direction\n\t\t\tvec2 dir = ndcEnd.xy - ndcStart.xy;\n\n\t\t\t// account for clip-space aspect ratio\n\t\t\tdir.x *= aspect;\n\t\t\tdir = normalize( dir );\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\t// get the offset direction as perpendicular to the view vector\n\t\t\t\tvec3 worldDir = normalize( end.xyz - start.xyz );\n\t\t\t\tvec3 offset;\n\t\t\t\tif ( position.y < 0.5 ) {\n\n\t\t\t\t\toffset = normalize( cross( start.xyz, worldDir ) );\n\n\t\t\t\t} else {\n\n\t\t\t\t\toffset = normalize( cross( end.xyz, worldDir ) );\n\n\t\t\t\t}\n\n\t\t\t\t// sign flip\n\t\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t\tfloat forwardOffset = dot( worldDir, vec3( 0.0, 0.0, 1.0 ) );\n\n\t\t\t\t// don't extend the line if we're rendering dashes because we\n\t\t\t\t// won't be rendering the endcaps\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t// extend the line bounds to encompass endcaps\n\t\t\t\t\tstart.xyz += - worldDir * lineWidth * 0.5;\n\t\t\t\t\tend.xyz += worldDir * lineWidth * 0.5;\n\n\t\t\t\t\t// shift the position of the quad so it hugs the forward edge of the line\n\t\t\t\t\toffset.xy -= dir * forwardOffset;\n\t\t\t\t\toffset.z += 0.5;\n\n\t\t\t\t#endif\n\n\t\t\t\t// endcaps\n\t\t\t\tif ( position.y > 1.0 || position.y < 0.0 ) {\n\n\t\t\t\t\toffset.xy += dir * 2.0 * forwardOffset;\n\n\t\t\t\t}\n\n\t\t\t\t// adjust for lineWidth\n\t\t\t\toffset *= lineWidth * 0.5;\n\n\t\t\t\t// set the world position\n\t\t\t\tworldPos = ( position.y < 0.5 ) ? start : end;\n\t\t\t\tworldPos.xyz += offset;\n\n\t\t\t\t// project the worldpos\n\t\t\t\tvec4 clip = projectionMatrix * worldPos;\n\n\t\t\t\t// shift the depth of the projected points so the line\n\t\t\t\t// segments overlap neatly\n\t\t\t\tvec3 clipPose = ( position.y < 0.5 ) ? ndcStart : ndcEnd;\n\t\t\t\tclip.z = clipPose.z * clip.w;\n\n\t\t\t#else\n\n\t\t\t\tvec2 offset = vec2( dir.y, - dir.x );\n\t\t\t\t// undo aspect ratio adjustment\n\t\t\t\tdir.x /= aspect;\n\t\t\t\toffset.x /= aspect;\n\n\t\t\t\t// sign flip\n\t\t\t\tif ( position.x < 0.0 ) offset *= - 1.0;\n\n\t\t\t\t// endcaps\n\t\t\t\tif ( position.y < 0.0 ) {\n\n\t\t\t\t\toffset += - dir;\n\n\t\t\t\t} else if ( position.y > 1.0 ) {\n\n\t\t\t\t\toffset += dir;\n\n\t\t\t\t}\n\n\t\t\t\t// adjust for lineWidth\n\t\t\t\toffset *= lineWidth;\n\n\t\t\t\t// adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...\n\t\t\t\toffset /= resolution.y; //* devicePixelRatio;\n\n\t\t\t\t// select end\n\t\t\t\tvec4 clip = ( position.y < 0.5 ) ? clipStart : clipEnd;\n\n\t\t\t\t// back to clip space\n\t\t\t\toffset *= clip.w;\n\n\t\t\t\tclip.xy += offset;\n\n\t\t\t#endif\n\n\t\t\tgl_Position = clip;\n\n\t\t\tvec4 mvPosition = ( position.y < 0.5 ) ? start : end; // this is an approximation\n\n\t\t\t#include <logdepthbuf_vertex>\n\t\t\t#include <clipping_planes_vertex>\n\t\t\t#include <fog_vertex>\n\n\t\t}\n\t\t",
  10143. fragmentShader: /* glsl */"\n\t\tuniform vec3 diffuse;\n\t\tuniform float opacity;\n\t\tuniform float lineWidth;\n uniform bool uUseOrthographicCamera; \n\t\t#ifdef USE_DASH\n\n\t\t\tuniform float dashOffset;\n\t\t\tuniform float dashSize;\n\t\t\tuniform float gapSize; \n\t\t#endif\n \n //\u52A0\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n uniform sampler2D depthTexture;\n uniform float nearPlane;\n uniform float farPlane; \n uniform vec2 resolution;\n uniform vec2 viewportOffset;\n uniform vec3 backColor;\n uniform float occlusionDistance;\n uniform float clipDistance;\n uniform float maxClipFactor;\n uniform float maxOcclusionFactor;\n #endif\n\n\n\n\t\tvarying float vLineDistance;\n\n\t\t#ifdef WORLD_UNITS\n\n\t\t\tvarying vec4 worldPos;\n\t\t\tvarying vec3 worldStart;\n\t\t\tvarying vec3 worldEnd;\n\n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tvarying vec2 vUv;\n\n\t\t\t#endif\n\n\t\t#else\n\n\t\t\tvarying vec2 vUv;\n\n\t\t#endif\n\n\t\t#include <common>\n\t\t#include <color_pars_fragment>\n\t\t#include <fog_pars_fragment>\n\t\t#include <logdepthbuf_pars_fragment>\n\t\t#include <clipping_planes_pars_fragment>\n\n\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n float convertToLinear(float zValue)\n {\n //if(uUseOrthographicCamera){\n // return zValue*(farPlane-nearPlane)+nearPlane;\n //}else{ \n float z = zValue * 2.0 - 1.0;\n return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));\n //} \n }\n #endif\n\n\n\n\t\tvec2 closestLineToLine(vec3 p1, vec3 p2, vec3 p3, vec3 p4) {\n\n\t\t\tfloat mua;\n\t\t\tfloat mub;\n\n\t\t\tvec3 p13 = p1 - p3;\n\t\t\tvec3 p43 = p4 - p3;\n\n\t\t\tvec3 p21 = p2 - p1;\n\n\t\t\tfloat d1343 = dot( p13, p43 );\n\t\t\tfloat d4321 = dot( p43, p21 );\n\t\t\tfloat d1321 = dot( p13, p21 );\n\t\t\tfloat d4343 = dot( p43, p43 );\n\t\t\tfloat d2121 = dot( p21, p21 );\n\n\t\t\tfloat denom = d2121 * d4343 - d4321 * d4321;\n\n\t\t\tfloat numer = d1343 * d4321 - d1321 * d4343;\n\n\t\t\tmua = numer / denom;\n\t\t\tmua = clamp( mua, 0.0, 1.0 );\n\t\t\tmub = ( d1343 + d4321 * ( mua ) ) / d4343;\n\t\t\tmub = clamp( mub, 0.0, 1.0 );\n\n\t\t\treturn vec2( mua, mub );\n\n\t\t}\n\n\t\tvoid main() {\n\n\t\t\t#include <clipping_planes_fragment>\n\n\t\t\t/*#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n\n\t\t\t\tif ( mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize ) discard; // todo - FIX\n\n\t\t\t#endif*/\n \n\t\t\t#ifdef USE_DASH\n\n\t\t\t\tif ( vUv.y < - 1.0 || vUv.y > 1.0 ) discard; // discard endcaps\n \n \n bool unvisible = mod( vLineDistance + dashOffset, dashSize + gapSize ) > dashSize;\n //\u52A0\n #ifdef DASH_with_depth\n \n #else \n if (unvisible) discard; // todo - FIX\n #endif\n\t\t\t#endif\n \n\n\t\t\tfloat alpha = opacity;\n\n\t\t\t#ifdef WORLD_UNITS\n\n\t\t\t\t// Find the closest points on the view ray and the line segment\n\t\t\t\tvec3 rayEnd = normalize( worldPos.xyz ) * 1e5;\n\t\t\t\tvec3 lineDir = worldEnd - worldStart;\n\t\t\t\tvec2 params = closestLineToLine( worldStart, worldEnd, vec3( 0.0, 0.0, 0.0 ), rayEnd );\n\n\t\t\t\tvec3 p1 = worldStart + lineDir * params.x;\n\t\t\t\tvec3 p2 = rayEnd * params.y;\n\t\t\t\tvec3 delta = p1 - p2;\n\t\t\t\tfloat len = length( delta );\n\t\t\t\tfloat norm = len / lineWidth;\n\n\t\t\t\t#ifndef USE_DASH\n\n\t\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t\tfloat dnorm = fwidth( norm );\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 0.5 - dnorm, 0.5 + dnorm, norm );\n\n\t\t\t\t\t#else\n\n\t\t\t\t\t\tif ( norm > 0.5 ) {\n\n\t\t\t\t\t\t\tdiscard;\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t#endif\n\n\t\t\t\t#endif\n\n\t\t\t#else\n\n\t\t\t\t#ifdef USE_ALPHA_TO_COVERAGE\n\n\t\t\t\t\t// artifacts appear on some hardware if a derivative is taken within a conditional\n\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\tfloat len2 = a * a + b * b;\n\t\t\t\t\tfloat dlen = fwidth( len2 );\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\talpha = 1.0 - smoothstep( 1.0 - dlen, 1.0 + dlen, len2 );\n\n\t\t\t\t\t}\n\n\t\t\t\t#else\n\n\t\t\t\t\tif ( abs( vUv.y ) > 1.0 ) {\n\n\t\t\t\t\t\tfloat a = vUv.x;\n\t\t\t\t\t\tfloat b = ( vUv.y > 0.0 ) ? vUv.y - 1.0 : vUv.y + 1.0;\n\t\t\t\t\t\tfloat len2 = a * a + b * b;\n\n\t\t\t\t\t\tif ( len2 > 1.0 ) discard;\n\n\t\t\t\t\t}\n\n\t\t\t\t#endif\n\n\t\t\t#endif\n\n\t\t\tvec4 diffuseColor = vec4( diffuse, alpha );\n\n\n //\u52A0\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n \n float mixFactor = 0.0;\n float clipFactor = 0.0;\n\n float fragDepth = convertToLinear(gl_FragCoord.z);\n //gl_FragCoord\u5927\u5C0F\u4E3A viewport client\u5927\u5C0F \n vec2 depthTxtCoords = vec2(gl_FragCoord.x - viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;\n\n float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);\n\n float delta = fragDepth - textureDepth;\n\n if (delta > 0.0)\n {\n \n mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);\n clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);\n }\n \n if (clipFactor == 1.0)\n {\n discard;\n }\n \n vec4 backColor_ = vec4(backColor, opacity); //vec4(0.8,0.8,0.8, 0.8*opacity);\n \n #ifdef DASH_with_depth \n // \u53EA\u5728\u88AB\u906E\u4F4F\u7684\u90E8\u5206\u663E\u793A\u865A\u7EBF, \u6240\u4EE5\u82E5\u540C\u65F6\u662F\u865A\u7EBF\u4E0D\u53EF\u89C1\u90E8\u5206\u548C\u88AB\u906E\u4F4F\u65F6\uFF0C a\u4E3A0\n if(unvisible) backColor_.a = 0.0;\n #endif \n \n //vec4 diffuseColor = vec4(mix(diffuse, backColor_, mixFactor), opacity*(1.0 - clipFactor));\n \n \n \n diffuseColor = mix(diffuseColor, backColor_ , mixFactor); \n \n \n diffuseColor.a *= (1.0 - clipFactor); \n \n #endif\n\n\n\n\t\t\t#include <logdepthbuf_fragment>\n\t\t\t#include <color_fragment>\n\n\t\t\t//gl_FragColor = vec4( diffuseColor.rgb, alpha );\n\t\t\tgl_FragColor = vec4( diffuseColor.rgb, diffuseColor.a );\n\t\t\t#include <tonemapping_fragment>\n\t\t\t#include <encodings_fragment>\n\t\t\t#include <fog_fragment>\n\t\t\t#include <premultiplied_alpha_fragment>\n\n\t\t}\n\t\t"
  10144. };
  10145. class LineMaterial extends ShaderMaterial {
  10146. constructor(parameters) {
  10147. var {
  10148. vs,
  10149. fs
  10150. } = Potree.Common.changeShaderToWebgl2(ShaderLib['line'].vertexShader, ShaderLib['line'].fragmentShader, 'ShaderMaterial');
  10151. super({
  10152. type: 'LineMaterial',
  10153. uniforms: UniformsUtils.clone(ShaderLib['line'].uniforms),
  10154. vertexShader: vs,
  10155. fragmentShader: fs,
  10156. clipping: true // required for clipping support
  10157. });
  10158. this.isLineMaterial = true;
  10159. this.lineWidth_ = 0;
  10160. this.supportExtDepth = parameters.supportExtDepth;
  10161. this.depthTestWhenPick = false; //pick时是否识别点云等
  10162. if (parameters.color) {
  10163. this.color = new Color(parameters.color);
  10164. }
  10165. if (parameters.backColor) {
  10166. this.uniforms.backColor.value = new Color(parameters.backColor);
  10167. }
  10168. if (parameters.clipDistance) {
  10169. this.uniforms.clipDistance.value = parameters.clipDistance;
  10170. }
  10171. if (parameters.occlusionDistance) {
  10172. this.uniforms.occlusionDistance.value = parameters.occlusionDistance;
  10173. }
  10174. if (parameters.maxClipFactor) {
  10175. this.uniforms.maxClipFactor.value = parameters.maxClipFactor;
  10176. }
  10177. Object.defineProperties(this, {
  10178. color: {
  10179. enumerable: true,
  10180. get: function get() {
  10181. return this.uniforms.diffuse.value;
  10182. },
  10183. set: function set(value) {
  10184. this.uniforms.diffuse.value = value;
  10185. }
  10186. },
  10187. worldUnits: {
  10188. enumerable: true,
  10189. get: function get() {
  10190. return 'WORLD_UNITS' in this.defines;
  10191. },
  10192. set: function set(value) {
  10193. if (value === true) {
  10194. this.defines.WORLD_UNITS = '';
  10195. } else {
  10196. delete this.defines.WORLD_UNITS;
  10197. }
  10198. }
  10199. },
  10200. lineWidth: {
  10201. enumerable: true,
  10202. get: function get() {
  10203. return this.lineWidth_; //this.uniforms.lineWidth.value;
  10204. },
  10205. set: function set(value) {
  10206. this.uniforms.lineWidth.value = value * window.devicePixelRatio;
  10207. this.lineWidth_ = value;
  10208. }
  10209. },
  10210. dashed: {
  10211. enumerable: true,
  10212. get: function get() {
  10213. return Boolean('USE_DASH' in this.defines);
  10214. },
  10215. set(value) {
  10216. if (Boolean(value) !== Boolean('USE_DASH' in this.defines)) {
  10217. this.needsUpdate = true;
  10218. }
  10219. if (value === true) {
  10220. this.defines.USE_DASH = '';
  10221. } else {
  10222. delete this.defines.USE_DASH;
  10223. }
  10224. }
  10225. },
  10226. dashScale: {
  10227. enumerable: true,
  10228. get: function get() {
  10229. return this.uniforms.dashScale.value;
  10230. },
  10231. set: function set(value) {
  10232. this.uniforms.dashScale.value = value;
  10233. }
  10234. },
  10235. dashSize: {
  10236. enumerable: true,
  10237. get: function get() {
  10238. return this.uniforms.dashSize.value;
  10239. },
  10240. set: function set(value) {
  10241. this.uniforms.dashSize.value = value;
  10242. }
  10243. },
  10244. dashOffset: {
  10245. enumerable: true,
  10246. get: function get() {
  10247. return this.uniforms.dashOffset.value;
  10248. },
  10249. set: function set(value) {
  10250. this.uniforms.dashOffset.value = value;
  10251. }
  10252. },
  10253. gapSize: {
  10254. enumerable: true,
  10255. get: function get() {
  10256. return this.uniforms.gapSize.value;
  10257. },
  10258. set: function set(value) {
  10259. this.uniforms.gapSize.value = value;
  10260. }
  10261. },
  10262. opacity: {
  10263. enumerable: true,
  10264. get: function get() {
  10265. return this.uniforms.opacity.value;
  10266. },
  10267. set: function set(value) {
  10268. this.uniforms.opacity.value = value;
  10269. }
  10270. },
  10271. resolution: {
  10272. enumerable: true,
  10273. get: function get() {
  10274. return this.uniforms.resolution.value;
  10275. },
  10276. set: function set(value) {
  10277. this.uniforms.resolution.value.copy(value);
  10278. }
  10279. },
  10280. alphaToCoverage: {
  10281. enumerable: true,
  10282. get: function get() {
  10283. return Boolean('USE_ALPHA_TO_COVERAGE' in this.defines);
  10284. },
  10285. set: function set(value) {
  10286. if (Boolean(value) !== Boolean('USE_ALPHA_TO_COVERAGE' in this.defines)) {
  10287. this.needsUpdate = true;
  10288. }
  10289. if (value === true) {
  10290. this.defines.USE_ALPHA_TO_COVERAGE = '';
  10291. this.extensions.derivatives = true;
  10292. } else {
  10293. delete this.defines.USE_ALPHA_TO_COVERAGE;
  10294. this.extensions.derivatives = false;
  10295. }
  10296. }
  10297. },
  10298. dashWithDepth: {
  10299. //add
  10300. enumerable: true,
  10301. get: function get() {
  10302. return 'DASH_with_depth' in this.defines;
  10303. },
  10304. set: function set(value) {
  10305. value = value && !!this.supportExtDepth;
  10306. if (value != this.dashWithDepth) {
  10307. if (value) {
  10308. this.defines.DASH_with_depth = '';
  10309. } else {
  10310. delete this.defines.DASH_with_depth;
  10311. }
  10312. this.needsUpdate = true;
  10313. }
  10314. }
  10315. }
  10316. });
  10317. this.events = {
  10318. setSize: e => {
  10319. //如果出现横条状的异常,往往是viewportOffset出错 //地图不需要
  10320. var viewport = e.viewport;
  10321. //console.log(viewport.name, viewport.resolution2)
  10322. this.uniforms.resolution.value.copy(viewport.resolution2);
  10323. this.uniforms.devicePixelRatio.value = window.devicePixelRatio;
  10324. this.lineWidth = this.lineWidth_; //update
  10325. if (!this.realUseDepth || !e.viewport) return;
  10326. var viewportOffset = viewport.offset || new THREE.Vector2();
  10327. this.uniforms.viewportOffset.value.copy(viewportOffset);
  10328. },
  10329. render: e => {
  10330. //before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  10331. this.useDepth && this.updateDepthParams(e);
  10332. var viewport = e.viewport || viewer.mainViewport;
  10333. if (viewport != this.lastViewport) {
  10334. //当mapViewer要渲染测量线后,就需要变viewport
  10335. this.events.setSize({
  10336. viewport
  10337. });
  10338. }
  10339. this.lastViewport = viewport;
  10340. }
  10341. };
  10342. this.setValues(parameters);
  10343. var viewport = viewer.mainViewport;
  10344. this.events.setSize({
  10345. viewport
  10346. });
  10347. viewer.addEventListener('resize', this.events.setSize);
  10348. viewer.addEventListener("render.begin", this.events.render);
  10349. }
  10350. get useDepth() {
  10351. return this.useDepth_;
  10352. }
  10353. set useDepth(value) {
  10354. value = value && this.supportExtDepth; //如果不支持 EXT_DEPTH 的话会失效
  10355. if (this.useDepth_ != value) {
  10356. this.setRealDepth(value);
  10357. this.useDepth_ = value;
  10358. }
  10359. }
  10360. setRealDepth(useDepth, viewport) {
  10361. //确实使用到depthTex
  10362. if (this.realUseDepth != useDepth) {
  10363. if (useDepth) {
  10364. this.defines.useDepth = '';
  10365. } else {
  10366. delete this.defines.useDepth;
  10367. }
  10368. this.realUseDepth = useDepth;
  10369. if (this.autoDepthTest) this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest
  10370. this.needsUpdate = true;
  10371. if (!viewport) viewport = viewer.mainViewport; //暂时这么设置
  10372. useDepth && this.events.setSize({
  10373. viewport
  10374. });
  10375. }
  10376. }
  10377. updateDepthParams() {
  10378. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  10379. var viewport = e.viewport || viewer.mainViewport;
  10380. var camera = viewport.camera;
  10381. var hasDepth = this.useDepth && camera.isPerspectiveCamera && (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL);
  10382. this.setRealDepth(hasDepth, viewport);
  10383. if (hasDepth) {
  10384. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  10385. this.uniforms.nearPlane.value = camera.near;
  10386. this.uniforms.farPlane.value = camera.far;
  10387. }
  10388. //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera
  10389. }
  10390. }
  10391. var _start$2 = new Vector3();
  10392. var _end$2 = new Vector3();
  10393. var _start4 = new Vector4();
  10394. var _end4 = new Vector4();
  10395. var _ssOrigin = new Vector4();
  10396. var _ssOrigin3 = new Vector3();
  10397. var _mvMatrix = new Matrix4();
  10398. var _line = new Line3();
  10399. var _closestPoint = new Vector3();
  10400. var _box$5 = new Box3();
  10401. var _sphere$4 = new Sphere();
  10402. var _clipToWorldVector = new Vector4();
  10403. var _ray$3, _instanceStart, _instanceEnd, _lineWidth;
  10404. // Returns the margin required to expand by in world space given the distance from the camera,
  10405. // line width, resolution, and camera projection
  10406. function getWorldSpaceHalfWidth(camera, distance, resolution) {
  10407. // transform into clip space, adjust the x and y values by the pixel width offset, then
  10408. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  10409. // width does not need to be halved.
  10410. _clipToWorldVector.set(0, 0, -distance, 1.0).applyMatrix4(camera.projectionMatrix);
  10411. _clipToWorldVector.multiplyScalar(1.0 / _clipToWorldVector.w);
  10412. _clipToWorldVector.x = _lineWidth / resolution.width;
  10413. _clipToWorldVector.y = _lineWidth / resolution.height;
  10414. _clipToWorldVector.applyMatrix4(camera.projectionMatrixInverse);
  10415. _clipToWorldVector.multiplyScalar(1.0 / _clipToWorldVector.w);
  10416. return Math.abs(Math.max(_clipToWorldVector.x, _clipToWorldVector.y));
  10417. }
  10418. function raycastWorldUnits(lineSegments, intersects) {
  10419. for (var i = 0, l = _instanceStart.count; i < l; i++) {
  10420. _line.start.fromBufferAttribute(_instanceStart, i);
  10421. _line.end.fromBufferAttribute(_instanceEnd, i);
  10422. var pointOnLine = new Vector3();
  10423. var point = new Vector3();
  10424. _ray$3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
  10425. var isInside = point.distanceTo(pointOnLine) < _lineWidth * 0.5;
  10426. if (isInside) {
  10427. intersects.push({
  10428. point,
  10429. pointOnLine,
  10430. distance: _ray$3.origin.distanceTo(point),
  10431. object: lineSegments,
  10432. face: null,
  10433. faceIndex: i,
  10434. uv: null,
  10435. uv2: null
  10436. });
  10437. }
  10438. }
  10439. }
  10440. function raycastScreenSpace(lineSegments, camera, intersects) {
  10441. var projectionMatrix = camera.projectionMatrix;
  10442. var material = lineSegments.material;
  10443. var resolution = material.resolution;
  10444. var matrixWorld = lineSegments.matrixWorld;
  10445. var geometry = lineSegments.geometry;
  10446. var instanceStart = geometry.attributes.instanceStart;
  10447. var instanceEnd = geometry.attributes.instanceEnd;
  10448. var near = -camera.near;
  10449. //
  10450. // pick a point 1 unit out along the ray to avoid the ray origin
  10451. // sitting at the camera origin which will cause "w" to be 0 when
  10452. // applying the projection matrix.
  10453. _ray$3.at(1, _ssOrigin);
  10454. // ndc space [ - 1.0, 1.0 ]
  10455. _ssOrigin.w = 1;
  10456. _ssOrigin.applyMatrix4(camera.matrixWorldInverse);
  10457. _ssOrigin.applyMatrix4(projectionMatrix);
  10458. _ssOrigin.multiplyScalar(1 / _ssOrigin.w);
  10459. // screen space
  10460. _ssOrigin.x *= resolution.x / 2;
  10461. _ssOrigin.y *= resolution.y / 2;
  10462. _ssOrigin.z = 0;
  10463. _ssOrigin3.copy(_ssOrigin);
  10464. _mvMatrix.multiplyMatrices(camera.matrixWorldInverse, matrixWorld);
  10465. for (var i = 0, l = instanceStart.count; i < l; i++) {
  10466. _start4.fromBufferAttribute(instanceStart, i);
  10467. _end4.fromBufferAttribute(instanceEnd, i);
  10468. _start4.w = 1;
  10469. _end4.w = 1;
  10470. // camera space
  10471. _start4.applyMatrix4(_mvMatrix);
  10472. _end4.applyMatrix4(_mvMatrix);
  10473. // skip the segment if it's entirely behind the camera
  10474. var isBehindCameraNear = _start4.z > near && _end4.z > near;
  10475. if (isBehindCameraNear) {
  10476. continue;
  10477. }
  10478. // trim the segment if it extends behind camera near
  10479. if (_start4.z > near) {
  10480. var deltaDist = _start4.z - _end4.z;
  10481. var t = (_start4.z - near) / deltaDist;
  10482. _start4.lerp(_end4, t);
  10483. } else if (_end4.z > near) {
  10484. var _deltaDist = _end4.z - _start4.z;
  10485. var _t = (_end4.z - near) / _deltaDist;
  10486. _end4.lerp(_start4, _t);
  10487. }
  10488. // clip space
  10489. _start4.applyMatrix4(projectionMatrix);
  10490. _end4.applyMatrix4(projectionMatrix);
  10491. // ndc space [ - 1.0, 1.0 ]
  10492. _start4.multiplyScalar(1 / _start4.w);
  10493. _end4.multiplyScalar(1 / _end4.w);
  10494. // screen space
  10495. _start4.x *= resolution.x / 2;
  10496. _start4.y *= resolution.y / 2;
  10497. _end4.x *= resolution.x / 2;
  10498. _end4.y *= resolution.y / 2;
  10499. // create 2d segment
  10500. _line.start.copy(_start4);
  10501. _line.start.z = 0;
  10502. _line.end.copy(_end4);
  10503. _line.end.z = 0;
  10504. // get closest point on ray to segment
  10505. var param = _line.closestPointToPointParameter(_ssOrigin3, true);
  10506. _line.at(param, _closestPoint);
  10507. // check if the intersection point is within clip space
  10508. var zPos = MathUtils.lerp(_start4.z, _end4.z, param);
  10509. var isInClipSpace = zPos >= -1 && zPos <= 1;
  10510. var isInside = _ssOrigin3.distanceTo(_closestPoint) < _lineWidth * 0.5;
  10511. if (isInClipSpace && isInside) {
  10512. _line.start.fromBufferAttribute(instanceStart, i);
  10513. _line.end.fromBufferAttribute(instanceEnd, i);
  10514. _line.start.applyMatrix4(matrixWorld);
  10515. _line.end.applyMatrix4(matrixWorld);
  10516. var pointOnLine = new Vector3();
  10517. var point = new Vector3();
  10518. _ray$3.distanceSqToSegment(_line.start, _line.end, point, pointOnLine);
  10519. intersects.push({
  10520. point: point,
  10521. pointOnLine: pointOnLine,
  10522. distance: _ray$3.origin.distanceTo(point),
  10523. object: lineSegments,
  10524. face: null,
  10525. faceIndex: i,
  10526. uv: null,
  10527. uv2: null
  10528. });
  10529. }
  10530. }
  10531. }
  10532. class LineSegments2 extends Mesh {
  10533. constructor() {
  10534. var geometry = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new LineSegmentsGeometry();
  10535. var material = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new LineMaterial({
  10536. color: Math.random() * 0xffffff
  10537. });
  10538. super(geometry, material);
  10539. this.isLineSegments2 = true;
  10540. this.type = 'LineSegments2';
  10541. }
  10542. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  10543. computeLineDistances() {
  10544. var geometry = this.geometry;
  10545. var instanceStart = geometry.attributes.instanceStart;
  10546. var instanceEnd = geometry.attributes.instanceEnd;
  10547. var lineDistances = new Float32Array(2 * instanceStart.count);
  10548. for (var i = 0, j = 0, l = instanceStart.count; i < l; i++, j += 2) {
  10549. _start$2.fromBufferAttribute(instanceStart, i);
  10550. _end$2.fromBufferAttribute(instanceEnd, i);
  10551. lineDistances[j] = j === 0 ? 0 : lineDistances[j - 1];
  10552. lineDistances[j + 1] = lineDistances[j] + _start$2.distanceTo(_end$2);
  10553. }
  10554. var instanceDistanceBuffer = new InstancedInterleavedBuffer(lineDistances, 2, 1); // d0, d1
  10555. geometry.setAttribute('instanceDistanceStart', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 0)); // d0
  10556. geometry.setAttribute('instanceDistanceEnd', new InterleavedBufferAttribute(instanceDistanceBuffer, 1, 1)); // d1
  10557. return this;
  10558. }
  10559. raycast(raycaster, intersects) {
  10560. var worldUnits = this.material.worldUnits;
  10561. var camera = raycaster.camera;
  10562. if (camera === null && !worldUnits) {
  10563. console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.');
  10564. }
  10565. var threshold = raycaster.params.Line2 !== undefined ? raycaster.params.Line2.threshold || 0 : 0;
  10566. _ray$3 = raycaster.ray;
  10567. var matrixWorld = this.matrixWorld;
  10568. var geometry = this.geometry;
  10569. var material = this.material;
  10570. _lineWidth = material.lineWidth + threshold;
  10571. _instanceStart = geometry.attributes.instanceStart;
  10572. _instanceEnd = geometry.attributes.instanceEnd;
  10573. // check if we intersect the sphere bounds
  10574. if (geometry.boundingSphere === null) {
  10575. geometry.computeBoundingSphere();
  10576. }
  10577. _sphere$4.copy(geometry.boundingSphere).applyMatrix4(matrixWorld);
  10578. // increase the sphere bounds by the worst case line screen space width
  10579. var sphereMargin;
  10580. if (worldUnits) {
  10581. sphereMargin = _lineWidth * 0.5;
  10582. } else {
  10583. var distanceToSphere = Math.max(camera.near, _sphere$4.distanceToPoint(_ray$3.origin));
  10584. sphereMargin = getWorldSpaceHalfWidth(camera, distanceToSphere, material.resolution);
  10585. }
  10586. _sphere$4.radius += sphereMargin;
  10587. if (_ray$3.intersectsSphere(_sphere$4) === false) {
  10588. return;
  10589. }
  10590. // check if we intersect the box bounds
  10591. if (geometry.boundingBox === null) {
  10592. geometry.computeBoundingBox();
  10593. }
  10594. _box$5.copy(geometry.boundingBox).applyMatrix4(matrixWorld);
  10595. // increase the box bounds by the worst case line width
  10596. var boxMargin;
  10597. if (worldUnits) {
  10598. boxMargin = _lineWidth * 0.5;
  10599. } else {
  10600. var distanceToBox = Math.max(camera.near, _box$5.distanceToPoint(_ray$3.origin));
  10601. boxMargin = getWorldSpaceHalfWidth(camera, distanceToBox, material.resolution);
  10602. }
  10603. _box$5.expandByScalar(boxMargin);
  10604. if (_ray$3.intersectsBox(_box$5) === false) {
  10605. return;
  10606. }
  10607. if (worldUnits) {
  10608. raycastWorldUnits(this, intersects);
  10609. } else {
  10610. raycastScreenSpace(this, camera, intersects);
  10611. }
  10612. }
  10613. }
  10614. class LineGeometry extends LineSegmentsGeometry {
  10615. constructor() {
  10616. super();
  10617. this.isLineGeometry = true;
  10618. this.type = 'LineGeometry';
  10619. }
  10620. setPositions(array) {
  10621. //见potree.shim.js
  10622. // converts [ x1, y1, z1, x2, y2, z2, ... ] to pairs format
  10623. var length = array.length - 3;
  10624. var points = new Float32Array(2 * length);
  10625. for (var i = 0; i < length; i += 3) {
  10626. points[2 * i] = array[i];
  10627. points[2 * i + 1] = array[i + 1];
  10628. points[2 * i + 2] = array[i + 2];
  10629. points[2 * i + 3] = array[i + 3];
  10630. points[2 * i + 4] = array[i + 4];
  10631. points[2 * i + 5] = array[i + 5];
  10632. }
  10633. super.setPositions(points);
  10634. return this;
  10635. }
  10636. setColors(array) {
  10637. // converts [ r1, g1, b1, r2, g2, b2, ... ] to pairs format
  10638. var length = array.length - 3;
  10639. var colors = new Float32Array(2 * length);
  10640. for (var i = 0; i < length; i += 3) {
  10641. colors[2 * i] = array[i];
  10642. colors[2 * i + 1] = array[i + 1];
  10643. colors[2 * i + 2] = array[i + 2];
  10644. colors[2 * i + 3] = array[i + 3];
  10645. colors[2 * i + 4] = array[i + 4];
  10646. colors[2 * i + 5] = array[i + 5];
  10647. }
  10648. super.setColors(colors);
  10649. return this;
  10650. }
  10651. fromLine(line) {
  10652. var geometry = line.geometry;
  10653. this.setPositions(geometry.attributes.position.array); // assumes non-indexed
  10654. // set colors, maybe
  10655. return this;
  10656. }
  10657. }
  10658. class Line2 extends LineSegments2 {
  10659. constructor() {
  10660. var geometry = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new LineGeometry();
  10661. var material = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new LineMaterial({
  10662. color: Math.random() * 0xffffff
  10663. });
  10664. super(geometry, material);
  10665. this.isLine2 = true;
  10666. this.type = 'Line2';
  10667. }
  10668. }
  10669. //old
  10670. function createHeightLine() {
  10671. var lineGeometry = new LineGeometry();
  10672. lineGeometry.setPositions([0, 0, 0, 0, 0, 0]);
  10673. var lineMaterial = new LineMaterial({
  10674. color: 0x00ff00,
  10675. dashSize: 5,
  10676. gapSize: 2,
  10677. linewidth: 2,
  10678. resolution: new Vector2(1000, 1000)
  10679. });
  10680. lineMaterial.depthTest = false;
  10681. var heightEdge = new Line2(lineGeometry, lineMaterial);
  10682. heightEdge.visible = false;
  10683. //this.add(this.heightEdge);
  10684. return heightEdge;
  10685. }
  10686. function createHeightLabel() {
  10687. var heightLabel = new TextSprite$1('');
  10688. heightLabel.setTextColor({
  10689. r: 140,
  10690. g: 250,
  10691. b: 140,
  10692. a: 1.0
  10693. });
  10694. heightLabel.setBorderColor({
  10695. r: 0,
  10696. g: 0,
  10697. b: 0,
  10698. a: 1.0
  10699. });
  10700. heightLabel.setBackgroundColor({
  10701. r: 0,
  10702. g: 0,
  10703. b: 0,
  10704. a: 1.0
  10705. });
  10706. heightLabel.fontsize = 16;
  10707. heightLabel.material.depthTest = false;
  10708. heightLabel.material.opacity = 1;
  10709. heightLabel.visible = false;
  10710. return heightLabel;
  10711. }
  10712. function createAreaLabel() {
  10713. var areaLabel = new TextSprite$1('');
  10714. areaLabel.setTextColor({
  10715. r: 140,
  10716. g: 250,
  10717. b: 140,
  10718. a: 1.0
  10719. });
  10720. areaLabel.setBorderColor({
  10721. r: 0,
  10722. g: 0,
  10723. b: 0,
  10724. a: 1.0
  10725. });
  10726. areaLabel.setBackgroundColor({
  10727. r: 0,
  10728. g: 0,
  10729. b: 0,
  10730. a: 1.0
  10731. });
  10732. areaLabel.fontsize = 16;
  10733. areaLabel.material.depthTest = false;
  10734. areaLabel.material.opacity = 1;
  10735. areaLabel.visible = false;
  10736. return areaLabel;
  10737. }
  10738. function createCircleRadiusLabel() {
  10739. var circleRadiusLabel = new TextSprite$1("");
  10740. circleRadiusLabel.setTextColor({
  10741. r: 140,
  10742. g: 250,
  10743. b: 140,
  10744. a: 1.0
  10745. });
  10746. circleRadiusLabel.setBorderColor({
  10747. r: 0,
  10748. g: 0,
  10749. b: 0,
  10750. a: 1.0
  10751. });
  10752. circleRadiusLabel.setBackgroundColor({
  10753. r: 0,
  10754. g: 0,
  10755. b: 0,
  10756. a: 1.0
  10757. });
  10758. circleRadiusLabel.fontsize = 16;
  10759. circleRadiusLabel.material.depthTest = false;
  10760. circleRadiusLabel.material.opacity = 1;
  10761. circleRadiusLabel.visible = false;
  10762. return circleRadiusLabel;
  10763. }
  10764. function createCircleRadiusLine() {
  10765. var lineGeometry = new LineGeometry();
  10766. lineGeometry.setPositions([0, 0, 0, 0, 0, 0]);
  10767. var lineMaterial = new LineMaterial({
  10768. color: 0xff0000,
  10769. linewidth: 2,
  10770. resolution: new Vector2(1000, 1000),
  10771. gapSize: 1,
  10772. dashed: true
  10773. });
  10774. lineMaterial.depthTest = false;
  10775. var circleRadiusLine = new Line2(lineGeometry, lineMaterial);
  10776. circleRadiusLine.visible = false;
  10777. return circleRadiusLine;
  10778. }
  10779. function createCircleLine() {
  10780. var coordinates = [];
  10781. var n = 128;
  10782. for (var i = 0; i <= n; i++) {
  10783. var u0 = 2 * Math.PI * (i / n);
  10784. var u1 = 2 * Math.PI * (i + 1) / n;
  10785. var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0);
  10786. var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0);
  10787. coordinates.push(...p0.toArray(), ...p1.toArray());
  10788. }
  10789. var geometry = new LineGeometry();
  10790. geometry.setPositions(coordinates);
  10791. var material = new LineMaterial({
  10792. color: 0xff0000,
  10793. dashSize: 5,
  10794. gapSize: 2,
  10795. linewidth: 2,
  10796. resolution: new Vector2(1000, 1000)
  10797. });
  10798. material.depthTest = false;
  10799. var circleLine = new Line2(geometry, material);
  10800. circleLine.visible = false;
  10801. circleLine.computeLineDistances();
  10802. return circleLine;
  10803. }
  10804. function createCircleCenter() {
  10805. var sg = new SphereGeometry(1, 32, 32);
  10806. var sm = new MeshNormalMaterial();
  10807. var circleCenter = new Mesh(sg, sm);
  10808. circleCenter.visible = false;
  10809. return circleCenter;
  10810. }
  10811. function createLine() {
  10812. var geometry = new LineGeometry();
  10813. geometry.setPositions([0, 0, 0, 0, 0, 0]);
  10814. var material = new LineMaterial({
  10815. color: 0xff0000,
  10816. linewidth: 2,
  10817. resolution: new Vector2(1000, 1000),
  10818. gapSize: 1,
  10819. dashed: true
  10820. });
  10821. material.depthTest = false;
  10822. var line = new Line2(geometry, material);
  10823. return line;
  10824. }
  10825. function createCircle() {
  10826. var coordinates = [];
  10827. var n = 128;
  10828. for (var i = 0; i <= n; i++) {
  10829. var u0 = 2 * Math.PI * (i / n);
  10830. var u1 = 2 * Math.PI * (i + 1) / n;
  10831. var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0);
  10832. var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0);
  10833. coordinates.push(...p0.toArray(), ...p1.toArray());
  10834. }
  10835. var geometry = new LineGeometry();
  10836. geometry.setPositions(coordinates);
  10837. var material = new LineMaterial({
  10838. color: 0xff0000,
  10839. dashSize: 5,
  10840. gapSize: 2,
  10841. linewidth: 2,
  10842. resolution: new Vector2(1000, 1000)
  10843. });
  10844. material.depthTest = false;
  10845. var line = new Line2(geometry, material);
  10846. line.computeLineDistances();
  10847. return line;
  10848. }
  10849. function createAzimuth() {
  10850. var azimuth = {
  10851. label: null,
  10852. center: null,
  10853. target: null,
  10854. north: null,
  10855. centerToNorth: null,
  10856. centerToTarget: null,
  10857. centerToTargetground: null,
  10858. targetgroundToTarget: null,
  10859. circle: null,
  10860. node: null
  10861. };
  10862. var sg = new SphereGeometry(1, 32, 32);
  10863. var sm = new MeshNormalMaterial();
  10864. {
  10865. var label = new TextSprite$1("");
  10866. label.setTextColor({
  10867. r: 140,
  10868. g: 250,
  10869. b: 140,
  10870. a: 1.0
  10871. });
  10872. label.setBorderColor({
  10873. r: 0,
  10874. g: 0,
  10875. b: 0,
  10876. a: 1.0
  10877. });
  10878. label.setBackgroundColor({
  10879. r: 0,
  10880. g: 0,
  10881. b: 0,
  10882. a: 1.0
  10883. });
  10884. label.fontsize = 16;
  10885. label.material.depthTest = false;
  10886. label.material.opacity = 1;
  10887. azimuth.label = label;
  10888. }
  10889. azimuth.center = new Mesh(sg, sm);
  10890. azimuth.target = new Mesh(sg, sm);
  10891. azimuth.north = new Mesh(sg, sm);
  10892. azimuth.centerToNorth = createLine();
  10893. azimuth.centerToTarget = createLine();
  10894. azimuth.centerToTargetground = createLine();
  10895. azimuth.targetgroundToTarget = createLine();
  10896. azimuth.circle = createCircle();
  10897. azimuth.node = new Object3D();
  10898. azimuth.node.add(azimuth.centerToNorth, azimuth.centerToTarget, azimuth.centerToTargetground, azimuth.targetgroundToTarget, azimuth.circle, azimuth.label, azimuth.center, azimuth.target, azimuth.north);
  10899. return azimuth;
  10900. }
  10901. class Measure extends Object3D {
  10902. constructor() {
  10903. super();
  10904. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  10905. this.name = 'Measure_' + this.constructor.counter;
  10906. this.points = [];
  10907. this._showDistances = true;
  10908. this._showCoordinates = false;
  10909. this._showArea = false;
  10910. this._closed = true;
  10911. this._showAngles = false;
  10912. this._showCircle = false;
  10913. this._showHeight = false;
  10914. this._showEdges = true;
  10915. this._showAzimuth = false;
  10916. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  10917. this.sphereGeometry = new SphereGeometry(0.4, 10, 10);
  10918. this.color = new Color(0xff0000);
  10919. this.spheres = [];
  10920. this.edges = [];
  10921. this.sphereLabels = [];
  10922. this.edgeLabels = [];
  10923. this.angleLabels = [];
  10924. this.coordinateLabels = [];
  10925. this.heightEdge = createHeightLine();
  10926. this.heightLabel = createHeightLabel();
  10927. this.areaLabel = createAreaLabel();
  10928. this.circleRadiusLabel = createCircleRadiusLabel();
  10929. this.circleRadiusLine = createCircleRadiusLine();
  10930. this.circleLine = createCircleLine();
  10931. this.circleCenter = createCircleCenter();
  10932. this.azimuth = createAzimuth();
  10933. this.add(this.heightEdge);
  10934. this.add(this.heightLabel);
  10935. this.add(this.areaLabel);
  10936. this.add(this.circleRadiusLabel);
  10937. this.add(this.circleRadiusLine);
  10938. this.add(this.circleLine);
  10939. this.add(this.circleCenter);
  10940. this.add(this.azimuth.node);
  10941. }
  10942. createSphereMaterial() {
  10943. var sphereMaterial = new MeshLambertMaterial({
  10944. //shading: THREE.SmoothShading,
  10945. color: this.color,
  10946. depthTest: false,
  10947. depthWrite: false
  10948. });
  10949. return sphereMaterial;
  10950. }
  10951. addMarker(point) {
  10952. if (point.x != null) {
  10953. point = {
  10954. position: point
  10955. };
  10956. } else if (point instanceof Array) {
  10957. point = {
  10958. position: new Vector3(...point)
  10959. };
  10960. }
  10961. this.points.push(point);
  10962. // sphere
  10963. var sphere = new Mesh(this.sphereGeometry, this.createSphereMaterial());
  10964. this.add(sphere);
  10965. this.spheres.push(sphere);
  10966. {
  10967. // edges
  10968. var lineGeometry = new LineGeometry();
  10969. lineGeometry.setPositions([0, 0, 0, 0, 0, 0]);
  10970. var lineMaterial = new LineMaterial({
  10971. color: 0xff0000,
  10972. linewidth: 2,
  10973. resolution: new Vector2(1000, 1000)
  10974. });
  10975. lineMaterial.depthTest = false;
  10976. var edge = new Line2(lineGeometry, lineMaterial);
  10977. edge.visible = true;
  10978. this.add(edge);
  10979. this.edges.push(edge);
  10980. }
  10981. {
  10982. // edge labels
  10983. var edgeLabel = new TextSprite$1();
  10984. edgeLabel.setBorderColor({
  10985. r: 0,
  10986. g: 0,
  10987. b: 0,
  10988. a: 1.0
  10989. });
  10990. edgeLabel.setBackgroundColor({
  10991. r: 0,
  10992. g: 0,
  10993. b: 0,
  10994. a: 1.0
  10995. });
  10996. edgeLabel.material.depthTest = false;
  10997. edgeLabel.visible = false;
  10998. edgeLabel.fontsize = 16;
  10999. this.edgeLabels.push(edgeLabel);
  11000. this.add(edgeLabel);
  11001. }
  11002. {
  11003. // angle labels
  11004. var angleLabel = new TextSprite$1();
  11005. angleLabel.setBorderColor({
  11006. r: 0,
  11007. g: 0,
  11008. b: 0,
  11009. a: 1.0
  11010. });
  11011. angleLabel.setBackgroundColor({
  11012. r: 0,
  11013. g: 0,
  11014. b: 0,
  11015. a: 1.0
  11016. });
  11017. angleLabel.fontsize = 16;
  11018. angleLabel.material.depthTest = false;
  11019. angleLabel.material.opacity = 1;
  11020. angleLabel.visible = false;
  11021. this.angleLabels.push(angleLabel);
  11022. this.add(angleLabel);
  11023. }
  11024. {
  11025. // coordinate labels
  11026. var coordinateLabel = new TextSprite$1();
  11027. coordinateLabel.setBorderColor({
  11028. r: 0,
  11029. g: 0,
  11030. b: 0,
  11031. a: 1.0
  11032. });
  11033. coordinateLabel.setBackgroundColor({
  11034. r: 0,
  11035. g: 0,
  11036. b: 0,
  11037. a: 1.0
  11038. });
  11039. coordinateLabel.fontsize = 16;
  11040. coordinateLabel.material.depthTest = false;
  11041. coordinateLabel.material.opacity = 1;
  11042. coordinateLabel.visible = false;
  11043. this.coordinateLabels.push(coordinateLabel);
  11044. this.add(coordinateLabel);
  11045. }
  11046. {
  11047. // Event Listeners
  11048. var drag = e => {
  11049. var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds, {
  11050. pickClipped: true
  11051. });
  11052. if (I) {
  11053. var i = this.spheres.indexOf(e.drag.object);
  11054. if (i !== -1) {
  11055. var _point = this.points[i];
  11056. // loop through current keys and cleanup ones that will be orphaned
  11057. for (var key of Object.keys(_point)) {
  11058. if (!I.point[key]) {
  11059. delete _point[key];
  11060. }
  11061. }
  11062. for (var _key of Object.keys(I.point).filter(e => e !== 'position')) {
  11063. _point[_key] = I.point[_key];
  11064. }
  11065. this.setPosition(i, I.location);
  11066. }
  11067. }
  11068. };
  11069. var drop = e => {
  11070. var i = this.spheres.indexOf(e.drag.object);
  11071. if (i !== -1) {
  11072. this.dispatchEvent({
  11073. 'type': 'marker_dropped',
  11074. 'measurement': this,
  11075. 'index': i
  11076. });
  11077. }
  11078. };
  11079. var mouseover = e => e.object.material.emissive.setHex(0x888888);
  11080. var mouseleave = e => e.object.material.emissive.setHex(0x000000);
  11081. sphere.addEventListener('drag', drag);
  11082. sphere.addEventListener('drop', drop);
  11083. sphere.addEventListener('mouseover', mouseover);
  11084. sphere.addEventListener('mouseleave', mouseleave);
  11085. }
  11086. var event = {
  11087. type: 'marker_added',
  11088. measurement: this,
  11089. sphere: sphere
  11090. };
  11091. this.dispatchEvent(event);
  11092. this.setMarker(this.points.length - 1, point);
  11093. }
  11094. removeMarker(index) {
  11095. this.points.splice(index, 1);
  11096. this.remove(this.spheres[index]);
  11097. var edgeIndex = index === 0 ? 0 : index - 1;
  11098. this.remove(this.edges[edgeIndex]);
  11099. this.edges.splice(edgeIndex, 1);
  11100. this.remove(this.edgeLabels[edgeIndex]);
  11101. this.edgeLabels.splice(edgeIndex, 1);
  11102. this.coordinateLabels.splice(index, 1);
  11103. this.remove(this.angleLabels[index]);
  11104. this.angleLabels.splice(index, 1);
  11105. this.spheres.splice(index, 1);
  11106. this.update();
  11107. this.dispatchEvent({
  11108. type: 'marker_removed',
  11109. measurement: this
  11110. });
  11111. }
  11112. setMarker(index, point) {
  11113. this.points[index] = point;
  11114. var event = {
  11115. type: 'marker_moved',
  11116. measure: this,
  11117. index: index,
  11118. position: point.position.clone()
  11119. };
  11120. this.dispatchEvent(event);
  11121. this.update();
  11122. }
  11123. setPosition(index, position) {
  11124. var point = this.points[index];
  11125. point.position.copy(position);
  11126. var event = {
  11127. type: 'marker_moved',
  11128. measure: this,
  11129. index: index,
  11130. position: position.clone()
  11131. };
  11132. this.dispatchEvent(event);
  11133. this.update();
  11134. }
  11135. getArea() {
  11136. var area = 0;
  11137. var j = this.points.length - 1;
  11138. for (var i = 0; i < this.points.length; i++) {
  11139. var p1 = this.points[i].position;
  11140. var p2 = this.points[j].position;
  11141. area += (p2.x + p1.x) * (p1.y - p2.y);
  11142. j = i;
  11143. }
  11144. return Math.abs(area / 2);
  11145. }
  11146. getTotalDistance() {
  11147. if (this.points.length === 0) {
  11148. return 0;
  11149. }
  11150. var distance = 0;
  11151. for (var i = 1; i < this.points.length; i++) {
  11152. var prev = this.points[i - 1].position;
  11153. var curr = this.points[i].position;
  11154. var d = prev.distanceTo(curr);
  11155. distance += d;
  11156. }
  11157. if (this.closed && this.points.length > 1) {
  11158. var first = this.points[0].position;
  11159. var last = this.points[this.points.length - 1].position;
  11160. var _d = last.distanceTo(first);
  11161. distance += _d;
  11162. }
  11163. return distance;
  11164. }
  11165. getAngleBetweenLines(cornerPoint, point1, point2) {
  11166. var v1 = new Vector3().subVectors(point1.position, cornerPoint.position);
  11167. var v2 = new Vector3().subVectors(point2.position, cornerPoint.position);
  11168. // avoid the error printed by threejs if denominator is 0
  11169. var denominator = Math.sqrt(v1.lengthSq() * v2.lengthSq());
  11170. if (denominator === 0) {
  11171. return 0;
  11172. } else {
  11173. return v1.angleTo(v2);
  11174. }
  11175. }
  11176. getAngle(index) {
  11177. if (this.points.length < 3 || index >= this.points.length) {
  11178. return 0;
  11179. }
  11180. var previous = index === 0 ? this.points[this.points.length - 1] : this.points[index - 1];
  11181. var point = this.points[index];
  11182. var next = this.points[(index + 1) % this.points.length];
  11183. return this.getAngleBetweenLines(point, previous, next);
  11184. }
  11185. // updateAzimuth(){
  11186. // // if(this.points.length !== 2){
  11187. // // return;
  11188. // // }
  11189. // // const azimuth = this.azimuth;
  11190. // // const [p0, p1] = this.points;
  11191. // // const r = p0.position.distanceTo(p1.position);
  11192. // }
  11193. update() {
  11194. if (this.points.length === 0) {
  11195. return;
  11196. } else if (this.points.length === 1) {
  11197. var point = this.points[0];
  11198. var position = point.position;
  11199. this.spheres[0].position.copy(position);
  11200. {
  11201. // coordinate labels
  11202. var coordinateLabel = this.coordinateLabels[0];
  11203. var msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  11204. coordinateLabel.setText(msg);
  11205. coordinateLabel.visible = this.showCoordinates;
  11206. }
  11207. return;
  11208. }
  11209. var lastIndex = this.points.length - 1;
  11210. var centroid = new Vector3();
  11211. for (var i = 0; i <= lastIndex; i++) {
  11212. var _point2 = this.points[i];
  11213. centroid.add(_point2.position);
  11214. }
  11215. centroid.divideScalar(this.points.length);
  11216. for (var _i = 0; _i <= lastIndex; _i++) {
  11217. var index = _i;
  11218. var nextIndex = _i + 1 > lastIndex ? 0 : _i + 1;
  11219. var previousIndex = _i === 0 ? lastIndex : _i - 1;
  11220. var _point3 = this.points[index];
  11221. var nextPoint = this.points[nextIndex];
  11222. var previousPoint = this.points[previousIndex];
  11223. var sphere = this.spheres[index];
  11224. // spheres
  11225. sphere.position.copy(_point3.position);
  11226. sphere.material.color = this.color;
  11227. {
  11228. // edges
  11229. var edge = this.edges[index];
  11230. edge.material.color = this.color;
  11231. edge.position.copy(_point3.position);
  11232. edge.geometry.setPositions([0, 0, 0, ...nextPoint.position.clone().sub(_point3.position).toArray()]);
  11233. edge.geometry.verticesNeedUpdate = true;
  11234. edge.geometry.computeBoundingSphere();
  11235. edge.computeLineDistances();
  11236. edge.visible = index < lastIndex || this.closed;
  11237. if (!this.showEdges) {
  11238. edge.visible = false;
  11239. }
  11240. }
  11241. {
  11242. // edge labels
  11243. var edgeLabel = this.edgeLabels[_i];
  11244. var center = new Vector3().add(_point3.position);
  11245. center.add(nextPoint.position);
  11246. center = center.multiplyScalar(0.5);
  11247. var distance = _point3.position.distanceTo(nextPoint.position);
  11248. edgeLabel.position.copy(center);
  11249. var suffix = "";
  11250. if (this.lengthUnit != null && this.lengthUnitDisplay != null) {
  11251. distance = distance / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit
  11252. suffix = this.lengthUnitDisplay.code;
  11253. }
  11254. var txtLength = Utils.addCommas(distance.toFixed(2));
  11255. edgeLabel.setText("".concat(txtLength, " ").concat(suffix));
  11256. edgeLabel.visible = this.showDistances && (index < lastIndex || this.closed) && this.points.length >= 2 && distance > 0;
  11257. }
  11258. {
  11259. // angle labels
  11260. var angleLabel = this.angleLabels[_i];
  11261. var angle = this.getAngleBetweenLines(_point3, previousPoint, nextPoint);
  11262. var dir = nextPoint.position.clone().sub(previousPoint.position);
  11263. dir.multiplyScalar(0.5);
  11264. dir = previousPoint.position.clone().add(dir).sub(_point3.position).normalize();
  11265. var dist = Math.min(_point3.position.distanceTo(previousPoint.position), _point3.position.distanceTo(nextPoint.position));
  11266. dist = dist / 9;
  11267. var labelPos = _point3.position.clone().add(dir.multiplyScalar(dist));
  11268. angleLabel.position.copy(labelPos);
  11269. var _msg = Utils.addCommas((angle * (180.0 / Math.PI)).toFixed(1)) + '\u00B0';
  11270. angleLabel.setText(_msg);
  11271. angleLabel.visible = this.showAngles && (index < lastIndex || this.closed) && this.points.length >= 3 && angle > 0;
  11272. }
  11273. }
  11274. {
  11275. // update height stuff
  11276. var heightEdge = this.heightEdge;
  11277. heightEdge.visible = this.showHeight;
  11278. this.heightLabel.visible = this.showHeight;
  11279. if (this.showHeight) {
  11280. var sorted = this.points.slice().sort((a, b) => a.position.z - b.position.z);
  11281. var lowPoint = sorted[0].position.clone();
  11282. var highPoint = sorted[sorted.length - 1].position.clone();
  11283. var min = lowPoint.z;
  11284. var max = highPoint.z;
  11285. var height = max - min;
  11286. var start = new Vector3(highPoint.x, highPoint.y, min);
  11287. var end = new Vector3(highPoint.x, highPoint.y, max);
  11288. heightEdge.position.copy(lowPoint);
  11289. heightEdge.geometry.setPositions([0, 0, 0, ...start.clone().sub(lowPoint).toArray(), ...start.clone().sub(lowPoint).toArray(), ...end.clone().sub(lowPoint).toArray()]);
  11290. heightEdge.geometry.verticesNeedUpdate = true;
  11291. // heightEdge.geometry.computeLineDistances();
  11292. // heightEdge.geometry.lineDistancesNeedUpdate = true;
  11293. heightEdge.geometry.computeBoundingSphere();
  11294. heightEdge.computeLineDistances();
  11295. // heightEdge.material.dashSize = height / 40;
  11296. // heightEdge.material.gapSize = height / 40;
  11297. var heightLabelPosition = start.clone().add(end).multiplyScalar(0.5);
  11298. this.heightLabel.position.copy(heightLabelPosition);
  11299. var _suffix = "";
  11300. if (this.lengthUnit != null && this.lengthUnitDisplay != null) {
  11301. height = height / this.lengthUnit.unitspermeter * this.lengthUnitDisplay.unitspermeter; //convert to meters then to the display unit
  11302. _suffix = this.lengthUnitDisplay.code;
  11303. }
  11304. var txtHeight = Utils.addCommas(height.toFixed(2));
  11305. var _msg2 = "".concat(txtHeight, " ").concat(_suffix);
  11306. this.heightLabel.setText(_msg2);
  11307. }
  11308. }
  11309. {
  11310. // update circle stuff
  11311. var circleRadiusLabel = this.circleRadiusLabel;
  11312. var circleRadiusLine = this.circleRadiusLine;
  11313. var circleLine = this.circleLine;
  11314. var circleCenter = this.circleCenter;
  11315. var circleOkay = this.points.length === 3;
  11316. circleRadiusLabel.visible = this.showCircle && circleOkay;
  11317. circleRadiusLine.visible = this.showCircle && circleOkay;
  11318. circleLine.visible = this.showCircle && circleOkay;
  11319. circleCenter.visible = this.showCircle && circleOkay;
  11320. if (this.showCircle && circleOkay) {
  11321. var A = this.points[0].position;
  11322. var B = this.points[1].position;
  11323. var C = this.points[2].position;
  11324. var AB = B.clone().sub(A);
  11325. var AC = C.clone().sub(A);
  11326. var N = AC.clone().cross(AB).normalize();
  11327. var _center = Potree.Utils.computeCircleCenter(A, B, C);
  11328. var radius = _center.distanceTo(A);
  11329. var scale = radius / 20;
  11330. circleCenter.position.copy(_center);
  11331. circleCenter.scale.set(scale, scale, scale);
  11332. //circleRadiusLine.geometry.vertices[0].set(0, 0, 0);
  11333. //circleRadiusLine.geometry.vertices[1].copy(B.clone().sub(center));
  11334. circleRadiusLine.geometry.setPositions([0, 0, 0, ...B.clone().sub(_center).toArray()]);
  11335. circleRadiusLine.geometry.verticesNeedUpdate = true;
  11336. circleRadiusLine.geometry.computeBoundingSphere();
  11337. circleRadiusLine.position.copy(_center);
  11338. circleRadiusLine.computeLineDistances();
  11339. var target = _center.clone().add(N);
  11340. circleLine.position.copy(_center);
  11341. circleLine.scale.set(radius, radius, radius);
  11342. circleLine.lookAt(target);
  11343. circleRadiusLabel.visible = true;
  11344. circleRadiusLabel.position.copy(_center.clone().add(B).multiplyScalar(0.5));
  11345. circleRadiusLabel.setText("".concat(radius.toFixed(3)));
  11346. }
  11347. }
  11348. {
  11349. // update area label
  11350. this.areaLabel.position.copy(centroid);
  11351. this.areaLabel.visible = this.showArea && this.points.length >= 3;
  11352. var area = this.getArea();
  11353. var _suffix2 = "";
  11354. if (this.lengthUnit != null && this.lengthUnitDisplay != null) {
  11355. area = area / Math.pow(this.lengthUnit.unitspermeter, 2) * Math.pow(this.lengthUnitDisplay.unitspermeter, 2); //convert to square meters then to the square display unit
  11356. _suffix2 = this.lengthUnitDisplay.code;
  11357. }
  11358. var txtArea = Utils.addCommas(area.toFixed(1));
  11359. var _msg3 = "".concat(txtArea, " ").concat(_suffix2, "\xB2");
  11360. this.areaLabel.setText(_msg3);
  11361. }
  11362. // this.updateAzimuth();
  11363. }
  11364. raycast(raycaster, intersects) {
  11365. for (var i = 0; i < this.points.length; i++) {
  11366. var sphere = this.spheres[i];
  11367. sphere.raycast(raycaster, intersects);
  11368. }
  11369. // recalculate distances because they are not necessarely correct
  11370. // for scaled objects.
  11371. // see https://github.com/mrdoob/three.js/issues/5827
  11372. // TODO: remove this once the bug has been fixed
  11373. for (var _i2 = 0; _i2 < intersects.length; _i2++) {
  11374. var I = intersects[_i2];
  11375. I.distance = raycaster.ray.origin.distanceTo(I.point);
  11376. }
  11377. intersects.sort(function (a, b) {
  11378. return a.distance - b.distance;
  11379. });
  11380. }
  11381. get showCoordinates() {
  11382. return this._showCoordinates;
  11383. }
  11384. set showCoordinates(value) {
  11385. this._showCoordinates = value;
  11386. this.update();
  11387. }
  11388. get showAngles() {
  11389. return this._showAngles;
  11390. }
  11391. set showAngles(value) {
  11392. this._showAngles = value;
  11393. this.update();
  11394. }
  11395. get showCircle() {
  11396. return this._showCircle;
  11397. }
  11398. set showCircle(value) {
  11399. this._showCircle = value;
  11400. this.update();
  11401. }
  11402. get showAzimuth() {
  11403. return this._showAzimuth;
  11404. }
  11405. set showAzimuth(value) {
  11406. this._showAzimuth = value;
  11407. this.update();
  11408. }
  11409. get showEdges() {
  11410. return this._showEdges;
  11411. }
  11412. set showEdges(value) {
  11413. this._showEdges = value;
  11414. this.update();
  11415. }
  11416. get showHeight() {
  11417. return this._showHeight;
  11418. }
  11419. set showHeight(value) {
  11420. this._showHeight = value;
  11421. this.update();
  11422. }
  11423. get showArea() {
  11424. return this._showArea;
  11425. }
  11426. set showArea(value) {
  11427. this._showArea = value;
  11428. this.update();
  11429. }
  11430. get closed() {
  11431. return this._closed;
  11432. }
  11433. set closed(value) {
  11434. this._closed = value;
  11435. this.update();
  11436. }
  11437. get showDistances() {
  11438. return this._showDistances;
  11439. }
  11440. set showDistances(value) {
  11441. this._showDistances = value;
  11442. this.update();
  11443. }
  11444. }
  11445. class PolygonClipVolume extends Object3D {
  11446. constructor(camera) {
  11447. super();
  11448. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  11449. this.name = "polygon_clip_volume_" + this.constructor.counter;
  11450. this.camera = camera.clone();
  11451. this.camera.rotation.set(...camera.rotation.toArray()); // [r85] workaround because camera.clone() doesn't work on rotation
  11452. this.camera.rotation.order = camera.rotation.order;
  11453. this.camera.updateMatrixWorld();
  11454. this.camera.updateProjectionMatrix();
  11455. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  11456. this.viewMatrix = this.camera.matrixWorldInverse.clone();
  11457. this.projMatrix = this.camera.projectionMatrix.clone();
  11458. // projected markers
  11459. this.markers = [];
  11460. this.initialized = false;
  11461. }
  11462. addMarker() {
  11463. var marker = new Mesh();
  11464. var cancel;
  11465. var drag = e => {
  11466. var size = e.viewer.renderer.getSize(new Vector2());
  11467. var projectedPos = new Vector3(2.0 * (e.drag.end.x / size.width) - 1.0, -2.0 * (e.drag.end.y / size.height) + 1.0, 0);
  11468. marker.position.copy(projectedPos);
  11469. };
  11470. var drop = e => {
  11471. cancel();
  11472. };
  11473. cancel = e => {
  11474. marker.removeEventListener("drag", drag);
  11475. marker.removeEventListener("drop", drop);
  11476. };
  11477. marker.addEventListener("drag", drag);
  11478. marker.addEventListener("drop", drop);
  11479. this.markers.push(marker);
  11480. }
  11481. removeLastMarker() {
  11482. if (this.markers.length > 0) {
  11483. this.markers.splice(this.markers.length - 1, 1);
  11484. }
  11485. }
  11486. }
  11487. ;
  11488. class Utils {
  11489. static loadShapefileFeatures(file, callback) {
  11490. return _asyncToGenerator(function* () {
  11491. var features = [];
  11492. var handleFinish = () => {
  11493. callback(features);
  11494. };
  11495. var source = yield shapefile.open(file);
  11496. while (true) {
  11497. var result = yield source.read();
  11498. if (result.done) {
  11499. handleFinish();
  11500. break;
  11501. }
  11502. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  11503. features.push(result.value);
  11504. }
  11505. }
  11506. })();
  11507. }
  11508. static toString(value) {
  11509. if (value.x != null) {
  11510. return value.x.toFixed(2) + ', ' + value.y.toFixed(2) + ', ' + value.z.toFixed(2);
  11511. } else {
  11512. return '' + value + '';
  11513. }
  11514. }
  11515. static normalizeURL(url) {
  11516. var u = new URL(url);
  11517. return u.protocol + '//' + u.hostname + u.pathname.replace(/\/+/g, '/');
  11518. }
  11519. static pathExists(url) {
  11520. var req = XHRFactory.createXMLHttpRequest();
  11521. req.open('GET', url, false);
  11522. req.send(null);
  11523. if (req.status !== 200) {
  11524. return false;
  11525. }
  11526. return true;
  11527. }
  11528. static debugSphere(parent, position, scale, color) {
  11529. var geometry = new SphereGeometry(1, 8, 8);
  11530. var material;
  11531. if (color !== undefined) {
  11532. material = new MeshBasicMaterial({
  11533. color: color
  11534. });
  11535. } else {
  11536. material = new MeshNormalMaterial();
  11537. }
  11538. var sphere = new Mesh(geometry, material);
  11539. sphere.position.copy(position);
  11540. sphere.scale.set(scale, scale, scale);
  11541. parent.add(sphere);
  11542. return sphere;
  11543. }
  11544. static debugLine(parent, start, end, color) {
  11545. var material = new LineBasicMaterial({
  11546. color: color
  11547. });
  11548. var geometry = new Geometry();
  11549. var p1 = new Vector3(0, 0, 0);
  11550. var p2 = end.clone().sub(start);
  11551. geometry.vertices.push(p1, p2);
  11552. var tl = new Line(geometry, material);
  11553. tl.position.copy(start);
  11554. parent.add(tl);
  11555. var line = {
  11556. node: tl,
  11557. set: (start, end) => {
  11558. geometry.vertices[0].copy(start);
  11559. geometry.vertices[1].copy(end);
  11560. geometry.verticesNeedUpdate = true;
  11561. }
  11562. };
  11563. return line;
  11564. }
  11565. static debugCircle(parent, center, radius, normal, color) {
  11566. var material = new LineBasicMaterial({
  11567. color: color
  11568. });
  11569. var geometry = new Geometry();
  11570. var n = 32;
  11571. for (var i = 0; i <= n; i++) {
  11572. var u0 = 2 * Math.PI * (i / n);
  11573. var u1 = 2 * Math.PI * (i + 1) / n;
  11574. var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0);
  11575. var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0);
  11576. geometry.vertices.push(p0, p1);
  11577. }
  11578. var tl = new Line(geometry, material);
  11579. tl.position.copy(center);
  11580. tl.scale.set(radius, radius, radius);
  11581. parent.add(tl);
  11582. }
  11583. static debugBox(parent, box) {
  11584. var transform = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new Matrix4();
  11585. var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0xFFFF00;
  11586. var vertices = [[box.min.x, box.min.y, box.min.z], [box.min.x, box.min.y, box.max.z], [box.min.x, box.max.y, box.min.z], [box.min.x, box.max.y, box.max.z], [box.max.x, box.min.y, box.min.z], [box.max.x, box.min.y, box.max.z], [box.max.x, box.max.y, box.min.z], [box.max.x, box.max.y, box.max.z]].map(v => new Vector3(...v));
  11587. var edges = [[0, 4], [4, 5], [5, 1], [1, 0], [2, 6], [6, 7], [7, 3], [3, 2], [0, 2], [4, 6], [5, 7], [1, 3]];
  11588. var center = box.getCenter(new Vector3());
  11589. var centroids = [{
  11590. position: [box.min.x, center.y, center.z],
  11591. color: 0xFF0000
  11592. }, {
  11593. position: [box.max.x, center.y, center.z],
  11594. color: 0x880000
  11595. }, {
  11596. position: [center.x, box.min.y, center.z],
  11597. color: 0x00FF00
  11598. }, {
  11599. position: [center.x, box.max.y, center.z],
  11600. color: 0x008800
  11601. }, {
  11602. position: [center.x, center.y, box.min.z],
  11603. color: 0x0000FF
  11604. }, {
  11605. position: [center.x, center.y, box.max.z],
  11606. color: 0x000088
  11607. }];
  11608. for (var vertex of vertices) {
  11609. var pos = vertex.clone().applyMatrix4(transform);
  11610. Utils.debugSphere(parent, pos, 0.1, 0xFF0000);
  11611. }
  11612. for (var edge of edges) {
  11613. var start = vertices[edge[0]].clone().applyMatrix4(transform);
  11614. var end = vertices[edge[1]].clone().applyMatrix4(transform);
  11615. Utils.debugLine(parent, start, end, color);
  11616. }
  11617. for (var centroid of centroids) {
  11618. var _pos = new Vector3(...centroid.position).applyMatrix4(transform);
  11619. Utils.debugSphere(parent, _pos, 0.1, centroid.color);
  11620. }
  11621. }
  11622. static debugPlane(parent, plane) {
  11623. var size = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  11624. var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0x0000FF;
  11625. var planehelper = new PlaneHelper(plane, size, color);
  11626. parent.add(planehelper);
  11627. }
  11628. /**
  11629. * adapted from mhluska at https://github.com/mrdoob/three.js/issues/1561
  11630. */
  11631. static computeTransformedBoundingBox(box, transform) {
  11632. var vertices = [new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.max.x, box.min.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.max.y, box.min.z).applyMatrix4(transform), new Vector3(box.min.x, box.min.y, box.max.z).applyMatrix4(transform), new Vector3(box.min.x, box.max.y, box.max.z).applyMatrix4(transform), new Vector3(box.max.x, box.max.y, box.min.z).applyMatrix4(transform), new Vector3(box.max.x, box.min.y, box.max.z).applyMatrix4(transform), new Vector3(box.max.x, box.max.y, box.max.z).applyMatrix4(transform)];
  11633. var boundingBox = new Box3();
  11634. boundingBox.setFromPoints(vertices);
  11635. return boundingBox;
  11636. }
  11637. //感觉就是bound.applyMatrix4(transform)
  11638. /**
  11639. * add separators to large numbers
  11640. *
  11641. * @param nStr
  11642. * @returns
  11643. */
  11644. static addCommas(nStr) {
  11645. nStr += '';
  11646. var x = nStr.split('.');
  11647. var x1 = x[0];
  11648. var x2 = x.length > 1 ? '.' + x[1] : '';
  11649. var rgx = /(\d+)(\d{3})/;
  11650. while (rgx.test(x1)) {
  11651. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  11652. }
  11653. return x1 + x2;
  11654. }
  11655. static removeCommas(str) {
  11656. return str.replace(/,/g, '');
  11657. }
  11658. /**
  11659. * create worker from a string
  11660. *
  11661. * code from http://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string
  11662. */
  11663. static createWorker(code) {
  11664. var blob = new Blob([code], {
  11665. type: 'application/javascript'
  11666. });
  11667. var worker = new Worker(URL.createObjectURL(blob));
  11668. return worker;
  11669. }
  11670. static moveTo(scene, endPosition, endTarget) {
  11671. var view = scene.view;
  11672. var camera = scene.getActiveCamera();
  11673. var animationDuration = 500;
  11674. var easing = TWEEN.Easing.Quartic.Out;
  11675. {
  11676. // animate camera position
  11677. var tween = new TWEEN.Tween(view.position).to(endPosition, animationDuration);
  11678. tween.easing(easing);
  11679. tween.start();
  11680. }
  11681. {
  11682. // animate camera target
  11683. var camTargetDistance = camera.position.distanceTo(endTarget);
  11684. var target = new Vector3().addVectors(camera.position, camera.getWorldDirection(new Vector3()).clone().multiplyScalar(camTargetDistance));
  11685. var _tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  11686. _tween.easing(easing);
  11687. _tween.onUpdate(() => {
  11688. view.lookAt(target);
  11689. });
  11690. _tween.onComplete(() => {
  11691. view.lookAt(target);
  11692. });
  11693. _tween.start();
  11694. }
  11695. }
  11696. static loadSkybox(path) {
  11697. var parent = new Object3D("skybox_root");
  11698. var camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  11699. camera.up.set(0, 0, 1);
  11700. var scene = new Scene();
  11701. var format = '.jpg';
  11702. var urls = [path + 'px' + format, path + 'nx' + format, path + 'py' + format, path + 'ny' + format, path + 'pz' + format, path + 'nz' + format];
  11703. var materialArray = [];
  11704. {
  11705. var _loop = function _loop() {
  11706. var material = new MeshBasicMaterial({
  11707. map: null,
  11708. side: BackSide,
  11709. depthTest: false,
  11710. depthWrite: false,
  11711. color: 0x424556
  11712. });
  11713. materialArray.push(material);
  11714. var loader = new TextureLoader();
  11715. loader.load(urls[i], function loaded(texture) {
  11716. material.map = texture;
  11717. material.needsUpdate = true;
  11718. material.color.setHex(0xffffff);
  11719. }, function progress(xhr) {
  11720. // console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
  11721. }, function error(xhr) {
  11722. console.log('An error happened', xhr);
  11723. });
  11724. };
  11725. for (var i = 0; i < 6; i++) {
  11726. _loop();
  11727. }
  11728. }
  11729. var skyGeometry = new BoxGeometry(700, 700, 700);
  11730. var skybox = new Mesh(skyGeometry, materialArray);
  11731. scene.add(skybox);
  11732. scene.traverse(n => n.frustumCulled = false);
  11733. // z up
  11734. scene.rotation.x = Math.PI / 2;
  11735. parent.children.push(camera);
  11736. camera.parent = parent;
  11737. return {
  11738. camera,
  11739. scene,
  11740. parent
  11741. };
  11742. }
  11743. static createGrid(width, length, spacing, color) {
  11744. var material = new LineBasicMaterial({
  11745. color: color || 0x888888
  11746. });
  11747. var geometry = new Geometry();
  11748. for (var i = 0; i <= length; i++) {
  11749. geometry.vertices.push(new Vector3(-(spacing * width) / 2, i * spacing - spacing * length / 2, 0));
  11750. geometry.vertices.push(new Vector3(+(spacing * width) / 2, i * spacing - spacing * length / 2, 0));
  11751. }
  11752. for (var _i = 0; _i <= width; _i++) {
  11753. geometry.vertices.push(new Vector3(_i * spacing - spacing * width / 2, -(spacing * length) / 2, 0));
  11754. geometry.vertices.push(new Vector3(_i * spacing - spacing * width / 2, +(spacing * length) / 2, 0));
  11755. }
  11756. var line = new LineSegments(geometry, material, LinePieces);
  11757. line.receiveShadow = true;
  11758. return line;
  11759. }
  11760. static createBackgroundTexture(width, height) {
  11761. function gauss(x, y) {
  11762. return 1 / (2 * Math.PI) * Math.exp(-(x * x + y * y) / 2);
  11763. }
  11764. ;
  11765. // map.magFilter = THREE.NearestFilter;
  11766. var size = width * height;
  11767. var data = new Uint8Array(3 * size);
  11768. var chroma = [1, 1.5, 1.7];
  11769. var max = gauss(0, 0);
  11770. for (var x = 0; x < width; x++) {
  11771. for (var y = 0; y < height; y++) {
  11772. var u = 2 * (x / width) - 1;
  11773. var v = 2 * (y / height) - 1;
  11774. var i = x + width * y;
  11775. var d = gauss(2 * u, 2 * v) / max;
  11776. var r = (Math.random() + Math.random() + Math.random()) / 3;
  11777. r = (d * 0.5 + 0.5) * r * 0.03;
  11778. r = r * 0.4;
  11779. // d = Math.pow(d, 0.6);
  11780. data[3 * i + 0] = 255 * (d / 15 + 0.05 + r) * chroma[0];
  11781. data[3 * i + 1] = 255 * (d / 15 + 0.05 + r) * chroma[1];
  11782. data[3 * i + 2] = 255 * (d / 15 + 0.05 + r) * chroma[2];
  11783. }
  11784. }
  11785. var texture = new DataTexture(data, width, height, RGBFormat);
  11786. texture.needsUpdate = true;
  11787. return texture;
  11788. }
  11789. static getMousePointCloudIntersection(mouse, camera, viewer, pointclouds) {
  11790. var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  11791. var renderer = viewer.renderer;
  11792. var nmouse = {
  11793. x: mouse.x / renderer.domElement.clientWidth * 2 - 1,
  11794. y: -(mouse.y / renderer.domElement.clientHeight) * 2 + 1
  11795. };
  11796. var pickParams = {};
  11797. if (params.pickClipped) {
  11798. pickParams.pickClipped = params.pickClipped;
  11799. }
  11800. pickParams.x = mouse.x;
  11801. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  11802. var raycaster = new Raycaster();
  11803. raycaster.setFromCamera(nmouse, camera);
  11804. var ray = raycaster.ray;
  11805. var selectedPointcloud = null;
  11806. var closestDistance = Infinity;
  11807. var closestIntersection = null;
  11808. var closestPoint = null;
  11809. for (var pointcloud of pointclouds) {
  11810. var point = pointcloud.pick(viewer, camera, ray, pickParams);
  11811. if (!point) {
  11812. continue;
  11813. }
  11814. var distance = camera.position.distanceTo(point.position);
  11815. if (distance < closestDistance) {
  11816. closestDistance = distance;
  11817. selectedPointcloud = pointcloud;
  11818. closestIntersection = point.position;
  11819. closestPoint = point;
  11820. }
  11821. }
  11822. if (selectedPointcloud) {
  11823. return {
  11824. location: closestIntersection,
  11825. distance: closestDistance,
  11826. pointcloud: selectedPointcloud,
  11827. point: closestPoint
  11828. };
  11829. } else {
  11830. return null;
  11831. }
  11832. }
  11833. static pixelsArrayToImage(pixels, width, height) {
  11834. var canvas = document.createElement('canvas');
  11835. canvas.width = width;
  11836. canvas.height = height;
  11837. var context = canvas.getContext('2d');
  11838. pixels = new pixels.constructor(pixels);
  11839. for (var i = 0; i < pixels.length; i++) {
  11840. pixels[i * 4 + 3] = 255;
  11841. }
  11842. var imageData = context.createImageData(width, height);
  11843. imageData.data.set(pixels);
  11844. context.putImageData(imageData, 0, 0);
  11845. var img = new Image();
  11846. img.src = canvas.toDataURL();
  11847. // img.style.transform = "scaleY(-1)";
  11848. return img;
  11849. }
  11850. static pixelsArrayToDataUrl(pixels, width, height) {
  11851. var canvas = document.createElement('canvas');
  11852. canvas.width = width;
  11853. canvas.height = height;
  11854. var context = canvas.getContext('2d');
  11855. pixels = new pixels.constructor(pixels);
  11856. for (var i = 0; i < pixels.length; i++) {
  11857. pixels[i * 4 + 3] = 255;
  11858. }
  11859. var imageData = context.createImageData(width, height);
  11860. imageData.data.set(pixels);
  11861. context.putImageData(imageData, 0, 0);
  11862. var dataURL = canvas.toDataURL();
  11863. return dataURL;
  11864. }
  11865. static pixelsArrayToCanvas(pixels, width, height) {
  11866. var canvas = document.createElement('canvas');
  11867. canvas.width = width;
  11868. canvas.height = height;
  11869. var context = canvas.getContext('2d');
  11870. pixels = new pixels.constructor(pixels);
  11871. //for (let i = 0; i < pixels.length; i++) {
  11872. // pixels[i * 4 + 3] = 255;
  11873. //}
  11874. // flip vertically
  11875. var bytesPerLine = width * 4;
  11876. for (var i = 0; i < parseInt(height / 2); i++) {
  11877. var j = height - i - 1;
  11878. var lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  11879. var lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  11880. pixels.set(lineJ, i * bytesPerLine);
  11881. pixels.set(lineI, j * bytesPerLine);
  11882. }
  11883. var imageData = context.createImageData(width, height);
  11884. imageData.data.set(pixels);
  11885. context.putImageData(imageData, 0, 0);
  11886. return canvas;
  11887. }
  11888. static removeListeners(dispatcher, type) {
  11889. if (dispatcher._listeners === undefined) {
  11890. return;
  11891. }
  11892. if (dispatcher._listeners[type]) {
  11893. delete dispatcher._listeners[type];
  11894. }
  11895. }
  11896. static mouseToRay(mouse, camera, width, height) {
  11897. var normalizedMouse = {
  11898. x: mouse.x / width * 2 - 1,
  11899. y: -(mouse.y / height) * 2 + 1
  11900. };
  11901. var vector = new Vector3(normalizedMouse.x, normalizedMouse.y, 0.5);
  11902. var origin = camera.position.clone();
  11903. vector.unproject(camera);
  11904. var direction = new Vector3().subVectors(vector, origin).normalize();
  11905. var ray = new Ray(origin, direction);
  11906. return ray;
  11907. }
  11908. static projectedRadius(radius, camera, distance, screenWidth, screenHeight) {
  11909. if (camera instanceof OrthographicCamera) {
  11910. return Utils.projectedRadiusOrtho(radius, camera.projectionMatrix, screenWidth, screenHeight);
  11911. } else if (camera instanceof PerspectiveCamera) {
  11912. return Utils.projectedRadiusPerspective(radius, camera.fov * Math.PI / 180, distance, screenHeight);
  11913. } else {
  11914. throw new Error("invalid parameters");
  11915. }
  11916. }
  11917. static projectedRadiusPerspective(radius, fov, distance, screenHeight) {
  11918. var projFactor = 1 / Math.tan(fov / 2) / distance;
  11919. projFactor = projFactor * screenHeight / 2;
  11920. return radius * projFactor;
  11921. }
  11922. static projectedRadiusOrtho(radius, proj, screenWidth, screenHeight) {
  11923. var p1 = new Vector4(0);
  11924. var p2 = new Vector4(radius);
  11925. p1.applyMatrix4(proj);
  11926. p2.applyMatrix4(proj);
  11927. p1 = new Vector3(p1.x, p1.y, p1.z);
  11928. p2 = new Vector3(p2.x, p2.y, p2.z);
  11929. p1.x = (p1.x + 1.0) * 0.5 * screenWidth;
  11930. p1.y = (p1.y + 1.0) * 0.5 * screenHeight;
  11931. p2.x = (p2.x + 1.0) * 0.5 * screenWidth;
  11932. p2.y = (p2.y + 1.0) * 0.5 * screenHeight;
  11933. return p1.distanceTo(p2);
  11934. }
  11935. static topView(camera, node) {
  11936. camera.position.set(0, 1, 0);
  11937. camera.rotation.set(-Math.PI / 2, 0, 0);
  11938. camera.zoomTo(node, 1);
  11939. }
  11940. static frontView(camera, node) {
  11941. camera.position.set(0, 0, 1);
  11942. camera.rotation.set(0, 0, 0);
  11943. camera.zoomTo(node, 1);
  11944. }
  11945. static leftView(camera, node) {
  11946. camera.position.set(-1, 0, 0);
  11947. camera.rotation.set(0, -Math.PI / 2, 0);
  11948. camera.zoomTo(node, 1);
  11949. }
  11950. static rightView(camera, node) {
  11951. camera.position.set(1, 0, 0);
  11952. camera.rotation.set(0, Math.PI / 2, 0);
  11953. camera.zoomTo(node, 1);
  11954. }
  11955. static findClosestGpsTime(target, viewer) {
  11956. var start = performance.now();
  11957. var nodes = [];
  11958. for (var pc of viewer.scene.pointclouds) {
  11959. nodes.push(pc.root);
  11960. for (var child of pc.root.children) {
  11961. if (child) {
  11962. nodes.push(child);
  11963. }
  11964. }
  11965. }
  11966. var closestNode = null;
  11967. var closestIndex = Infinity;
  11968. var closestDistance = Infinity;
  11969. var closestValue = 0;
  11970. for (var node of nodes) {
  11971. var isOkay = node.geometryNode != null && node.geometryNode.geometry != null && node.sceneNode != null;
  11972. if (!isOkay) {
  11973. continue;
  11974. }
  11975. var _geometry = node.geometryNode.geometry;
  11976. var gpsTime = _geometry.attributes["gps-time"];
  11977. var range = gpsTime.potree.range;
  11978. for (var i = 0; i < gpsTime.array.length; i++) {
  11979. var value = gpsTime.array[i];
  11980. value = value * (range[1] - range[0]) + range[0];
  11981. var distance = Math.abs(target - value);
  11982. if (distance < closestDistance) {
  11983. closestIndex = i;
  11984. closestDistance = distance;
  11985. closestValue = value;
  11986. closestNode = node;
  11987. //console.log("found a closer one: " + value);
  11988. }
  11989. }
  11990. }
  11991. var geometry = closestNode.geometryNode.geometry;
  11992. var position = new Vector3(geometry.attributes.position.array[3 * closestIndex + 0], geometry.attributes.position.array[3 * closestIndex + 1], geometry.attributes.position.array[3 * closestIndex + 2]);
  11993. position.applyMatrix4(closestNode.sceneNode.matrixWorld);
  11994. var end = performance.now();
  11995. var duration = end - start;
  11996. console.log("duration: ".concat(duration.toFixed(3), "ms"));
  11997. return {
  11998. node: closestNode,
  11999. index: closestIndex,
  12000. position: position
  12001. };
  12002. }
  12003. /**
  12004. *
  12005. * 0: no intersection
  12006. * 1: intersection
  12007. * 2: fully inside
  12008. */
  12009. static frustumSphereIntersection(frustum, sphere) {
  12010. var planes = frustum.planes;
  12011. var center = sphere.center;
  12012. var negRadius = -sphere.radius;
  12013. var minDistance = Number.MAX_VALUE;
  12014. for (var i = 0; i < 6; i++) {
  12015. var distance = planes[i].distanceToPoint(center);
  12016. if (distance < negRadius) {
  12017. return 0;
  12018. }
  12019. minDistance = Math.min(minDistance, distance);
  12020. }
  12021. return minDistance >= sphere.radius ? 2 : 1;
  12022. }
  12023. // code taken from three.js
  12024. // ImageUtils - generateDataTexture()
  12025. static generateDataTexture(width, height, color) {
  12026. var size = width * height;
  12027. var data = new Uint8Array(4 * width * height);
  12028. var r = Math.floor(color.r * 255);
  12029. var g = Math.floor(color.g * 255);
  12030. var b = Math.floor(color.b * 255);
  12031. for (var i = 0; i < size; i++) {
  12032. data[i * 3] = r;
  12033. data[i * 3 + 1] = g;
  12034. data[i * 3 + 2] = b;
  12035. }
  12036. var texture = new DataTexture(data, width, height, RGBAFormat);
  12037. texture.needsUpdate = true;
  12038. texture.magFilter = NearestFilter;
  12039. return texture;
  12040. }
  12041. // from http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
  12042. static getParameterByName(name) {
  12043. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  12044. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  12045. var results = regex.exec(document.location.search);
  12046. return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, ' '));
  12047. }
  12048. static setParameter(name, value) {
  12049. // value = encodeURIComponent(value);
  12050. name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]');
  12051. var regex = new RegExp('([\\?&])(' + name + '=([^&#]*))');
  12052. var results = regex.exec(document.location.search);
  12053. var url = window.location.href;
  12054. if (results === null) {
  12055. if (window.location.search.length === 0) {
  12056. url = url + '?';
  12057. } else {
  12058. url = url + '&';
  12059. }
  12060. url = url + name + '=' + value;
  12061. } else {
  12062. var newValue = name + '=' + value;
  12063. url = url.replace(results[2], newValue);
  12064. }
  12065. window.history.replaceState({}, '', url);
  12066. }
  12067. static createChildAABB(aabb, index) {
  12068. var min = aabb.min.clone();
  12069. var max = aabb.max.clone();
  12070. var size = new Vector3().subVectors(max, min);
  12071. if ((index & 0b0001) > 0) {
  12072. min.z += size.z / 2;
  12073. } else {
  12074. max.z -= size.z / 2;
  12075. }
  12076. if ((index & 0b0010) > 0) {
  12077. min.y += size.y / 2;
  12078. } else {
  12079. max.y -= size.y / 2;
  12080. }
  12081. if ((index & 0b0100) > 0) {
  12082. min.x += size.x / 2;
  12083. } else {
  12084. max.x -= size.x / 2;
  12085. }
  12086. return new Box3(min, max);
  12087. }
  12088. // see https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
  12089. static clipboardCopy(text) {
  12090. var textArea = document.createElement("textarea");
  12091. textArea.style.position = 'fixed';
  12092. textArea.style.top = 0;
  12093. textArea.style.left = 0;
  12094. textArea.style.width = '2em';
  12095. textArea.style.height = '2em';
  12096. textArea.style.padding = 0;
  12097. textArea.style.border = 'none';
  12098. textArea.style.outline = 'none';
  12099. textArea.style.boxShadow = 'none';
  12100. textArea.style.background = 'transparent';
  12101. textArea.value = text;
  12102. document.body.appendChild(textArea);
  12103. textArea.select();
  12104. try {
  12105. var success = document.execCommand('copy');
  12106. if (success) {
  12107. console.log("copied text to clipboard");
  12108. } else {
  12109. console.log("copy to clipboard failed");
  12110. }
  12111. } catch (err) {
  12112. console.log("error while trying to copy to clipboard");
  12113. }
  12114. document.body.removeChild(textArea);
  12115. }
  12116. static getMeasurementIcon(measurement) {
  12117. if (measurement instanceof Measure) {
  12118. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  12119. return "".concat(Potree.resourcePath, "/icons/distance.svg");
  12120. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  12121. return "".concat(Potree.resourcePath, "/icons/area.svg");
  12122. } else if (measurement.maxMarkers === 1) {
  12123. return "".concat(Potree.resourcePath, "/icons/point.svg");
  12124. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  12125. return "".concat(Potree.resourcePath, "/icons/angle.png");
  12126. } else if (measurement.showHeight) {
  12127. return "".concat(Potree.resourcePath, "/icons/height.svg");
  12128. } else {
  12129. return "".concat(Potree.resourcePath, "/icons/distance.svg");
  12130. }
  12131. } else if (measurement instanceof Profile) {
  12132. return "".concat(Potree.resourcePath, "/icons/profile.svg");
  12133. } else if (measurement instanceof Volume) {
  12134. return "".concat(Potree.resourcePath, "/icons/volume.svg");
  12135. } else if (measurement instanceof PolygonClipVolume) {
  12136. return "".concat(Potree.resourcePath, "/icons/clip-polygon.svg");
  12137. }
  12138. }
  12139. static lineToLineIntersection(P0, P1, P2, P3) {
  12140. var P = [P0, P1, P2, P3];
  12141. var d = (m, n, o, p) => {
  12142. var result = (P[m].x - P[n].x) * (P[o].x - P[p].x) + (P[m].y - P[n].y) * (P[o].y - P[p].y) + (P[m].z - P[n].z) * (P[o].z - P[p].z);
  12143. return result;
  12144. };
  12145. var mua = (d(0, 2, 3, 2) * d(3, 2, 1, 0) - d(0, 2, 1, 0) * d(3, 2, 3, 2)
  12146. /**-----------------------------------------------------------------**/) / (d(1, 0, 1, 0) * d(3, 2, 3, 2) - d(3, 2, 1, 0) * d(3, 2, 1, 0));
  12147. var mub = (d(0, 2, 3, 2) + mua * d(3, 2, 1, 0)
  12148. /**--------------------------------------**/) / d(3, 2, 3, 2);
  12149. var P01 = P1.clone().sub(P0);
  12150. var P23 = P3.clone().sub(P2);
  12151. var Pa = P0.clone().add(P01.multiplyScalar(mua));
  12152. var Pb = P2.clone().add(P23.multiplyScalar(mub));
  12153. var center = Pa.clone().add(Pb).multiplyScalar(0.5);
  12154. return center;
  12155. }
  12156. static computeCircleCenter(A, B, C) {
  12157. var AB = B.clone().sub(A);
  12158. var AC = C.clone().sub(A);
  12159. var N = AC.clone().cross(AB).normalize();
  12160. var ab_dir = AB.clone().cross(N).normalize();
  12161. var ac_dir = AC.clone().cross(N).normalize();
  12162. var ab_origin = A.clone().add(B).multiplyScalar(0.5);
  12163. var ac_origin = A.clone().add(C).multiplyScalar(0.5);
  12164. var P0 = ab_origin;
  12165. var P1 = ab_origin.clone().add(ab_dir);
  12166. var P2 = ac_origin;
  12167. var P3 = ac_origin.clone().add(ac_dir);
  12168. var center = Utils.lineToLineIntersection(P0, P1, P2, P3);
  12169. return center;
  12170. // Potree.Utils.debugLine(viewer.scene.scene, P0, P1, 0x00ff00);
  12171. // Potree.Utils.debugLine(viewer.scene.scene, P2, P3, 0x0000ff);
  12172. // Potree.Utils.debugSphere(viewer.scene.scene, center, 0.03, 0xff00ff);
  12173. // const radius = center.distanceTo(A);
  12174. // Potree.Utils.debugCircle(viewer.scene.scene, center, radius, new THREE.Vector3(0, 0, 1), 0xff00ff);
  12175. }
  12176. static getNorthVec(p1, distance, projection) {
  12177. if (projection) {
  12178. // if there is a projection, transform coordinates to WGS84
  12179. // and compute angle to north there
  12180. proj4.defs("pointcloud", projection);
  12181. var transform = proj4("pointcloud", "WGS84");
  12182. var llP1 = transform.forward(p1.toArray());
  12183. var llP2 = transform.forward([p1.x, p1.y + distance]);
  12184. var polarRadius = Math.sqrt((llP2[0] - llP1[0]) ** 2 + (llP2[1] - llP1[1]) ** 2);
  12185. llP2 = [llP1[0], llP1[1] + polarRadius];
  12186. var northVec = transform.inverse(llP2);
  12187. return new Vector3(...northVec, p1.z).sub(p1);
  12188. } else {
  12189. // if there is no projection, assume [0, 1, 0] as north direction
  12190. var vec = new Vector3(0, 1, 0).multiplyScalar(distance);
  12191. return vec;
  12192. }
  12193. }
  12194. static computeAzimuth(p1, p2, projection) {
  12195. var azimuth = 0;
  12196. if (projection) {
  12197. // if there is a projection, transform coordinates to WGS84
  12198. // and compute angle to north there
  12199. var transform;
  12200. if (projection.includes('EPSG')) {
  12201. transform = proj4(projection, "WGS84");
  12202. } else {
  12203. proj4.defs("pointcloud", projection);
  12204. transform = proj4("pointcloud", "WGS84");
  12205. }
  12206. var llP1 = transform.forward(p1.toArray());
  12207. var llP2 = transform.forward(p2.toArray());
  12208. var dir = [llP2[0] - llP1[0], llP2[1] - llP1[1]];
  12209. azimuth = Math.atan2(dir[1], dir[0]) - Math.PI / 2;
  12210. } else {
  12211. // if there is no projection, assume [0, 1, 0] as north direction
  12212. var _dir = [p2.x - p1.x, p2.y - p1.y];
  12213. azimuth = Math.atan2(_dir[1], _dir[0]) - Math.PI / 2;
  12214. }
  12215. // make clockwise
  12216. azimuth = -azimuth;
  12217. return azimuth;
  12218. }
  12219. static loadScript(url) {
  12220. return _asyncToGenerator(function* () {
  12221. return new Promise(resolve => {
  12222. var element = document.getElementById(url);
  12223. if (element) {
  12224. resolve();
  12225. } else {
  12226. var script = document.createElement("script");
  12227. script.id = url;
  12228. script.onload = () => {
  12229. resolve();
  12230. };
  12231. script.src = url;
  12232. document.body.appendChild(script);
  12233. }
  12234. });
  12235. })();
  12236. }
  12237. static createSvgGradient(scheme) {
  12238. // this is what we are creating:
  12239. //
  12240. //<svg width="1em" height="3em" xmlns="http://www.w3.org/2000/svg">
  12241. // <defs>
  12242. // <linearGradient id="gradientID" gradientTransform="rotate(90)">
  12243. // <stop offset="0%" stop-color="rgb(93, 78, 162)" />
  12244. // ...
  12245. // <stop offset="100%" stop-color="rgb(157, 0, 65)" />
  12246. // </linearGradient>
  12247. // </defs>
  12248. //
  12249. // <rect width="100%" height="100%" fill="url('#myGradient')" stroke="black" stroke-width="0.1em"/>
  12250. //</svg>
  12251. var gradientId = "".concat(Math.random(), "_").concat(Date.now());
  12252. var svgn = "http://www.w3.org/2000/svg";
  12253. var svg = document.createElementNS(svgn, "svg");
  12254. svg.setAttributeNS(null, "width", "2em");
  12255. svg.setAttributeNS(null, "height", "3em");
  12256. {
  12257. // <defs>
  12258. var defs = document.createElementNS(svgn, "defs");
  12259. var linearGradient = document.createElementNS(svgn, "linearGradient");
  12260. linearGradient.setAttributeNS(null, "id", gradientId);
  12261. linearGradient.setAttributeNS(null, "gradientTransform", "rotate(90)");
  12262. for (var i = scheme.length - 1; i >= 0; i--) {
  12263. var stopVal = scheme[i];
  12264. var percent = parseInt(100 - stopVal[0] * 100);
  12265. var [r, g, b] = stopVal[1].toArray().map(v => parseInt(v * 255));
  12266. var stop = document.createElementNS(svgn, "stop");
  12267. stop.setAttributeNS(null, "offset", "".concat(percent, "%"));
  12268. stop.setAttributeNS(null, "stop-color", "rgb(".concat(r, ", ").concat(g, ", ").concat(b, ")"));
  12269. linearGradient.appendChild(stop);
  12270. }
  12271. defs.appendChild(linearGradient);
  12272. svg.appendChild(defs);
  12273. }
  12274. var rect = document.createElementNS(svgn, "rect");
  12275. rect.setAttributeNS(null, "width", "100%");
  12276. rect.setAttributeNS(null, "height", "100%");
  12277. rect.setAttributeNS(null, "fill", "url(\"#".concat(gradientId, "\")"));
  12278. rect.setAttributeNS(null, "stroke", "black");
  12279. rect.setAttributeNS(null, "stroke-width", "0.1em");
  12280. svg.appendChild(rect);
  12281. return svg;
  12282. }
  12283. static waitAny(promises) {
  12284. return _asyncToGenerator(function* () {
  12285. return new Promise(resolve => {
  12286. promises.map(promise => {
  12287. promise.then(() => {
  12288. resolve();
  12289. });
  12290. });
  12291. });
  12292. })();
  12293. }
  12294. }
  12295. Utils.screenPass = new function () {
  12296. this.screenScene = new Scene();
  12297. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  12298. this.screenQuad.material.depthTest = true;
  12299. this.screenQuad.material.depthWrite = true;
  12300. this.screenQuad.material.transparent = true;
  12301. this.screenScene.add(this.screenQuad);
  12302. this.camera = new Camera();
  12303. this.render = function (renderer, material, target) {
  12304. this.screenQuad.material = material;
  12305. if (typeof target === 'undefined') {
  12306. renderer.render(this.screenScene, this.camera);
  12307. } else {
  12308. renderer.render(this.screenScene, this.camera, target);
  12309. }
  12310. };
  12311. }();
  12312. class Version {
  12313. constructor(version) {
  12314. this.version = version;
  12315. var vmLength = version.indexOf('.') === -1 ? version.length : version.indexOf('.');
  12316. this.versionMajor = parseInt(version.substr(0, vmLength));
  12317. this.versionMinor = parseInt(version.substr(vmLength + 1));
  12318. if (this.versionMinor.length === 0) {
  12319. this.versionMinor = 0;
  12320. }
  12321. }
  12322. newerThan(version) {
  12323. var v = new Version(version);
  12324. if (this.versionMajor > v.versionMajor) {
  12325. return true;
  12326. } else if (this.versionMajor === v.versionMajor && this.versionMinor > v.versionMinor) {
  12327. return true;
  12328. } else {
  12329. return false;
  12330. }
  12331. }
  12332. equalOrHigher(version) {
  12333. var v = new Version(version);
  12334. if (this.versionMajor > v.versionMajor) {
  12335. return true;
  12336. } else if (this.versionMajor === v.versionMajor && this.versionMinor >= v.versionMinor) {
  12337. return true;
  12338. } else {
  12339. return false;
  12340. }
  12341. }
  12342. upTo(version) {
  12343. return !this.newerThan(version);
  12344. }
  12345. }
  12346. //加载 解析点云
  12347. class BinaryLoader {
  12348. constructor(version, boundingBox, scale) {
  12349. if (typeof version === 'string') {
  12350. this.version = new Version(version);
  12351. } else {
  12352. this.version = version;
  12353. }
  12354. this.boundingBox = boundingBox;
  12355. this.scale = scale;
  12356. }
  12357. load(node) {
  12358. if (node.loaded) {
  12359. return;
  12360. }
  12361. var url = node.getURL();
  12362. if (this.version.equalOrHigher('1.4')) {
  12363. url += '.bin';
  12364. }
  12365. var xhr = XHRFactory.createXMLHttpRequest();
  12366. xhr.open('GET', url, true);
  12367. xhr.responseType = 'arraybuffer';
  12368. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  12369. xhr.onreadystatechange = () => {
  12370. if (xhr.readyState === 4) {
  12371. if ((xhr.status === 200 || xhr.status === 0) && xhr.response !== null) {
  12372. var buffer = xhr.response;
  12373. this.parse(node, buffer);
  12374. } else {
  12375. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  12376. throw new Error("Failed to load file! HTTP status: ".concat(xhr.status, ", file: ").concat(url));
  12377. }
  12378. }
  12379. };
  12380. try {
  12381. xhr.send(null);
  12382. } catch (e) {
  12383. console.log('fehler beim laden der punktwolke: ' + e);
  12384. }
  12385. }
  12386. parse(node, buffer, callback) {
  12387. var pointAttributes = node.pcoGeometry.pointAttributes;
  12388. var numPoints = buffer.byteLength / node.pcoGeometry.pointAttributes.byteSize;
  12389. if (this.version.upTo('1.5')) {
  12390. node.numPoints = numPoints;
  12391. }
  12392. var workerPath = Potree.scriptPath + '/workers/BinaryDecoderWorker.js';
  12393. var worker = Potree.workerPool.getWorker(workerPath);
  12394. worker.onmessage = function (e) {
  12395. var data = e.data;
  12396. var buffers = data.attributeBuffers;
  12397. var tightBoundingBox = new Box3(new Vector3().fromArray(data.tightBoundingBox.min), new Vector3().fromArray(data.tightBoundingBox.max));
  12398. Potree.workerPool.returnWorker(workerPath, worker);
  12399. var geometry = new BufferGeometry();
  12400. var _loop = function _loop() {
  12401. var buffer = buffers[property].buffer;
  12402. var batchAttribute = buffers[property].attribute;
  12403. if (property === "POSITION_CARTESIAN") {
  12404. geometry.setAttribute('position', new BufferAttribute(new Float32Array(buffer), 3));
  12405. } else if (property === "rgba") {
  12406. geometry.setAttribute("rgba", new BufferAttribute(new Uint8Array(buffer), 4, true));
  12407. } else if (property === "NORMAL_SPHEREMAPPED") {
  12408. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  12409. } else if (property === "NORMAL_OCT16") {
  12410. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  12411. } else if (property === "NORMAL") {
  12412. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(buffer), 3));
  12413. } else if (property === "INDICES") {
  12414. var bufferAttribute = new BufferAttribute(new Uint8Array(buffer), 4);
  12415. bufferAttribute.normalized = true;
  12416. geometry.setAttribute('indices', bufferAttribute);
  12417. } else if (property === "SPACING") {
  12418. var _bufferAttribute = new BufferAttribute(new Float32Array(buffer), 1);
  12419. geometry.setAttribute('spacing', _bufferAttribute);
  12420. } else {
  12421. var _bufferAttribute2 = new BufferAttribute(new Float32Array(buffer), 1);
  12422. _bufferAttribute2.potree = {
  12423. offset: buffers[property].offset,
  12424. scale: buffers[property].scale,
  12425. preciseBuffer: buffers[property].preciseBuffer,
  12426. range: batchAttribute.range
  12427. };
  12428. geometry.setAttribute(property, _bufferAttribute2);
  12429. var attribute = pointAttributes.attributes.find(a => a.name === batchAttribute.name);
  12430. attribute.range[0] = Math.min(attribute.range[0], batchAttribute.range[0]);
  12431. attribute.range[1] = Math.max(attribute.range[1], batchAttribute.range[1]);
  12432. if (node.getLevel() === 0) {
  12433. attribute.initialRange = batchAttribute.range;
  12434. }
  12435. }
  12436. };
  12437. for (var property in buffers) {
  12438. _loop();
  12439. }
  12440. tightBoundingBox.max.sub(tightBoundingBox.min);
  12441. tightBoundingBox.min.set(0, 0, 0);
  12442. var numPoints = e.data.buffer.byteLength / pointAttributes.byteSize;
  12443. node.numPoints = numPoints;
  12444. node.geometry = geometry;
  12445. node.mean = new Vector3(...data.mean);
  12446. node.tightBoundingBox = tightBoundingBox;
  12447. node.loaded = true;
  12448. node.loading = false;
  12449. node.estimatedSpacing = data.estimatedSpacing;
  12450. Potree.numNodesLoading--;
  12451. callback(); //add
  12452. };
  12453. var message = {
  12454. buffer: buffer,
  12455. pointAttributes: pointAttributes,
  12456. version: this.version.version,
  12457. min: [node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z],
  12458. offset: [node.pcoGeometry.offset.x, node.pcoGeometry.offset.y, node.pcoGeometry.offset.z],
  12459. scale: this.scale,
  12460. spacing: node.spacing,
  12461. hasChildren: node.hasChildren,
  12462. name: node.name
  12463. };
  12464. worker.postMessage(message, [message.buffer]);
  12465. }
  12466. }
  12467. var ftCanvas = document.createElement('canvas');
  12468. var Features = function () {
  12469. var gl = ftCanvas.getContext('webgl') || ftCanvas.getContext('experimental-webgl');
  12470. if (gl === null) {
  12471. return {};
  12472. }
  12473. // -- code taken from THREE.WebGLRenderer --
  12474. var _vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT);
  12475. var _vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT);
  12476. // Unused: let _vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT);
  12477. var _fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  12478. var _fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT);
  12479. // Unused: let _fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT);
  12480. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12481. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12482. // -----------------------------------------
  12483. var precision;
  12484. if (highpAvailable) {
  12485. precision = 'highp';
  12486. } else if (mediumpAvailable) {
  12487. precision = 'mediump';
  12488. } else {
  12489. precision = 'lowp';
  12490. }
  12491. return {
  12492. SHADER_INTERPOLATION: {
  12493. isSupported: function isSupported() {
  12494. var supported = true;
  12495. supported = supported && gl.getExtension('EXT_frag_depth');
  12496. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  12497. return supported;
  12498. }
  12499. },
  12500. SHADER_SPLATS: {
  12501. isSupported: function isSupported() {
  12502. var supported = true;
  12503. supported = supported && gl.getExtension('EXT_frag_depth');
  12504. supported = supported && gl.getExtension('OES_texture_float');
  12505. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  12506. return supported;
  12507. }
  12508. },
  12509. SHADER_EDL: {
  12510. isSupported: function isSupported() {
  12511. var supported = true;
  12512. supported = supported && gl.getExtension('EXT_frag_depth');
  12513. supported = supported && gl.getExtension('OES_texture_float');
  12514. supported = supported && gl.getParameter(gl.MAX_VARYING_VECTORS) >= 8;
  12515. //supported = supported || (gl instanceof WebGL2RenderingContext);
  12516. return supported;
  12517. }
  12518. },
  12519. //WEBGL2: {
  12520. // isSupported: function(){
  12521. // return typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext;
  12522. // }
  12523. //},
  12524. precision: precision
  12525. };
  12526. }();
  12527. /**
  12528. * Some types of possible point attribute data formats
  12529. *
  12530. * @class
  12531. */
  12532. var PointAttributeTypes = {
  12533. DATA_TYPE_DOUBLE: {
  12534. ordinal: 0,
  12535. name: "double",
  12536. size: 8
  12537. },
  12538. DATA_TYPE_FLOAT: {
  12539. ordinal: 1,
  12540. name: "float",
  12541. size: 4
  12542. },
  12543. DATA_TYPE_INT8: {
  12544. ordinal: 2,
  12545. name: "int8",
  12546. size: 1
  12547. },
  12548. DATA_TYPE_UINT8: {
  12549. ordinal: 3,
  12550. name: "uint8",
  12551. size: 1
  12552. },
  12553. DATA_TYPE_INT16: {
  12554. ordinal: 4,
  12555. name: "int16",
  12556. size: 2
  12557. },
  12558. DATA_TYPE_UINT16: {
  12559. ordinal: 5,
  12560. name: "uint16",
  12561. size: 2
  12562. },
  12563. DATA_TYPE_INT32: {
  12564. ordinal: 6,
  12565. name: "int32",
  12566. size: 4
  12567. },
  12568. DATA_TYPE_UINT32: {
  12569. ordinal: 7,
  12570. name: "uint32",
  12571. size: 4
  12572. },
  12573. DATA_TYPE_INT64: {
  12574. ordinal: 8,
  12575. name: "int64",
  12576. size: 8
  12577. },
  12578. DATA_TYPE_UINT64: {
  12579. ordinal: 9,
  12580. name: "uint64",
  12581. size: 8
  12582. }
  12583. };
  12584. var i$1 = 0;
  12585. for (var obj in PointAttributeTypes) {
  12586. PointAttributeTypes[i$1] = PointAttributeTypes[obj];
  12587. i$1++;
  12588. }
  12589. class PointAttribute {
  12590. constructor(name, type, numElements) {
  12591. this.name = name;
  12592. this.type = type;
  12593. this.numElements = numElements;
  12594. this.byteSize = this.numElements * this.type.size;
  12595. this.description = "";
  12596. this.range = [Infinity, -Infinity];
  12597. }
  12598. }
  12599. ;
  12600. PointAttribute.POSITION_CARTESIAN = new PointAttribute("POSITION_CARTESIAN", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  12601. PointAttribute.RGBA_PACKED = new PointAttribute("COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 4);
  12602. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  12603. PointAttribute.RGB_PACKED = new PointAttribute("COLOR_PACKED", PointAttributeTypes.DATA_TYPE_INT8, 3);
  12604. PointAttribute.NORMAL_FLOATS = new PointAttribute("NORMAL_FLOATS", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  12605. PointAttribute.INTENSITY = new PointAttribute("INTENSITY", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  12606. PointAttribute.CLASSIFICATION = new PointAttribute("CLASSIFICATION", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  12607. PointAttribute.NORMAL_SPHEREMAPPED = new PointAttribute("NORMAL_SPHEREMAPPED", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  12608. PointAttribute.NORMAL_OCT16 = new PointAttribute("NORMAL_OCT16", PointAttributeTypes.DATA_TYPE_UINT8, 2);
  12609. PointAttribute.NORMAL = new PointAttribute("NORMAL", PointAttributeTypes.DATA_TYPE_FLOAT, 3);
  12610. PointAttribute.RETURN_NUMBER = new PointAttribute("RETURN_NUMBER", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  12611. PointAttribute.NUMBER_OF_RETURNS = new PointAttribute("NUMBER_OF_RETURNS", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  12612. PointAttribute.SOURCE_ID = new PointAttribute("SOURCE_ID", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  12613. PointAttribute.INDICES = new PointAttribute("INDICES", PointAttributeTypes.DATA_TYPE_UINT32, 1);
  12614. PointAttribute.SPACING = new PointAttribute("SPACING", PointAttributeTypes.DATA_TYPE_FLOAT, 1);
  12615. PointAttribute.GPS_TIME = new PointAttribute("GPS_TIME", PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  12616. class PointAttributes {
  12617. constructor(pointAttributes) {
  12618. this.attributes = [];
  12619. this.byteSize = 0;
  12620. this.size = 0;
  12621. this.vectors = [];
  12622. if (pointAttributes != null) {
  12623. for (var _i = 0; _i < pointAttributes.length; _i++) {
  12624. var pointAttributeName = pointAttributes[_i];
  12625. var pointAttribute = PointAttribute[pointAttributeName];
  12626. this.attributes.push(pointAttribute);
  12627. this.byteSize += pointAttribute.byteSize;
  12628. this.size++;
  12629. }
  12630. }
  12631. }
  12632. add(pointAttribute) {
  12633. this.attributes.push(pointAttribute);
  12634. this.byteSize += pointAttribute.byteSize;
  12635. this.size++;
  12636. }
  12637. addVector(vector) {
  12638. this.vectors.push(vector);
  12639. }
  12640. hasNormals() {
  12641. for (var name in this.attributes) {
  12642. var pointAttribute = this.attributes[name];
  12643. if (pointAttribute === PointAttribute.NORMAL_SPHEREMAPPED || pointAttribute === PointAttribute.NORMAL_FLOATS || pointAttribute === PointAttribute.NORMAL || pointAttribute === PointAttribute.NORMAL_OCT16) {
  12644. return true;
  12645. }
  12646. }
  12647. return false;
  12648. }
  12649. }
  12650. class Points$1 {
  12651. constructor() {
  12652. this.boundingBox = new Box3();
  12653. this.numPoints = 0;
  12654. this.data = {};
  12655. }
  12656. add(points) {
  12657. var currentSize = this.numPoints;
  12658. var additionalSize = points.numPoints;
  12659. var newSize = currentSize + additionalSize;
  12660. var thisAttributes = Object.keys(this.data);
  12661. var otherAttributes = Object.keys(points.data);
  12662. var attributes = new Set([...thisAttributes, ...otherAttributes]);
  12663. for (var attribute of attributes) {
  12664. if (thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  12665. // attribute in both, merge
  12666. var Type = this.data[attribute].constructor;
  12667. var merged = new Type(this.data[attribute].length + points.data[attribute].length);
  12668. merged.set(this.data[attribute], 0);
  12669. merged.set(points.data[attribute], this.data[attribute].length);
  12670. this.data[attribute] = merged;
  12671. } else if (thisAttributes.includes(attribute) && !otherAttributes.includes(attribute)) {
  12672. // attribute only in this; take over this and expand to new size
  12673. var elementsPerPoint = this.data[attribute].length / this.numPoints;
  12674. var _Type = this.data[attribute].constructor;
  12675. var expanded = new _Type(elementsPerPoint * newSize);
  12676. expanded.set(this.data[attribute], 0);
  12677. this.data[attribute] = expanded;
  12678. } else if (!thisAttributes.includes(attribute) && otherAttributes.includes(attribute)) {
  12679. // attribute only in points to be added; take over new points and expand to new size
  12680. var _elementsPerPoint = points.data[attribute].length / points.numPoints;
  12681. var _Type2 = points.data[attribute].constructor;
  12682. var _expanded = new _Type2(_elementsPerPoint * newSize);
  12683. _expanded.set(points.data[attribute], _elementsPerPoint * currentSize);
  12684. this.data[attribute] = _expanded;
  12685. }
  12686. }
  12687. this.numPoints = newSize;
  12688. this.boundingBox.union(points.boundingBox);
  12689. }
  12690. }
  12691. class CSVExporter {
  12692. static toString(points) {
  12693. var string = '';
  12694. var attributes = Object.keys(points.data).filter(a => a !== 'normal').sort((a, b) => {
  12695. if (a === 'position') return -1;
  12696. if (b === 'position') return 1;
  12697. if (a === 'rgba') return -1;
  12698. if (b === 'rgba') return 1;
  12699. });
  12700. var headerValues = [];
  12701. for (var attribute of attributes) {
  12702. var itemSize = points.data[attribute].length / points.numPoints;
  12703. if (attribute === 'position') {
  12704. headerValues = headerValues.concat(['x', 'y', 'z']);
  12705. } else if (attribute === 'rgba') {
  12706. headerValues = headerValues.concat(['r', 'g', 'b', 'a']);
  12707. } else if (itemSize > 1) {
  12708. for (var i = 0; i < itemSize; i++) {
  12709. headerValues.push("".concat(attribute, "_").concat(i));
  12710. }
  12711. } else {
  12712. headerValues.push(attribute);
  12713. }
  12714. }
  12715. string = headerValues.join(', ') + '\n';
  12716. for (var _i = 0; _i < points.numPoints; _i++) {
  12717. var values = [];
  12718. for (var _attribute of attributes) {
  12719. var _itemSize = points.data[_attribute].length / points.numPoints;
  12720. var value = points.data[_attribute].subarray(_itemSize * _i, _itemSize * _i + _itemSize).join(', ');
  12721. values.push(value);
  12722. }
  12723. string += values.join(', ') + '\n';
  12724. }
  12725. return string;
  12726. }
  12727. }
  12728. ;
  12729. class LASExporter {
  12730. static toLAS(points) {
  12731. // TODO Unused: let string = '';
  12732. var boundingBox = points.boundingBox;
  12733. var offset = boundingBox.min.clone();
  12734. var diagonal = boundingBox.min.distanceTo(boundingBox.max);
  12735. var scale = new Vector3(0.001, 0.001, 0.001);
  12736. if (diagonal > 1000 * 1000) {
  12737. scale = new Vector3(0.01, 0.01, 0.01);
  12738. } else {
  12739. scale = new Vector3(0.001, 0.001, 0.001);
  12740. }
  12741. var setString = function setString(string, offset, buffer) {
  12742. var view = new Uint8Array(buffer);
  12743. for (var i = 0; i < string.length; i++) {
  12744. var charCode = string.charCodeAt(i);
  12745. view[offset + i] = charCode;
  12746. }
  12747. };
  12748. var buffer = new ArrayBuffer(227 + 28 * points.numPoints);
  12749. var view = new DataView(buffer);
  12750. var u8View = new Uint8Array(buffer);
  12751. // let u16View = new Uint16Array(buffer);
  12752. setString('LASF', 0, buffer);
  12753. u8View[24] = 1;
  12754. u8View[25] = 2;
  12755. // system identifier o:26 l:32
  12756. // generating software o:58 l:32
  12757. setString('Potree 1.7', 58, buffer);
  12758. // file creation day of year o:90 l:2
  12759. // file creation year o:92 l:2
  12760. // header size o:94 l:2
  12761. view.setUint16(94, 227, true);
  12762. // offset to point data o:96 l:4
  12763. view.setUint32(96, 227, true);
  12764. // number of letiable length records o:100 l:4
  12765. // point data record format 104 1
  12766. u8View[104] = 2;
  12767. // point data record length 105 2
  12768. view.setUint16(105, 28, true);
  12769. // number of point records 107 4
  12770. view.setUint32(107, points.numPoints, true);
  12771. // number of points by return 111 20
  12772. // x scale factor 131 8
  12773. view.setFloat64(131, scale.x, true);
  12774. // y scale factor 139 8
  12775. view.setFloat64(139, scale.y, true);
  12776. // z scale factor 147 8
  12777. view.setFloat64(147, scale.z, true);
  12778. // x offset 155 8
  12779. view.setFloat64(155, offset.x, true);
  12780. // y offset 163 8
  12781. view.setFloat64(163, offset.y, true);
  12782. // z offset 171 8
  12783. view.setFloat64(171, offset.z, true);
  12784. // max x 179 8
  12785. view.setFloat64(179, boundingBox.max.x, true);
  12786. // min x 187 8
  12787. view.setFloat64(187, boundingBox.min.x, true);
  12788. // max y 195 8
  12789. view.setFloat64(195, boundingBox.max.y, true);
  12790. // min y 203 8
  12791. view.setFloat64(203, boundingBox.min.y, true);
  12792. // max z 211 8
  12793. view.setFloat64(211, boundingBox.max.z, true);
  12794. // min z 219 8
  12795. view.setFloat64(219, boundingBox.min.z, true);
  12796. var boffset = 227;
  12797. for (var i = 0; i < points.numPoints; i++) {
  12798. var px = points.data.position[3 * i + 0];
  12799. var py = points.data.position[3 * i + 1];
  12800. var pz = points.data.position[3 * i + 2];
  12801. var ux = parseInt((px - offset.x) / scale.x);
  12802. var uy = parseInt((py - offset.y) / scale.y);
  12803. var uz = parseInt((pz - offset.z) / scale.z);
  12804. view.setUint32(boffset + 0, ux, true);
  12805. view.setUint32(boffset + 4, uy, true);
  12806. view.setUint32(boffset + 8, uz, true);
  12807. if (points.data.intensity) {
  12808. view.setUint16(boffset + 12, points.data.intensity[i], true);
  12809. }
  12810. var rt = 0;
  12811. if (points.data.returnNumber) {
  12812. rt += points.data.returnNumber[i];
  12813. }
  12814. if (points.data.numberOfReturns) {
  12815. rt += points.data.numberOfReturns[i] << 3;
  12816. }
  12817. view.setUint8(boffset + 14, rt);
  12818. if (points.data.classification) {
  12819. view.setUint8(boffset + 15, points.data.classification[i]);
  12820. }
  12821. // scan angle rank
  12822. // user data
  12823. // point source id
  12824. if (points.data.pointSourceID) {
  12825. view.setUint16(boffset + 18, points.data.pointSourceID[i]);
  12826. }
  12827. if (points.data.rgba) {
  12828. var rgba = points.data.rgba;
  12829. view.setUint16(boffset + 20, rgba[4 * i + 0] * 255, true);
  12830. view.setUint16(boffset + 22, rgba[4 * i + 1] * 255, true);
  12831. view.setUint16(boffset + 24, rgba[4 * i + 2] * 255, true);
  12832. }
  12833. boffset += 28;
  12834. }
  12835. return buffer;
  12836. }
  12837. }
  12838. /**
  12839. * @author mrdoob / http://mrdoob.com/ https://github.com/mrdoob/eventdispatcher.js
  12840. *
  12841. * with slight modifications by mschuetz, http://potree.org
  12842. *
  12843. */
  12844. // The MIT License
  12845. //
  12846. // Copyright (c) 2011 Mr.doob
  12847. //
  12848. // Permission is hereby granted, free of charge, to any person obtaining a copy
  12849. // of this software and associated documentation files (the "Software"), to deal
  12850. // in the Software without restriction, including without limitation the rights
  12851. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12852. // copies of the Software, and to permit persons to whom the Software is
  12853. // furnished to do so, subject to the following conditions:
  12854. //
  12855. // The above copyright notice and this permission notice shall be included in
  12856. // all copies or substantial portions of the Software.
  12857. //
  12858. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12859. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12860. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12861. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12862. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12863. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  12864. // THE SOFTWARE.
  12865. class EventDispatcher$1 {
  12866. constructor() {
  12867. this._listeners = {};
  12868. }
  12869. addEventListener(type, listener) {
  12870. var listeners = this._listeners;
  12871. if (listeners[type] === undefined) {
  12872. listeners[type] = [];
  12873. }
  12874. if (listeners[type].indexOf(listener) === -1) {
  12875. listeners[type].push(listener);
  12876. }
  12877. }
  12878. hasEventListener(type, listener) {
  12879. var listeners = this._listeners;
  12880. return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  12881. }
  12882. removeEventListener(type, listener) {
  12883. var listeners = this._listeners;
  12884. var listenerArray = listeners[type];
  12885. if (listenerArray !== undefined) {
  12886. var index = listenerArray.indexOf(listener);
  12887. if (index !== -1) {
  12888. listenerArray.splice(index, 1);
  12889. }
  12890. }
  12891. }
  12892. removeEventListeners(type) {
  12893. if (this._listeners[type] !== undefined) {
  12894. delete this._listeners[type];
  12895. }
  12896. }
  12897. dispatchEvent(event) {
  12898. var listeners = this._listeners;
  12899. var listenerArray = listeners[event.type];
  12900. if (listenerArray !== undefined) {
  12901. event.target = this;
  12902. for (var listener of listenerArray.slice(0)) {
  12903. listener.call(this, event);
  12904. }
  12905. }
  12906. }
  12907. }
  12908. class PointCloudTreeNode extends EventDispatcher$1 {
  12909. constructor() {
  12910. super();
  12911. this.needsTransformUpdate = true;
  12912. }
  12913. getChildren() {
  12914. throw new Error('override function');
  12915. }
  12916. getBoundingBox() {
  12917. throw new Error('override function');
  12918. }
  12919. isLoaded() {
  12920. throw new Error('override function');
  12921. }
  12922. isGeometryNode() {
  12923. throw new Error('override function');
  12924. }
  12925. isTreeNode() {
  12926. throw new Error('override function');
  12927. }
  12928. getLevel() {
  12929. throw new Error('override function');
  12930. }
  12931. getBoundingSphere() {
  12932. throw new Error('override function');
  12933. }
  12934. }
  12935. ;
  12936. class PointCloudTree extends Object3D {
  12937. constructor() {
  12938. super();
  12939. //this.spriteGroup = new THREE.Object3D //add
  12940. }
  12941. initialized() {
  12942. return this.root !== null;
  12943. }
  12944. }
  12945. ;
  12946. class PointCloudOctreeGeometry {
  12947. constructor() {
  12948. this.url = null;
  12949. this.octreeDir = null;
  12950. this.spacing = 0;
  12951. this.boundingBox = null;
  12952. this.root = null;
  12953. this.nodes = null;
  12954. this.pointAttributes = null;
  12955. this.hierarchyStepSize = -1;
  12956. this.loader = null;
  12957. }
  12958. }
  12959. class PointCloudOctreeGeometryNode extends PointCloudTreeNode {
  12960. constructor(name, pcoGeometry, boundingBox) {
  12961. super();
  12962. this.id = PointCloudOctreeGeometryNode.IDCount++;
  12963. this.name = name;
  12964. this.index = parseInt(name.charAt(name.length - 1));
  12965. this.pcoGeometry = pcoGeometry;
  12966. this.geometry = null;
  12967. this.boundingBox = boundingBox;
  12968. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  12969. this.children = {};
  12970. this.numPoints = 0;
  12971. this.level = null;
  12972. this.loaded = false;
  12973. this.oneTimeDisposeHandlers = [];
  12974. }
  12975. isGeometryNode() {
  12976. return true;
  12977. }
  12978. getLevel() {
  12979. return this.level;
  12980. }
  12981. isTreeNode() {
  12982. return false;
  12983. }
  12984. isLoaded() {
  12985. return this.loaded;
  12986. }
  12987. getBoundingSphere() {
  12988. return this.boundingSphere;
  12989. }
  12990. getBoundingBox() {
  12991. return this.boundingBox;
  12992. }
  12993. getChildren() {
  12994. var children = [];
  12995. for (var i = 0; i < 8; i++) {
  12996. if (this.children[i]) {
  12997. children.push(this.children[i]);
  12998. }
  12999. }
  13000. return children;
  13001. }
  13002. getBoundingBox() {
  13003. return this.boundingBox;
  13004. }
  13005. getURL() {
  13006. var url = '';
  13007. var version = this.pcoGeometry.loader.version;
  13008. if (version.equalOrHigher('1.5')) {
  13009. url = this.pcoGeometry.octreeDir + '/' + this.getHierarchyPath() + '/' + this.name;
  13010. } else if (version.equalOrHigher('1.4')) {
  13011. url = this.pcoGeometry.octreeDir + '/' + this.name;
  13012. } else if (version.upTo('1.3')) {
  13013. url = this.pcoGeometry.octreeDir + '/' + this.name;
  13014. }
  13015. return url;
  13016. }
  13017. getHierarchyPath() {
  13018. var path = 'r/';
  13019. var hierarchyStepSize = this.pcoGeometry.hierarchyStepSize;
  13020. var indices = this.name.substr(1);
  13021. var numParts = Math.floor(indices.length / hierarchyStepSize);
  13022. for (var i = 0; i < numParts; i++) {
  13023. path += indices.substr(i * hierarchyStepSize, hierarchyStepSize) + '/';
  13024. }
  13025. path = path.slice(0, -1);
  13026. return path;
  13027. }
  13028. addChild(child) {
  13029. this.children[child.index] = child;
  13030. child.parent = this;
  13031. }
  13032. load() {
  13033. if (this.loading === true || this.loaded === true || Potree.numNodesLoading >= Potree.maxNodesLoading) {
  13034. return;
  13035. }
  13036. this.loading = true;
  13037. Potree.numNodesLoading++;
  13038. if (this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  13039. if (this.level % this.pcoGeometry.hierarchyStepSize === 0 && this.hasChildren) {
  13040. this.loadHierachyThenPoints();
  13041. } else {
  13042. this.loadPoints();
  13043. }
  13044. } else {
  13045. this.pcoGeometry.dispatchEvent({
  13046. type: 'updateNodeMaxLevel',
  13047. level: this.level
  13048. }); //add
  13049. this.loadPoints();
  13050. }
  13051. }
  13052. loadPoints() {
  13053. this.pcoGeometry.loader.load(this);
  13054. }
  13055. loadHierachyThenPoints() {
  13056. var node = this;
  13057. // load hierarchy
  13058. var callback = function callback(node, hbuffer) {
  13059. var tStart = performance.now();
  13060. var view = new DataView(hbuffer);
  13061. var stack = [];
  13062. var children = view.getUint8(0);
  13063. var numPoints = view.getUint32(1, true);
  13064. node.numPoints = numPoints;
  13065. stack.push({
  13066. children: children,
  13067. numPoints: numPoints,
  13068. name: node.name
  13069. });
  13070. var decoded = [];
  13071. var offset = 5;
  13072. while (stack.length > 0) {
  13073. var snode = stack.shift();
  13074. var mask = 1;
  13075. for (var i = 0; i < 8; i++) {
  13076. if ((snode.children & mask) !== 0) {
  13077. var childName = snode.name + i;
  13078. var childChildren = view.getUint8(offset);
  13079. var childNumPoints = view.getUint32(offset + 1, true);
  13080. stack.push({
  13081. children: childChildren,
  13082. numPoints: childNumPoints,
  13083. name: childName
  13084. });
  13085. decoded.push({
  13086. children: childChildren,
  13087. numPoints: childNumPoints,
  13088. name: childName
  13089. });
  13090. offset += 5;
  13091. }
  13092. mask = mask * 2;
  13093. }
  13094. if (offset === hbuffer.byteLength) {
  13095. break;
  13096. }
  13097. }
  13098. // console.log(decoded);
  13099. var nodes = {};
  13100. nodes[node.name] = node;
  13101. var pco = node.pcoGeometry;
  13102. for (var _i = 0; _i < decoded.length; _i++) {
  13103. var name = decoded[_i].name;
  13104. var decodedNumPoints = decoded[_i].numPoints;
  13105. var index = parseInt(name.charAt(name.length - 1));
  13106. var parentName = name.substring(0, name.length - 1);
  13107. var parentNode = nodes[parentName];
  13108. var level = name.length - 1;
  13109. var boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  13110. var currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  13111. currentNode.level = level;
  13112. currentNode.numPoints = decodedNumPoints;
  13113. currentNode.hasChildren = decoded[_i].children > 0;
  13114. currentNode.spacing = pco.spacing / Math.pow(2, level);
  13115. parentNode.addChild(currentNode);
  13116. nodes[name] = currentNode;
  13117. }
  13118. var duration = performance.now() - tStart;
  13119. if (duration > 5) {
  13120. var msg = "duration: ".concat(duration, "ms, numNodes: ").concat(decoded.length);
  13121. console.log(msg);
  13122. }
  13123. node.loadPoints();
  13124. };
  13125. if (node.level % node.pcoGeometry.hierarchyStepSize === 0) {
  13126. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  13127. var hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  13128. var xhr = XHRFactory.createXMLHttpRequest();
  13129. xhr.open('GET', hurl, true);
  13130. xhr.responseType = 'arraybuffer';
  13131. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  13132. xhr.onreadystatechange = () => {
  13133. if (xhr.readyState === 4) {
  13134. if (xhr.status === 200 || xhr.status === 0) {
  13135. var hbuffer = xhr.response;
  13136. callback(node, hbuffer);
  13137. } else {
  13138. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  13139. Potree.numNodesLoading--;
  13140. }
  13141. }
  13142. };
  13143. try {
  13144. xhr.send(null);
  13145. } catch (e) {
  13146. console.log('fehler beim laden der punktwolke: ' + e);
  13147. }
  13148. }
  13149. }
  13150. getNumPoints() {
  13151. return this.numPoints;
  13152. }
  13153. dispose() {
  13154. if (this.geometry && this.parent != null) {
  13155. this.geometry.dispose();
  13156. this.geometry = null;
  13157. this.loaded = false;
  13158. this.dispatchEvent({
  13159. type: 'dispose'
  13160. });
  13161. for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  13162. var handler = this.oneTimeDisposeHandlers[i];
  13163. handler();
  13164. }
  13165. this.oneTimeDisposeHandlers = [];
  13166. }
  13167. }
  13168. }
  13169. PointCloudOctreeGeometryNode.IDCount = 0;
  13170. // -------------------------------------------
  13171. // to get a ready to use gradient array from a chroma.js gradient:
  13172. // http://gka.github.io/chroma.js/
  13173. // -------------------------------------------
  13174. //
  13175. // let stops = [];
  13176. // for(let i = 0; i <= 10; i++){
  13177. // let range = chroma.scale(['yellow', 'navy']).mode('lch').domain([10,0])(i)._rgb
  13178. // .slice(0, 3)
  13179. // .map(v => (v / 255).toFixed(4))
  13180. // .join(", ");
  13181. //
  13182. // let line = `[${i / 10}, new THREE.Color(${range})],`;
  13183. //
  13184. // stops.push(line);
  13185. // }
  13186. // stops.join("\n");
  13187. //
  13188. //
  13189. //
  13190. // -------------------------------------------
  13191. // to get a ready to use gradient array from matplotlib:
  13192. // -------------------------------------------
  13193. // import matplotlib.pyplot as plt
  13194. // import matplotlib.colors as colors
  13195. //
  13196. // norm = colors.Normalize(vmin=0,vmax=1)
  13197. // cmap = plt.cm.viridis
  13198. //
  13199. // for i in range(0,11):
  13200. // u = i / 10
  13201. // rgb = cmap(norm(u))[0:3]
  13202. // rgb = ["{0:.3f}".format(v) for v in rgb]
  13203. // rgb = "[" + str(u) + ", new THREE.Color(" + ", ".join(rgb) + ")],"
  13204. // print(rgb)
  13205. var Gradients = {
  13206. // From chroma spectral http://gka.github.io/chroma.js/
  13207. SPECTRAL: [[0, new Color(0.3686, 0.3098, 0.6353)], [0.1, new Color(0.1961, 0.5333, 0.7412)], [0.2, new Color(0.4000, 0.7608, 0.6471)], [0.3, new Color(0.6706, 0.8667, 0.6431)], [0.4, new Color(0.9020, 0.9608, 0.5961)], [0.5, new Color(1.0000, 1.0000, 0.7490)], [0.6, new Color(0.9961, 0.8784, 0.5451)], [0.7, new Color(0.9922, 0.6824, 0.3804)], [0.8, new Color(0.9569, 0.4275, 0.2627)], [0.9, new Color(0.8353, 0.2431, 0.3098)], [1, new Color(0.6196, 0.0039, 0.2588)]],
  13208. PLASMA: [[0.0, new Color(0.241, 0.015, 0.610)], [0.1, new Color(0.387, 0.001, 0.654)], [0.2, new Color(0.524, 0.025, 0.653)], [0.3, new Color(0.651, 0.125, 0.596)], [0.4, new Color(0.752, 0.227, 0.513)], [0.5, new Color(0.837, 0.329, 0.431)], [0.6, new Color(0.907, 0.435, 0.353)], [0.7, new Color(0.963, 0.554, 0.272)], [0.8, new Color(0.992, 0.681, 0.195)], [0.9, new Color(0.987, 0.822, 0.144)], [1.0, new Color(0.940, 0.975, 0.131)]],
  13209. YELLOW_GREEN: [[0, new Color(0.1647, 0.2824, 0.3451)], [0.1, new Color(0.1338, 0.3555, 0.4227)], [0.2, new Color(0.0610, 0.4319, 0.4864)], [0.3, new Color(0.0000, 0.5099, 0.5319)], [0.4, new Color(0.0000, 0.5881, 0.5569)], [0.5, new Color(0.1370, 0.6650, 0.5614)], [0.6, new Color(0.2906, 0.7395, 0.5477)], [0.7, new Color(0.4453, 0.8099, 0.5201)], [0.8, new Color(0.6102, 0.8748, 0.4850)], [0.9, new Color(0.7883, 0.9323, 0.4514)], [1, new Color(0.9804, 0.9804, 0.4314)]],
  13210. VIRIDIS: [[0.0, new Color(0.267, 0.005, 0.329)], [0.1, new Color(0.283, 0.141, 0.458)], [0.2, new Color(0.254, 0.265, 0.530)], [0.3, new Color(0.207, 0.372, 0.553)], [0.4, new Color(0.164, 0.471, 0.558)], [0.5, new Color(0.128, 0.567, 0.551)], [0.6, new Color(0.135, 0.659, 0.518)], [0.7, new Color(0.267, 0.749, 0.441)], [0.8, new Color(0.478, 0.821, 0.318)], [0.9, new Color(0.741, 0.873, 0.150)], [1.0, new Color(0.993, 0.906, 0.144)]],
  13211. INFERNO: [[0.0, new Color(0.077, 0.042, 0.206)], [0.1, new Color(0.225, 0.036, 0.388)], [0.2, new Color(0.373, 0.074, 0.432)], [0.3, new Color(0.522, 0.128, 0.420)], [0.4, new Color(0.665, 0.182, 0.370)], [0.5, new Color(0.797, 0.255, 0.287)], [0.6, new Color(0.902, 0.364, 0.184)], [0.7, new Color(0.969, 0.516, 0.063)], [0.8, new Color(0.988, 0.683, 0.072)], [0.9, new Color(0.961, 0.859, 0.298)], [1.0, new Color(0.988, 0.998, 0.645)]],
  13212. GRAYSCALE: [[0, new Color(0, 0, 0)], [1, new Color(1, 1, 1)]],
  13213. // 16 samples of the TURBU color scheme
  13214. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  13215. // original file licensed under Apache-2.0
  13216. TURBO: [[0.00, new Color(0.18995, 0.07176, 0.23217)], [0.07, new Color(0.25107, 0.25237, 0.63374)], [0.13, new Color(0.27628, 0.42118, 0.89123)], [0.20, new Color(0.25862, 0.57958, 0.99876)], [0.27, new Color(0.15844, 0.73551, 0.92305)], [0.33, new Color(0.09267, 0.86554, 0.7623)], [0.40, new Color(0.19659, 0.94901, 0.59466)], [0.47, new Color(0.42778, 0.99419, 0.38575)], [0.53, new Color(0.64362, 0.98999, 0.23356)], [0.60, new Color(0.80473, 0.92452, 0.20459)], [0.67, new Color(0.93301, 0.81236, 0.22667)], [0.73, new Color(0.99314, 0.67408, 0.20348)], [0.80, new Color(0.9836, 0.49291, 0.12849)], [0.87, new Color(0.92105, 0.31489, 0.05475)], [0.93, new Color(0.81608, 0.18462, 0.01809)], [1.00, new Color(0.66449, 0.08436, 0.00424)]],
  13217. RAINBOW: [[0, new Color(0.278, 0, 0.714)], [1 / 6, new Color(0, 0, 1)], [2 / 6, new Color(0, 1, 1)], [3 / 6, new Color(0, 1, 0)], [4 / 6, new Color(1, 1, 0)], [5 / 6, new Color(1, 0.64, 0)], [1, new Color(1, 0, 0)]],
  13218. CONTOUR: [[0.00, new Color(0, 0, 0)], [0.03, new Color(0, 0, 0)], [0.04, new Color(1, 1, 1)], [1.00, new Color(1, 1, 1)]]
  13219. };
  13220. var Shaders = {};
  13221. Shaders["pointcloud_new.vs"] = "\nprecision highp float;\nprecision highp int;\n \n#define PI 3.141592653589793\n\n \n\n\n\n#if defined(usePanoMap) \n \n uniform samplerCube pano0Map; //\u968F\u4FBF\u8BBE\u7F6E\u4E00\u4E2AsamplerCube\u53BB\u4F7F\u7528\u90FD\u4F1A\u8BA9\u70B9\u4E91\u6D88\u5931\n uniform samplerCube pano1Map;\n \n uniform float progress;\n uniform float easeInOutRatio;\n\n \n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix; \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix;\n /*\n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n */\n#endif \n\n\n\n\n \n\n//--------------\n\n\n\n\n\nattribute vec3 position;\nattribute vec3 color;\nattribute float intensity;\nattribute float classification;\nattribute float returnNumber;\nattribute float numberOfReturns;\nattribute float pointSourceID;\nattribute vec4 indices; //\u6BCF\u4E2A\u70B9\u7684index\nattribute float spacing;\nattribute float gpsTime;\nattribute vec3 normal;\nattribute float aExtra;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat4 uViewInv;\n\n//uniform float uScreenWidth;\n//uniform float uScreenHeight;\nuniform vec2 resolution;\n\n\nuniform float fov;\nuniform float near;\nuniform float far;\n\n\n\n\nuniform bool uDebug;\n\nuniform bool uUseOrthographicCamera;\nuniform float uOrthoWidth;\nuniform float uOrthoHeight;\n\n#define CLIPTASK_NONE 0\n#define CLIPTASK_HIGHLIGHT 1\n#define CLIPTASK_SHOW_INSIDE 2\n#define CLIPTASK_SHOW_OUTSIDE 3\n\n#define CLIPMETHOD_INSIDE_ANY 0\n#define CLIPMETHOD_INSIDE_ALL 1\n\n//\u6700\u5916\u5C42\u88C1\u526A\uFF08\u4E0B\u8F7D\uFF09\n#if defined(bigClipInBox)\n\tuniform mat4 clipBoxBig_in;\n#endif\n//\u5185\u5C42\u88C1\u526A\n#if defined(num_in_clipboxes) && num_in_clipboxes > 0\n\tuniform mat4 clipBoxes_in[num_in_clipboxes];\n#endif\n#if defined(num_out_clipboxes) && num_out_clipboxes > 0\n\tuniform mat4 clipBoxes_out[num_out_clipboxes];\n#endif\n\n\n#if defined(num_clipspheres) && num_clipspheres > 0\n\tuniform mat4 uClipSpheres[num_clipspheres];\n#endif\n\n \n#if defined(num_highlightBox) && num_highlightBox > 0\n uniform mat4 boxes_highlight[num_highlightBox]; \n#endif \n\t\t \n\n#if defined(num_prism) && num_prism > 0\n uniform mat3 prismList[num_prism];\n uniform vec2 prismPoints[prismPointCountSum]; \n#endif \n\n#if defined(showBaseHeight) \n uniform sampler2D baseHeightAreaMap ;\n uniform vec2 baseHeightBoundZ;\n uniform vec4 baseHeightBoundXY; \n#endif \n\nuniform float size;\nuniform float minSize;\nuniform float maxSize; \nuniform float orthoMaxSize;//add\n\n\nuniform float uPCIndex;\nuniform float uOctreeSpacing;\nuniform float uNodeSpacing;\nuniform float uOctreeSize;\nuniform vec3 uBBSize;\nuniform float uLevel;\nuniform float levelPercent;//add\nuniform float uVNStart;\nuniform bool uIsLeafNode;\n\nuniform vec3 uColor;\nuniform float uOpacity; \nvarying float vOpacity; //add\n\n\n\nuniform vec2 elevationRange;\nuniform vec2 intensityRange;\n\nuniform vec2 uFilterReturnNumberRange;\nuniform vec2 uFilterNumberOfReturnsRange;\nuniform vec2 uFilterPointSourceIDClipRange;\nuniform vec2 uFilterGPSTimeClipRange;\n//uniform float ufilterByNormalThreshold; \n\nuniform float uGpsScale;\nuniform float uGpsOffset;\n\nuniform vec2 uNormalizedGpsBufferRange;\n\nuniform vec3 uIntensity_gbc;\nuniform vec3 uRGB_gbc;\nuniform vec3 uExtra_gbc;\n\nuniform float uTransition;\nuniform float wRGB;\nuniform float wIntensity;\nuniform float wElevation;\nuniform float wClassification;\nuniform float wReturnNumber;\nuniform float wSourceID;\n\nuniform vec2 uExtraNormalizedRange;\nuniform vec2 uExtraRange;\nuniform float uExtraScale;\nuniform float uExtraOffset;\n\nuniform vec3 uShadowColor;\n\nuniform sampler2D visibleNodes;\nuniform sampler2D gradient;\nuniform sampler2D classificationLUT;\n\n#if defined(color_type_matcap)\nuniform sampler2D matcapTextureUniform;\n#endif\nuniform bool backfaceCulling;\n\n#if defined(num_shadowmaps) && num_shadowmaps > 0\nuniform sampler2D uShadowMap[num_shadowmaps];\nuniform mat4 uShadowWorldView[num_shadowmaps];\nuniform mat4 uShadowProj[num_shadowmaps];\n#endif\n\n\n\nvarying vec3\tvColor;\nvarying float\tvLogDepth;\nvarying vec3\tvViewPosition;\nvarying float \tvRadius;\nvarying float \tvPointSize;\n\n\nfloat Round(float number){\n\treturn floor(number + 0.5);\n}\n\n// \n// ### ######## ### ######## ######## #### ## ## ######## ###### #### ######## ######## ###### \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ######## ## ## ## ## ###### ###### ## ## ###### ###### \n// ######### ## ## ######### ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ######## ## ## ## ## #### ### ######## ###### #### ######## ######## ###### \n// \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\n\n// ---------------------\n// OCTREE\n// ---------------------\n\n#if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_octree)\n/**\n * number of 1-bits up to inclusive index position\n * number is treated as if it were an integer in the range 0-255\n *\n */\nint numberOfOnes(int number, int index){\n\tint numOnes = 0;\n\tint tmp = 128;\n\tfor(int i = 7; i >= 0; i--){\n\t\t\n\t\tif(number >= tmp){\n\t\t\tnumber = number - tmp;\n\n\t\t\tif(i <= index){\n\t\t\t\tnumOnes++;\n\t\t\t}\n\t\t}\n\t\t\n\t\ttmp = tmp / 2;\n\t}\n\n\treturn numOnes;\n}\n\n\n/**\n * checks whether the bit at index is 1\n * number is treated as if it were an integer in the range 0-255\n *\n */\nbool isBitSet(int number, int index){\n\n\t// weird multi else if due to lack of proper array, int and bitwise support in WebGL 1.0\n\tint powi = 1;\n\tif(index == 0){\n\t\tpowi = 1;\n\t}else if(index == 1){\n\t\tpowi = 2;\n\t}else if(index == 2){\n\t\tpowi = 4;\n\t}else if(index == 3){\n\t\tpowi = 8;\n\t}else if(index == 4){\n\t\tpowi = 16;\n\t}else if(index == 5){\n\t\tpowi = 32;\n\t}else if(index == 6){\n\t\tpowi = 64;\n\t}else if(index == 7){\n\t\tpowi = 128;\n\t}else{\n\t\treturn false;\n\t}\n\n\tint ndp = number / powi;\n\n\treturn mod(float(ndp), 2.0) != 0.0;\n}\n\n\n/**\n * find the LOD at the point position\n */\nfloat getLOD(){//////we use this\n\t \n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tint iOffset = int(uVNStart);\n\tfloat depth = uLevel;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tint index = int(Round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));\n\t\tint mask = int(Round(value.r * 255.0));\n\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tint advanceG = int(Round(value.g * 255.0)) * 256;\n\t\t\tint advanceB = int(Round(value.b * 255.0));\n\t\t\tint advanceChild = numberOfOnes(mask, index - 1);\n\t\t\tint advance = advanceG + advanceB + advanceChild;\n\n\t\t\tiOffset = iOffset + advance;\n\t\t\t\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\t//return value.a * 255.0;\n\n\t\t\tfloat lodOffset = (255.0 * value.a) / 10.0 - 10.0;\n\n\t\t\treturn depth + lodOffset;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn depth;\n}\n\nfloat getSpacing(){\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tint iOffset = int(uVNStart);\n\tfloat depth = uLevel;\n\tfloat spacing = uNodeSpacing;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tint index = int(Round(4.0 * index3d.x + 2.0 * index3d.y + index3d.z));\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(float(iOffset) / 2048.0, 0.0));\n\t\tint mask = int(Round(value.r * 255.0));\n\t\tfloat spacingFactor = value.a;\n\n\t\tif(i > 0.0){\n\t\t\tspacing = spacing / (255.0 * spacingFactor);\n\t\t}\n\t\t\n\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tint advanceG = int(Round(value.g * 255.0)) * 256;\n\t\t\tint advanceB = int(Round(value.b * 255.0));\n\t\t\tint advanceChild = numberOfOnes(mask, index - 1);\n\t\t\tint advance = advanceG + advanceB + advanceChild;\n\n\t\t\tiOffset = iOffset + advance;\n\n\t\t\t//spacing = spacing / (255.0 * spacingFactor);\n\t\t\t//spacing = spacing / 3.0;\n\t\t\t\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\treturn spacing;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn spacing;\n}\n\nfloat getPointSizeAttenuation(){\n\treturn pow(2.0, getLOD());\n}\n\n\n#endif\n\n\n// ---------------------\n// KD-TREE\n// ---------------------\n\n#if (defined(adaptive_point_size) || defined(color_type_level_of_detail)) && defined(tree_type_kdtree)\n\nfloat getLOD(){\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tfloat iOffset = 0.0;\n\tfloat depth = 0.0;\n\t\t\n\t\t\n\tvec3 size = uBBSize;\t\n\tvec3 pos = position;\n\t\t\n\tfor(float i = 0.0; i <= 1000.0; i++){\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));\n\t\t\n\t\tint children = int(value.r * 255.0);\n\t\tfloat next = value.g * 255.0;\n\t\tint split = int(value.b * 255.0);\n\t\t\n\t\tif(next == 0.0){\n\t\t \treturn depth;\n\t\t}\n\t\t\n\t\tvec3 splitv = vec3(0.0, 0.0, 0.0);\n\t\tif(split == 1){\n\t\t\tsplitv.x = 1.0;\n\t\t}else if(split == 2){\n\t\t \tsplitv.y = 1.0;\n\t\t}else if(split == 4){\n\t\t \tsplitv.z = 1.0;\n\t\t}\n\t\t\n\t\tiOffset = iOffset + next;\n\t\t\n\t\tfloat factor = length(pos * splitv / size);\n\t\tif(factor < 0.5){\n\t\t\t// left\n\t\tif(children == 0 || children == 2){\n\t\t\t\treturn depth;\n\t\t\t}\n\t\t}else{\n\t\t\t// right\n\t\t\tpos = pos - size * splitv * 0.5;\n\t\t\tif(children == 0 || children == 1){\n\t\t\t\treturn depth;\n\t\t\t}\n\t\t\tif(children == 3){\n\t\t\t\tiOffset = iOffset + 1.0;\n\t\t\t}\n\t\t}\n\t\tsize = size * ((1.0 - (splitv + 1.0) / 2.0) + 0.5);\n\t\t\n\t\tdepth++;\n\t}\n\t\t\n\t\t\n\treturn depth;\t\n}\n\nfloat getPointSizeAttenuation(){\n\treturn 0.5 * pow(1.3, getLOD());\n}\n\n#endif\n\n\n\n// \n// ### ######## ######## ######## #### ######## ## ## ######## ######## ###### \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ######## ## ######## ## ## ## ###### ###### \n// ######### ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## \n// ## ## ## ## ## ## #### ######## ####### ## ######## ###### \n// \n\n\n\n// formula adapted from: http://www.dfstudios.co.uk/articles/programming/image-programming-algorithms/image-processing-algorithms-part-5-contrast-adjustment/\nfloat getContrastFactor(float contrast){\n\treturn (1.0158730158730156 * (contrast + 1.0)) / (1.0158730158730156 - contrast);\n}\n\nvec3 getRGB(){\n\tvec3 rgb = color;\n\t\n\trgb = pow(rgb, vec3(uRGB_gbc.x));\n\trgb = rgb + uRGB_gbc.y;\n\trgb = (rgb - 0.5) * getContrastFactor(uRGB_gbc.z) + 0.5;\n\trgb = clamp(rgb, 0.0, 1.0);\n\n\treturn rgb;\n}\n\nfloat getIntensity(){\n\tfloat w = (intensity - intensityRange.x) / (intensityRange.y - intensityRange.x);\n\tw = pow(w, uIntensity_gbc.x);\n\tw = w + uIntensity_gbc.y;\n\tw = (w - 0.5) * getContrastFactor(uIntensity_gbc.z) + 0.5;\n\tw = clamp(w, 0.0, 1.0);\n\n\treturn w;\n}\n\nvec3 getGpsTime(){\n\n\tfloat w = (gpsTime + uGpsOffset) * uGpsScale;\n\n\n\tvec3 c = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n\n\n\t// vec2 r = uNormalizedGpsBufferRange;\n\t// float w = gpsTime * (r.y - r.x) + r.x;\n\t// w = clamp(w, 0.0, 1.0);\n\t// vec3 c = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t\n\treturn c;\n}\n\nvec3 getElevation(vec4 world){ \n\tfloat w = (world.z - elevationRange.x) / (elevationRange.y - elevationRange.x);\n\tvec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\treturn cElevation;\n}\n\nvec4 getClassification(){\n\tvec2 uv = vec2(classification / 255.0, 0.5);\n\tvec4 classColor = texture2D(classificationLUT, uv);\n\t\n\treturn classColor;\n}\n\nvec3 getReturns(){\n\n\t// 0b 00_000_111\n\tfloat rn = mod(returnNumber, 8.0);\n\t// 0b 00_111_000\n\tfloat nr = mod(returnNumber / 8.0, 8.0);\n\n\tif(nr <= 1.0){\n\t\treturn vec3(1.0, 0.0, 0.0);\n\t}else{\n\t\treturn vec3(0.0, 1.0, 0.0);\n\t}\n\n\t// return vec3(nr / 4.0, 0.0, 0.0);\n\n\t// if(nr == 1.0){\n\t// \treturn vec3(1.0, 1.0, 0.0);\n\t// }else{\n\t// \tif(rn == 1.0){\n\t// \t\treturn vec3(1.0, 0.0, 0.0);\n\t// \t}else if(rn == nr){\n\t// \t\treturn vec3(0.0, 0.0, 1.0);\n\t// \t}else{\n\t// \t\treturn vec3(0.0, 1.0, 0.0);\n\t// \t}\n\t// }\n\n\t// if(numberOfReturns == 1.0){\n\t// \treturn vec3(1.0, 1.0, 0.0);\n\t// }else{\n\t// \tif(returnNumber == 1.0){\n\t// \t\treturn vec3(1.0, 0.0, 0.0);\n\t// \t}else if(returnNumber == numberOfReturns){\n\t// \t\treturn vec3(0.0, 0.0, 1.0);\n\t// \t}else{\n\t// \t\treturn vec3(0.0, 1.0, 0.0);\n\t// \t}\n\t// }\n}\n\nvec3 getReturnNumber(){\n\tif(numberOfReturns == 1.0){\n\t\treturn vec3(1.0, 1.0, 0.0);\n\t}else{\n\t\tif(returnNumber == 1.0){\n\t\t\treturn vec3(1.0, 0.0, 0.0);\n\t\t}else if(returnNumber == numberOfReturns){\n\t\t\treturn vec3(0.0, 0.0, 1.0);\n\t\t}else{\n\t\t\treturn vec3(0.0, 1.0, 0.0);\n\t\t}\n\t}\n}\n\nvec3 getNumberOfReturns(){\n\tfloat value = numberOfReturns;\n\n\tfloat w = value / 6.0;\n\n\tvec3 color = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n\n\treturn color;\n}\n\nvec3 getSourceID(){\n\tfloat w = mod(pointSourceID, 10.0) / 10.0;\n\treturn texture2D(gradient, vec2(w,1.0 - w)).rgb;\n}\n\nvec3 getCompositeColor(vec4 world){\n\tvec3 c;\n\tfloat w;\n\n\tc += wRGB * getRGB();\n\tw += wRGB;\n\t\n\tc += wIntensity * getIntensity() * vec3(1.0, 1.0, 1.0);\n\tw += wIntensity;\n\t\n\tc += wElevation * getElevation(world);\n\tw += wElevation;\n\t\n\tc += wReturnNumber * getReturnNumber();\n\tw += wReturnNumber;\n\t\n\tc += wSourceID * getSourceID();\n\tw += wSourceID;\n\t\n\tvec4 cl = wClassification * getClassification();\n\tc += cl.a * cl.rgb;\n\tw += wClassification * cl.a;\n\n\tc = c / w;\n\t\n\tif(w == 0.0){\n\t\t//c = color;\n\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t}\n\t\n\treturn c;\n}\n\n\nvec3 getNormal(){\n\t//vec3 n_hsv = vec3( modelMatrix * vec4( normal, 0.0 )) * 0.5 + 0.5; // (n_world.xyz + vec3(1.,1.,1.)) / 2.;\n\tvec3 n_view = normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );\n\treturn n_view;\n}\nbool applyBackfaceCulling() {\n\t// Black not facing vertices / Backface culling\n \n\tvec3 e = normalize(vec3(modelViewMatrix * vec4( position, 1. )));\n\tvec3 n = getNormal(); // normalize( vec3(modelViewMatrix * vec4( normal, 0.0 )) );\n\n\tif((uUseOrthographicCamera && n.z <= 0.) || (!uUseOrthographicCamera && dot( n, e ) >= 0.)) { \n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}\n\n#if defined(color_type_matcap)\n// Matcap Material\nvec3 getMatcap(){ \n\tvec3 eye = normalize( vec3( modelViewMatrix * vec4( position, 1. ) ) ); \n\tif(uUseOrthographicCamera) { \n\t\teye = vec3(0., 0., -1.);\n\t}\n\tvec3 r_en = reflect( eye, getNormal() ); // or r_en = e - 2. * dot( n, e ) * n;\n\tfloat m = 2. * sqrt(pow( r_en.x, 2. ) + pow( r_en.y, 2. ) + pow( r_en.z + 1., 2. ));\n\tvec2 vN = r_en.xy / m + .5;\n\treturn texture2D(matcapTextureUniform, vN).rgb; \n}\n#endif\n\nvec3 getExtra(){\n\n\tfloat w = (aExtra + uExtraOffset) * uExtraScale;\n\tw = clamp(w, 0.0, 1.0);\n\n\tvec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n\t// vec2 r = uExtraNormalizedRange;\n\n\t// float w = aExtra * (r.y - r.x) + r.x;\n\n\t// w = (w - uExtraRange.x) / (uExtraRange.y - uExtraRange.x);\n\n\t// w = clamp(w, 0.0, 1.0);\n\n\t// vec3 color = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n\treturn color;\n}\n\nvec3 getColor(vec4 world){\n\tvec3 color;\n\t\n\t#ifdef color_type_rgba\n\t\tcolor = getRGB();\n \n \n\t#elif defined color_type_height || defined color_type_elevation\n\t\tcolor = getElevation(world);\n\t#elif defined color_type_rgb_height\n\t\tvec3 cHeight = getElevation();\n\t\tcolor = (1.0 - uTransition) * getRGB() + uTransition * cHeight;\n\t#elif defined color_type_depth\n\t\tfloat linearDepth = gl_Position.w;\n\t\tfloat expDepth = (gl_Position.z / gl_Position.w) * 0.5 + 0.5;\n\t\tcolor = vec3(linearDepth, expDepth, 0.0);\n\t\t//color = vec3(1.0, 0.5, 0.3);\n\t#elif defined color_type_intensity\n\t\tfloat w = getIntensity();\n\t\tcolor = vec3(w, w, w);\n\t#elif defined color_type_gps_time\n\t\tcolor = getGpsTime();\n\t#elif defined color_type_intensity_gradient\n\t\tfloat w = getIntensity();\n\t\tcolor = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t#elif defined color_type_color\n\t\tcolor = uColor;\n\t#elif defined color_type_level_of_detail\n\t\tfloat depth = getLOD();\n\t\tfloat w = depth / 10.0;\n\t\tcolor = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\t#elif defined color_type_indices\n\t\tcolor = indices.rgb;\n\t#elif defined color_type_classification\n\t\tvec4 cl = getClassification(); \n\t\tcolor = cl.rgb;\n\t#elif defined color_type_return_number\n\t\tcolor = getReturnNumber();\n\t#elif defined color_type_returns\n\t\tcolor = getReturns();\n\t#elif defined color_type_number_of_returns\n\t\tcolor = getNumberOfReturns();\n\t#elif defined color_type_source_id\n\t\tcolor = getSourceID();\n\t#elif defined color_type_point_source_id\n\t\tcolor = getSourceID();\n\t#elif defined color_type_normal\n\t\tcolor = (modelMatrix * vec4(normal, 0.0)).xyz;\n\t#elif defined color_type_phong\n\t\tcolor = color;\n\t#elif defined color_type_composite\n\t\tcolor = getCompositeColor(world);\n\t#elif defined color_type_matcap\n\t\tcolor = getMatcap();\n\t#elif defined color_type_heightCpt //add\n color = vec3(0.0,0.0,0.0);\n #else\n\t\tcolor = getExtra();\n\t#endif\n\t\n\tif (backfaceCulling && applyBackfaceCulling()){\n //color = vec3(0.);\n }\n //applyBackfaceCulling\u76F4\u63A5\u8FD4\u56DEfalse\u6216\u8005\u6CE8\u91CAcolor = vec3(0.);\u90FD\u6CA1\u95EE\u9898\n\treturn color;\n}\n\nfloat getPointSize(){\n\tfloat pointSize = 1.0;\n\tfloat maxSize_ = maxSize;\n\tfloat slope = tan(fov / 2.0);\n\tfloat projFactor = -0.5 * resolution.y / (slope * vViewPosition.z);\n \n \n \n /*\n\tfloat scale = length(\n\t\tmodelViewMatrix * vec4(0, 0, 0, 1) - \n\t\tmodelViewMatrix * vec4(uOctreeSpacing, 0, 0, 1)\n\t) / uOctreeSpacing;\n \n\tprojFactor = projFactor * scale;\n\t*/\n \n \n\tfloat r = uOctreeSpacing * 1.7;\n\t//vRadius = r;\n \n \n\t#if defined fixed_point_size\n\t\tpointSize = size;\n\t#elif defined attenuated_point_size\n\t\tif(uUseOrthographicCamera){ \n pointSize = size / uOrthoWidth * resolution.x; //\u6539\u6210\u8FD1\u4F3Cadaptive_point_size\u6839\u636E\u7A97\u53E3\u7F29\u653E\u3002\u5176\u5B9E\u5C31\u662Fsize * zoom (size\u5355\u4F4D\u8F6C\u5316\u4E3A\u7C73\uFF0C\u5982size\u4E3A1\u4EE3\u8868\u4E00\u4E2A\u70B9\u4E91\u5728\u573A\u666F\u4E2D1\u7C73\u5BBD,zoom\u4EE3\u88681px=1/zoom\u7C73)\n maxSize_ = orthoMaxSize; //for panoEditor, when zoom in, need more details, rather than always same size\n\n\t\t}else{ //\u8FD1\u5927\u8FDC\u5C0F\uFF0C\u6A21\u62DF\u771F\u5B9Emesh\uFF0C\u8FB9\u7F18\u653E\u5927\n\t\t\t//pointSize = size * spacing * projFactor; //spacing\u662Fattribute \u4E3A\u7A7A \u5982\u679C\u6709\u8FD9\u4E2A\u503C\u5C31\u80FD\u66F4\u81EA\u9002\u5E94\u586B\u8865\n //pointSize = size * uOctreeSpacing * projFactor / 18.0; //\u76F4\u63A5\u7528cloud\u7684spacing\u91CC\uFF0C\u4E0D\u8FC7\u56E0\u4E3A\u90FD\u4E00\u6837\u6240\u4EE5\u53EF\u80FD\u6CA1\u6709\u4EC0\u4E48\u610F\u4E49\n\t\t\t//pointSize = pointSize * projFactor;\n pointSize = size * projFactor ;\n\t\t}\n \n\t#elif defined adaptive_point_size\n\t\tif(uUseOrthographicCamera) {\n\t\t\tfloat worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = (worldSpaceSize / uOrthoWidth) * resolution.x; //uScreenWidth;\n maxSize_ = orthoMaxSize;\n\t\t} else {\n\t\t\tfloat worldSpaceSize = 1.0 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = worldSpaceSize * projFactor;\n\t\t}\n \n\t#endif\n\n\tpointSize = max(minSize, pointSize);\n\tpointSize = min(maxSize_, pointSize);\n\t\n\tvRadius = pointSize / projFactor;\n\n\treturn pointSize;\n} \n\n\nbool insideBox(mat4 clipBox, vec4 worldPos){//add\n vec4 clipPosition = clipBox * worldPos;\n bool inside = -0.5 <= clipPosition.x && clipPosition.x <= 0.5;\n inside = inside && -0.5 <= clipPosition.y && clipPosition.y <= 0.5;\n inside = inside && -0.5 <= clipPosition.z && clipPosition.z <= 0.5;\n\n return inside;\n}\n\n\n\n#if defined(color_type_heightCpt)\n vec3 percentToByte(float num){\n //\u8F93\u51FA\u662F0-1\uFF0C shader\u7CBE\u5EA6\u4E0D\u591F\uFF0C\u53EA\u591F\u5B583\u4E2A\u6570\n float a = 1.0;\n float result[4];\n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a / 256.0 ; \n //\u5206\u6210256\u4EFD\uFF0C\u5176\u4E2D255\u4EFD\u7ED9\u5F53\u524D\u4F4D\u7F6E\uFF0C\u6700\u540E\u4E00\u4EFD\u7ED9\u540E\u4E00\u4E2A\u4F4D\u7F6E\uFF0C\u800C\u5230\u4E86\u6700\u540E\u4E00\u4E2A\u4F4D\u7F6E\u65F6\u6CA1\u6709\u4E0B\u4E00\u4E2A\u4F4D\u7F6E\u4E86\u6240\u4EE5\u53EA\u5206\u6210255\u4EFD\n if(num > a){\n float c = num / a;\n float r = floor(c);\n r = min(255.0, r);\n result[i] = r;\n num -= r * a;\n }else{\n result[i] = 0.0;\n }\n } \n return vec3(result[0]/255.0, result[1]/255.0,result[2]/255.0); \n \n //\u9664\u4EE5\u591A\u5C11255\u8FD8\u662F256? \u53C2\u8003uPCIndex / 255.0 \u5E94\u8BE5\u662F255\n } \n#endif\n\n \n\n#if defined(num_prism) && num_prism > 0\n \n \n int insidePrism(mat3 prismInfo, int pointIndexStart, vec4 worldPos){//\u662F\u5426\u5728\u68F1\u67F1\u91CC \n \n float zMin = prismInfo[0][0];\n float zMid = prismInfo[0][1];\n float zMax = prismInfo[0][2]; \n float xMin = prismInfo[1][0];\n float xMax = prismInfo[1][1];\n float yMin = prismInfo[1][2];\n float yMax = prismInfo[2][0]; \n\n int pointCount = int(Round(prismInfo[2][1]));\n \n if( worldPos.x < xMin || worldPos.x > xMax || worldPos.y < yMin || worldPos.y > yMax)return 0;\n #ifndef showBaseHeight\n if( worldPos.z < zMin || worldPos.z > zMax) return 0;\n #endif\n \n \n bool inside = false;\n \n int j=pointCount-1;\n \n for(int i=0; i<prism_maxPointsCount; i++){\n if(i>=pointCount)break;\n float xi = prismPoints[i+pointIndexStart].x, yi = prismPoints[i+pointIndexStart].y, xj = prismPoints[j+pointIndexStart].x, yj = prismPoints[j+pointIndexStart].y;\n\n if(((yi > worldPos.y) != (yj > worldPos.y)) && (worldPos.x < (xj - xi) * (worldPos.y - yi) / (yj - yi) + xi)){\n inside = !inside;\n }\n j=i; \n }\n \n if(inside){\n #ifdef showBaseHeight\n return 1;\n #else \n #ifdef color_type_heightCpt \n vColor = percentToByte((worldPos.z - zMin) / (zMax - zMin)); \n #endif \n #endif\n \n return worldPos.z < zMid ? 1 : 2;\n }else return 0; \n } \n \n#endif\n\n#ifdef showBaseHeight\n float byteToFloat(vec3 color){ \n float percent = 0.0;\n float a = 1.0; \n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a/256.0; \n percent += a * color[i] ;\n }\n return percent * 255.0 ; \n } \n \n#endif\n\n\n \n\n\nvoid doClipping(vec4 world){\n\n\t{\n\t\tvec4 cl = getClassification(); \n\t\tif(cl.a == 0.0){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\n\t#if defined(clip_return_number_enabled)\n\t{ // return number filter\n\t\tvec2 range = uFilterReturnNumberRange;\n\t\tif(returnNumber < range.x || returnNumber > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_number_of_returns_enabled)\n\t{ // number of return filter\n\t\tvec2 range = uFilterNumberOfReturnsRange;\n\t\tif(numberOfReturns < range.x || numberOfReturns > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_gps_enabled)\n\t{ // GPS time filter\n\t\tfloat time = (gpsTime + uGpsOffset) * uGpsScale;\n\t\tvec2 range = uFilterGPSTimeClipRange;\n\n\t\tif(time < range.x || time > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t#if defined(clip_point_source_id_enabled)\n\t{ // point source id filter\n\t\tvec2 range = uFilterPointSourceIDClipRange;\n\t\tif(pointSourceID < range.x || pointSourceID > range.y){\n\t\t\tgl_Position = vec4(100.0, 100.0, 100.0, 0.0);\n\t\t\t\n\t\t\treturn;\n\t\t}\n\t}\n\t#endif\n\n\t \n\n\n //\u603B\u5171\u4E09\u79CDbox : \u6700\u5916\u5C42\u53EF\u89C1\u3001\u5185\u5C42\u53EF\u89C1\u548C\u4E0D\u53EF\u89C1(\u5916\u5C42\u53EF\u89C1\u548C\u5185\u5C42\u53EF\u89C1\u662F\u4EA4\u96C6\uFF0C\u5185\u5C42\u53EF\u89C1\u548C\u5185\u5C42\u4E0D\u53EF\u89C1\u662F\u5E76\u96C6)\n \n #if defined(bigClipInBox) \n if(!insideBox(clipBoxBig_in, world)){ \n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;;\n } \n #endif \n \n #if defined(num_in_clipboxes) && num_in_clipboxes > 0\n //\u5F53\u6709\u53EF\u89C1box\u65F6\uFF0C\u9700\u8981\u5728\u4EFB\u4E00\u53EF\u89C1box\u5185\u624D\u53EF\u89C1\n bool visi1 = false;\n\t\tfor(int i = 0; i < num_in_clipboxes; i++){ \n if(insideBox(clipBoxes_in[i], world)){\n visi1 = true;\n break;\n } \n\t\t}\n if(!visi1){\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;\n }\n\t#endif\n\n\n #if defined(num_out_clipboxes) && num_out_clipboxes > 0\n //\u5F53\u6709\u4E0D\u53EF\u89C1box\u65F6\uFF0C\u4E0D\u5728\u6240\u6709\u4E0D\u53EF\u89C1box\u5185\u624D\u53EF\u89C1\n bool visi2 = true;\n\t\tfor(int i = 0; i < num_out_clipboxes; i++){ \n if(insideBox(clipBoxes_out[i], world)){\n visi2 = false;\n break;\n } \n\t\t}\n if(!visi2){\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0);\n return;\n }\n\t#endif \n \n \n #if defined(num_highlightBox) && num_highlightBox > 0\n //\u5F53\u6709\u9AD8\u4EAEbox\u65F6\uFF0C\u9700\u8981\u5728\u4EFB\u4E00\u53EF\u89C1\u9AD8\u4EAE\u5185\u90FD\u9AD8\u5BBD\n bool highlight = false;\n\t\tfor(int i = 0; i < num_highlightBox; i++){ \n if(insideBox(boxes_highlight[i], world)){\n highlight = true;\n break;\n } \n\t\t}\n if(highlight){\n vColor.r += 0.5; \n }\n\t#endif\n \n \n \n int highlight_ = 0; \n \n #if defined(num_prism) && num_prism > 0 \n //\u57FA\u4E8Eprism\u68F1\u67F1\u7684\u571F\u65B9\u91CF\u663E\u793A\u6216\u8BA1\u7B97\n \n int pointIndexStart = 0;\n\t\tfor(int i = 0; i < num_prism; i++){ \n highlight_ = insidePrism(prismList[i], pointIndexStart, world);\n \n if(highlight_>0){ \n #if !defined(showBaseHeight) && !defined(color_type_heightCpt)\n if(highlight_ == 1){\n vColor.r += 0.5; \n }else if(highlight_ == 2){\n vColor.g += 0.5;\n }\n #endif\n \n break;\n }\n \n \n pointIndexStart += int(Round(prismList[i][2][1])); \n\t\t} \n \n #ifdef color_type_heightCpt \n if(highlight_==0){ \n gl_Position = vec4(100.0, 100.0, 100.0, 1.0); //unvisible\n return;\n }\n #endif \n \n\t#endif\n \n \n \n \n #ifdef showBaseHeight\n //\u57FA\u4E8E\u6A21\u578B\u7684\u571F\u65B9\u91CF\u663E\u793A\u6216\u8BA1\u7B97\n bool outsidePrism = false;\n #if defined(num_prism) && num_prism > 0//\u9AD8\u4EAE\u4EA4\u96C6\n if( highlight_ == 0 ){\n outsidePrism = true;\n }\n #endif \n \n if(!outsidePrism){\n \n float zMin = baseHeightBoundZ.x; \n float zMax = baseHeightBoundZ.y; \n float xMin = baseHeightBoundXY.x;\n float xMax = baseHeightBoundXY.y;\n float yMin = baseHeightBoundXY.z;\n float yMax = baseHeightBoundXY.w; \n \n bool inside = false;\n if(world.z < zMin || world.z > zMax || world.x < xMin || world.x > xMax || world.y < yMin || world.y > yMax){\n inside = false;\n }else{\n vec2 uv = vec2((world.x - xMin) / (xMax - xMin), (world.y - yMin) / (yMax - yMin) );\n \n vec4 color = texture2D(baseHeightAreaMap,uv);\n //\u6297\u952F\u9F7F\u5F85\u5199\n \n \n if(color.a==1.0){ \n \n float currentHeight = (world.z - zMin) / (zMax - zMin) ; \n \n #ifdef color_type_heightCpt\n /*float diff = currentHeight - baseHeight;\n if(diff<0.0){\n diff = -diff;\n vOpacity = 0.5;//\u9700\u8981\u900F\u660E\u901A\u9053\uFF0C\u5BB9\u6613\u51FA\u9519\n }else{\n vOpacity = 1.0;\n }\n vColor = percentToByte(diff); \n */ \n vColor = percentToByte(currentHeight);\n //vColor = color.rgb;\n vOpacity = 1.0;\n \n #else\n //vColor = color.rgb;\n float baseHeight = byteToFloat(color.rgb);\n if(currentHeight > baseHeight){\n vColor.g += 0.5; \n }else{\n vColor.r += 0.5; \n }\n #endif\n \n inside = true;\n }else{\n inside = false;\n }\n \n \n \n } \n \n if(inside == false){\n #ifdef color_type_heightCpt\n gl_Position = vec4(100.0, 100.0, 100.0, 1.0); //unvisible\n return;\n #endif\n }\n \n }\n\t#endif\n}\n\n\n\n// \n// ## ## ### #### ## ## \n// ### ### ## ## ## ### ## \n// #### #### ## ## ## #### ## \n// ## ### ## ## ## ## ## ## ## \n// ## ## ######### ## ## #### \n// ## ## ## ## ## ## ### \n// ## ## ## ## #### ## ## \n//\n\n\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \n\nvec3 transformAxis( vec3 direction ) //navvis->4dkk\n{\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n}\n\nvoid main() {\n //bool filtered_by_normal = false; \n float normalZ = 0.0;\n\n\n\n #ifdef use_filter_by_normal\n /*if(abs(getNormal().z) > 0.4) { //ufilterByNormalThreshold \u6682\u5B9A 3\n\t\t\t// Move point outside clip space space to discard it.\n\t\t\t//gl_Position = vec4(0.0, 0.0, 2.0, 1.0); //gl_Position\u7684\u53EF\u89C6\u533A\u57DF\u662F x,y,z\u90FD\u662F[-1,1] \n //return;\n //filtered_by_normal = true; //\u6807\u8BB0\u4E00\u4E0B\u3002\u4E0D\u76F4\u63A5\u4E0D\u7ED8\u5236\uFF0C\u56E0\u4E3A\u6709\u7684\u6CD5\u7EBF\u90FD\u662F\u5782\u76F4\u5411\u4E0A\n \n\t\t}*/\n \n normalZ = abs(getNormal().z);\n #endif\n \n \n vec4 worldPos = modelMatrix * vec4(position, 1.0); \n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0 ); //vec4 mvPosition = viewMatrix * worldPos;\n vViewPosition = mvPosition.xyz;\n gl_Position = projectionMatrix * mvPosition;\n vLogDepth = log2(-mvPosition.z);\n \n \n \n // COLOR\n //\u52A0-------------------\n #if defined(usePanoMap)\n \n vec3 positionLocalToPanoCenter0 = worldPos.xyz - pano0Position;\n vec3 vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz; \n vWorldPosition0.x *= -1.0;\n vWorldPosition0 = transformAxis(vWorldPosition0);\n \n vec3 positionLocalToPanoCenter1 = worldPos.xyz - pano1Position;\n vec3 vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz; \n vWorldPosition1.x *= -1.0;\n vWorldPosition1 = transformAxis(vWorldPosition1);\n \n /*\n vec2 samplerCoord0 = getSamplerCoord(vWorldPosition0.xyz);\n vec2 samplerCoord1 = getSamplerCoord(vWorldPosition1.xyz); \n vec4 colorFromPano0 = texture2D(pano0Map,samplerCoord0);\n vec4 colorFromPano1 = texture2D(pano1Map,samplerCoord1);\n */\n \n \n \n \n vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);\n\n vColor = mix(colorFromPano0,colorFromPano1,progress).xyz; \n\n \n //float easeInOutRatio = 0.0; //\u7F13\u51B2\uFF0C\u6E10\u53D8\u70B9\u4E91\u5230\u8D34\u56FE\u7684\u989C\u8272 \n if(progress < easeInOutRatio){\n float easeProgress = (easeInOutRatio - progress) / easeInOutRatio;\n vec3 vColor1 = getColor(worldPos);\n vColor = mix(vColor,vColor1,easeProgress); \n }else if(progress > 1.0 - easeInOutRatio){ \n float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio;\n vec3 vColor1 = getColor(worldPos);\n vColor = mix(vColor,vColor1,easeProgress); \n }\n \n\n #else\n \n vColor = getColor(worldPos);\n \n #endif\n \n \n //------------------- \n \n if(uOpacity>=1.0 || uUseOrthographicCamera){ \n vOpacity = uOpacity; \n \n \n if(uOpacity<1.0){ //uUseOrthographicCamera \n //\u9632\u6B62\u7F29\u5C0F\u540E\u70B9\u4E91\u51E0\u4E4E\u770B\u4E0D\u89C1 \n vOpacity *= 4.0-3.0 * levelPercent; \n \n }\n \n }else{ //#ifdef attenuated_opacity zoom\u4E0D\u4F1A\u6539\u53D8z \u6240\u4EE5\u8FD9\u5E76\u4E0D\u662F\u7528\u5728\u5206\u5C4F\u65F6\u5019\u7684\n float v = -gl_Position.z-1.0 ; // \u8303\u56F4\u4ECE-2\u52300\uFF0C e\u7684-2\u52300\u6B21\u65B9\u7684\u8303\u56F4\u662F0.818\u52301 \n //vOpacity = uOpacity * exp(v/ (levelPercent * 20.0 ) ); \n \n //\u8FD1\u5904\u52A0\u6DF1\uFF0C\u8FDC\u5904\u53D8\u6DE1 gl_Position.z\u4F3C\u4E4E\u671D\u5411\u5C4F\u5E55\u91CC\u4E3A\u6B63\n float r = clamp( pow(1.1, v/10.0 ), 0.1, 1.0 ); //\u9664\u4EE5\u7684\u6570\u5B57\u8D8A\u5927\uFF0C\u8FD1\u9AD8\u8FDC\u4F4E\u7684\u7A0B\u5EA6\u8D8A\u5C0F\uFF0C\u8303\u56F4\u8D8A\u957F\u3002 \u7A0B\u5EA6\u592A\u9AD8\u8FDC\u5904\u5355\u8584\u7684\u533A\u57DF\u770B\u4E0D\u89C1 pow\u7684\u5E95\u6570\u8D8A\u5927\u6539\u53D8\u7387\u8D8A\u5927\n vOpacity = uOpacity * r ;\n \n \n } \n \n vOpacity *= max(0.3, pow((1.0 - normalZ),5.0));//\u5782\u76F4\u671D\u76F8\u673A\u65F6\u964D\u4F4E\u900F\u660E\u5EA6 \n //vOpacity = clamp(vOpacity, 0.0, 1.0); \n\n\n\n // POINT SIZE\n float pointSize = getPointSize();\n \n gl_PointSize = pointSize;\n vPointSize = pointSize;\n\n \n \n \n \n\n // only for \"replacing\" approaches\n // if(getLOD() != uLevel){\n // \tgl_Position = vec4(10.0, 10.0, 10.0, 1.0);\n // }\n\n\n #if defined hq_depth_pass\n float originalDepth = gl_Position.w;\n float adjustedDepth = originalDepth + 2.0 * vRadius;\n float adjust = adjustedDepth / originalDepth;\n\n mvPosition.xyz = mvPosition.xyz * adjust;\n gl_Position = projectionMatrix * mvPosition;\n #endif\n\n\n // CLIPPING\n doClipping(worldPos);\n\n #if defined(num_clipspheres) && num_clipspheres > 0\n for(int i = 0; i < num_clipspheres; i++){\n vec4 sphereLocal = uClipSpheres[i] * mvPosition;\n\n float distance = length(sphereLocal.xyz);\n\n if(distance < 1.0){\n float w = distance;\n vec3 cGradient = texture2D(gradient, vec2(w, 1.0 - w)).rgb;\n \n vColor = cGradient;\n //vColor = cGradient * 0.7 + vColor * 0.3;\n }\n }\n #endif\n\n #if defined(num_shadowmaps) && num_shadowmaps > 0\n\n const float sm_near = 0.1;\n const float sm_far = 10000.0;\n\n for(int i = 0; i < num_shadowmaps; i++){\n vec3 viewPos = (uShadowWorldView[i] * vec4(position, 1.0)).xyz;\n float distanceToLight = abs(viewPos.z);\n \n vec4 projPos = uShadowProj[i] * uShadowWorldView[i] * vec4(position, 1);\n vec3 nc = projPos.xyz / projPos.w;\n \n float u = nc.x * 0.5 + 0.5;\n float v = nc.y * 0.5 + 0.5;\n\n vec2 sampleStep = vec2(1.0 / (2.0*1024.0), 1.0 / (2.0*1024.0)) * 1.5;\n vec2 sampleLocations[9];\n sampleLocations[0] = vec2(0.0, 0.0);\n sampleLocations[1] = sampleStep;\n sampleLocations[2] = -sampleStep;\n sampleLocations[3] = vec2(sampleStep.x, -sampleStep.y);\n sampleLocations[4] = vec2(-sampleStep.x, sampleStep.y);\n\n sampleLocations[5] = vec2(0.0, sampleStep.y);\n sampleLocations[6] = vec2(0.0, -sampleStep.y);\n sampleLocations[7] = vec2(sampleStep.x, 0.0);\n sampleLocations[8] = vec2(-sampleStep.x, 0.0);\n\n float visibleSamples = 0.0;\n float numSamples = 0.0;\n\n float bias = vRadius * 2.0;\n\n for(int j = 0; j < 9; j++){\n vec4 depthMapValue = texture2D(uShadowMap[i], vec2(u, v) + sampleLocations[j]);\n\n float linearDepthFromSM = depthMapValue.x + bias;\n float linearDepthFromViewer = distanceToLight;\n\n if(linearDepthFromSM > linearDepthFromViewer){\n visibleSamples += 1.0;\n }\n\n numSamples += 1.0;\n }\n\n float visibility = visibleSamples / numSamples;\n\n if(u < 0.0 || u > 1.0 || v < 0.0 || v > 1.0 || nc.x < -1.0 || nc.x > 1.0 || nc.y < -1.0 || nc.y > 1.0 || nc.z < -1.0 || nc.z > 1.0){\n //vColor = vec3(0.0, 0.0, 0.2);\n }else{\n //vColor = vec3(1.0, 1.0, 1.0) * visibility + vec3(1.0, 1.0, 1.0) * vec3(0.5, 0.0, 0.0) * (1.0 - visibility);\n vColor = vColor * visibility + vColor * uShadowColor * (1.0 - visibility);\n }\n\n\n }\n\n #endif\n\n \n \n}\n";
  13222. Shaders["pointcloud_new.fs"] = "\n#if defined paraboloid_point_shape\n\t#extension GL_EXT_frag_depth : enable\n#endif\n#define PI 3.141592653589793\n\n\n\nprecision highp float;\nprecision highp int;\n\n/*\n#if defined(usePanoMap) \n \n uniform samplerCube pano0Map; //\u968F\u4FBF\u8BBE\u7F6E\u4E00\u4E2AsamplerCube\u53BB\u4F7F\u7528\u90FD\u4F1A\u8BA9\u70B9\u4E91\u6D88\u5931\n uniform samplerCube pano1Map;\n \n uniform float progress;\n uniform float easeInOutRatio;\n\n \n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix; \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix;\n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n\n#endif \n*/\n\n\n\n//------------\n\n\n\n\n\nuniform mat4 viewMatrix;\nuniform mat4 uViewInv;\nuniform mat4 uProjInv;\nuniform vec3 cameraPosition;\n\n\nuniform mat4 projectionMatrix;\n//uniform float uOpacity;\nvarying float vOpacity; //add\n\nuniform float blendHardness;\nuniform float blendDepthSupplement;\nuniform float fov;\nuniform float uSpacing;\nuniform float near;\nuniform float far;\nuniform float uPCIndex;\nuniform float uScreenWidth;\nuniform float uScreenHeight;\n\nvarying vec3\tvColor;\nvarying float\tvLogDepth;\nvarying vec3\tvViewPosition;\nvarying float\tvRadius;\nvarying float \tvPointSize;\nvarying vec3 \tvPosition;\n\n\nfloat specularStrength = 1.0;\n\n\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \n\n\n\n\nvoid main() {\n\n vec3 color = vColor; \n\t \n \n /*#if defined(usePanoMap) //\u52A0 \u7ECF\u6D4B\u8BD5\uFF0C\u5373\u4F7F\u5168\u90E8\u5199\u5728fragment\u91CC\u4E5F\u662F\u65E0\u8BBApointsize\u591A\u5927\u90FD\u662F\u4E00\u4E2A\u70B9\u4E00\u4E2A\u989C\u8272\uFF0C\u6240\u4EE5\u5E72\u8106\u5199\u5728vectex\u91CC\n \n \n vec4 colorFromPano0=textureCube(pano0Map,vWorldPosition0.xyz);\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1.xyz);\n \n color = mix(colorFromPano0,colorFromPano1,progress).xyz; \n \n \n //float easeInOutRatio = 0.0; //\u7F13\u51B2\uFF0C\u6E10\u53D8\u70B9\u4E91\u5230\u8D34\u56FE\u7684\u989C\u8272 \n if(progress < easeInOutRatio){\n float easeProgress = (easeInOutRatio - progress) / easeInOutRatio; \n color = mix(color,vColor,easeProgress); \n }else if(progress > 1.0 - easeInOutRatio){ \n float easeProgress = (progress - (1.0 - easeInOutRatio) ) / easeInOutRatio; \n color = mix(color,vColor,easeProgress); \n }\n \n \n #else \n color = vColor;\n #endif*/\n \n \n \n\tfloat depth = gl_FragCoord.z;\n\n\t#if defined(circle_point_shape) || defined(paraboloid_point_shape) \n\t\tfloat u = 2.0 * gl_PointCoord.x - 1.0;\n\t\tfloat v = 2.0 * gl_PointCoord.y - 1.0;\n\t#endif\n\t\n\t#if defined(circle_point_shape) \n\t\tfloat cc = u*u + v*v;\n\t\tif(cc > 1.0){\n\t\t\tdiscard;\n\t\t}\n\t#endif\n\t\n\n \n\n\t\n \n #if defined color_type_indices //pick point recognize\n\t\tgl_FragColor = vec4(color, uPCIndex / 255.0); //uPCIndex : node Index\n\t#else\n\t\tgl_FragColor = vec4(color, vOpacity);\n\t#endif\n \n \n \n \n \n \n \n \n\n\t#if defined paraboloid_point_shape\n\t\tfloat wi = 0.0 - ( u*u + v*v);\n\t\tvec4 pos = vec4(vViewPosition, 1.0);\n\t\tpos.z += wi * vRadius;\n\t\tfloat linearDepth = -pos.z;\n\t\tpos = projectionMatrix * pos;\n\t\tpos = pos / pos.w;\n\t\tfloat expDepth = pos.z;\n\t\tdepth = (pos.z + 1.0) / 2.0;\n\t\tgl_FragDepthEXT = depth;\n\t\tgl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //add\n \n \n\t\t#if defined(color_type_depth)\n\t\t\tcolor.r = linearDepth;\n\t\t\tcolor.g = expDepth;\n\t\t#endif\n\t\t\n\t\t#if defined(use_edl)\n\t\t\tgl_FragColor.a = log2(linearDepth);\n\t\t#endif\n\t\t\n\t#else\n\t\t#if defined(use_edl)\n\t\t\tgl_FragColor.a = vLogDepth;\n\t\t#endif\n\t#endif\n\n\t#if defined(weighted_splats)\n\t\tfloat distance = 2.0 * length(gl_PointCoord.xy - 0.5);\n\t\tfloat weight = max(0.0, 1.0 - distance);\n\t\tweight = pow(weight, 1.5);\n\n\t\tgl_FragColor.a = weight;\n\t\tgl_FragColor.xyz = gl_FragColor.xyz * weight;\n\t#endif\n\n\t//gl_FragColor = vec4(0.0, 0.7, 0.0, 1.0);\n\t\n}\n\n\n";
  13223. Shaders["pointcloud_sm.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec3 color;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\n\nuniform float uScreenWidth;\nuniform float uScreenHeight;\nuniform float near;\nuniform float far;\n\nuniform float uSpacing;\nuniform float uOctreeSize;\nuniform float uLevel;\nuniform float uVNStart;\n\nuniform sampler2D visibleNodes;\n\nvarying float vLinearDepth;\nvarying vec3 vColor;\n\n#define PI 3.141592653589793\n\n\n\n// ---------------------\n// OCTREE\n// ---------------------\n\n#if defined(adaptive_point_size)\n/**\n * number of 1-bits up to inclusive index position\n * number is treated as if it were an integer in the range 0-255\n *\n */\nfloat numberOfOnes(float number, float index){\n\tfloat tmp = mod(number, pow(2.0, index + 1.0));\n\tfloat numOnes = 0.0;\n\tfor(float i = 0.0; i < 8.0; i++){\n\t\tif(mod(tmp, 2.0) != 0.0){\n\t\t\tnumOnes++;\n\t\t}\n\t\ttmp = floor(tmp / 2.0);\n\t}\n\treturn numOnes;\n}\n\n\n/**\n * checks whether the bit at index is 1\n * number is treated as if it were an integer in the range 0-255\n *\n */\nbool isBitSet(float number, float index){\n\treturn mod(floor(number / pow(2.0, index)), 2.0) != 0.0;\n}\n\n\n/**\n * find the LOD at the point position\n */\nfloat getLOD(){\n\t\n\tvec3 offset = vec3(0.0, 0.0, 0.0);\n\tfloat iOffset = uVNStart;\n\tfloat depth = uLevel;\n\tfor(float i = 0.0; i <= 30.0; i++){\n\t\tfloat nodeSizeAtLevel = uOctreeSize / pow(2.0, i + uLevel + 0.0);\n\t\t\n\t\tvec3 index3d = (position-offset) / nodeSizeAtLevel;\n\t\tindex3d = floor(index3d + 0.5);\n\t\tfloat index = 4.0 * index3d.x + 2.0 * index3d.y + index3d.z;\n\t\t\n\t\tvec4 value = texture2D(visibleNodes, vec2(iOffset / 2048.0, 0.0));\n\t\tfloat mask = value.r * 255.0;\n\t\tif(isBitSet(mask, index)){\n\t\t\t// there are more visible child nodes at this position\n\t\t\tiOffset = iOffset + value.g * 255.0 * 256.0 + value.b * 255.0 + numberOfOnes(mask, index - 1.0);\n\t\t\tdepth++;\n\t\t}else{\n\t\t\t// no more visible child nodes at this position\n\t\t\treturn depth;\n\t\t}\n\t\t\n\t\toffset = offset + (vec3(1.0, 1.0, 1.0) * nodeSizeAtLevel * 0.5) * index3d;\n\t}\n\t\t\n\treturn depth;\n}\n\n#endif\n\nfloat getPointSize(){\n\tfloat pointSize = 1.0;\n\t\n\tfloat slope = tan(fov / 2.0);\n\tfloat projFactor = -0.5 * uScreenHeight / (slope * vViewPosition.z);\n\t\n\tfloat r = uOctreeSpacing * 1.5;\n\tvRadius = r;\n\t#if defined fixed_point_size\n\t\tpointSize = size;\n\t#elif defined attenuated_point_size\n\t\tif(uUseOrthographicCamera){\n\t\t\tpointSize = size;\t\t\t\n\t\t}else{\n\t\t\tpointSize = pointSize * projFactor;\n\t\t}\n\t#elif defined adaptive_point_size\n\t\tif(uUseOrthographicCamera) {\n\t\t\tfloat worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = (worldSpaceSize / uOrthoWidth) * uScreenWidth;\n\t\t} else {\n\t\t\tfloat worldSpaceSize = 1.5 * size * r / getPointSizeAttenuation();\n\t\t\tpointSize = worldSpaceSize * projFactor;\n\t\t}\n\t#endif\n\n\tpointSize = max(minSize, pointSize);\n\tpointSize = min(maxSize, pointSize);\n\t\n\tvRadius = pointSize / projFactor;\n\n\treturn pointSize;\n}\n\n\nvoid main() {\n\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tvLinearDepth = gl_Position.w;\n\n\tfloat pointSize = getPointSize();\n\tgl_PointSize = pointSize;\n\n}\n";
  13224. Shaders["pointcloud_sm.fs"] = "\nprecision mediump float;\nprecision mediump int;\n\nvarying vec3 vColor;\nvarying float vLinearDepth;\n\nvoid main() {\n\n\t//gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n\t//gl_FragColor = vec4(vColor, 1.0);\n\t//gl_FragColor = vec4(vLinearDepth, pow(vLinearDepth, 2.0), 0.0, 1.0);\n\tgl_FragColor = vec4(vLinearDepth, vLinearDepth / 30.0, vLinearDepth / 30.0, 1.0);\n\t\n}\n\n\n";
  13225. Shaders["normalize.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec2 uv;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelViewMatrix;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);\n}";
  13226. Shaders["normalize.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\nprecision mediump float;\nprecision mediump int;\n\nuniform sampler2D uWeightMap;\nuniform sampler2D uDepthMap;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tfloat depth = texture2D(uDepthMap, vUv).r;\n\t\n\tif(depth >= 1.0){\n\t\tdiscard;\n\t}\n\n\tgl_FragColor = vec4(depth, 1.0, 0.0, 1.0);\n\n\tvec4 color = texture2D(uWeightMap, vUv); \n\tcolor = color / color.w;\n\t\n\tgl_FragColor = vec4(color.xyz, 1.0); \n\t\n\tgl_FragDepthEXT = depth;\n\n\n}";
  13227. Shaders["normalize_and_edl.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\n// \n// adapted from the EDL shader code from Christian Boucheny in cloud compare:\n// https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL\n//\n\nprecision mediump float;\nprecision mediump int;\n\nuniform sampler2D uWeightMap;\nuniform sampler2D uEDLMap;\nuniform sampler2D uDepthMap;\n\nuniform float screenWidth;\nuniform float screenHeight;\nuniform vec2 neighbours[NEIGHBOUR_COUNT];\nuniform float edlStrength;\nuniform float radius;\n\nvarying vec2 vUv;\n\nfloat response(float depth){\n\tvec2 uvRadius = radius / vec2(screenWidth, screenHeight);\n\t\n\tfloat sum = 0.0;\n\t\n\tfor(int i = 0; i < NEIGHBOUR_COUNT; i++){\n\t\tvec2 uvNeighbor = vUv + uvRadius * neighbours[i];\n\t\t\n\t\tfloat neighbourDepth = texture2D(uEDLMap, uvNeighbor).a;\n\n\t\tif(neighbourDepth != 0.0){\n\t\t\tif(depth == 0.0){\n\t\t\t\tsum += 100.0;\n\t\t\t}else{\n\t\t\t\tsum += max(0.0, depth - neighbourDepth);\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn sum / float(NEIGHBOUR_COUNT);\n}\n\nvoid main() {\n\n\tfloat edlDepth = texture2D(uEDLMap, vUv).a;\n\tfloat res = response(edlDepth);\n\tfloat shade = exp(-res * 300.0 * edlStrength);\n\n\tfloat depth = texture2D(uDepthMap, vUv).r;\n\tif(depth >= 1.0 && res == 0.0){\n\t\tdiscard;\n\t}\n\t\n\tvec4 color = texture2D(uWeightMap, vUv); \n\tcolor = color / color.w;\n\tcolor = color * shade;\n\n\tgl_FragColor = vec4(color.xyz, 1.0); \n\n\tgl_FragDepthEXT = depth;\n}";
  13228. Shaders["edl_new.vs"] = "\nprecision mediump float;\nprecision mediump int;\n\nattribute vec3 position;\nattribute vec2 uv;\n\nuniform mat4 projectionMatrix;\nuniform mat4 modelViewMatrix;\n\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\t\n\tvec4 mvPosition = modelViewMatrix * vec4(position,1.0);\n\n\tgl_Position = projectionMatrix * mvPosition;\n}";
  13229. Shaders["edl_new.fs"] = "\n#extension GL_EXT_frag_depth : enable\n\n// \n// adapted from the EDL shader code from Christian Boucheny in cloud compare:\n// https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL\n//\n\nprecision mediump float;\nprecision mediump int;\n\n//uniform float screenWidth;\n//uniform float screenHeight;\nuniform vec2 resolution;\n\n\nuniform vec2 neighbours[NEIGHBOUR_COUNT];\nuniform float edlStrength;\nuniform float radius;\nuniform float opacity;\n\n//uniform float uNear;\n//uniform float uFar;\n\nuniform mat4 uProj;\n\nuniform sampler2D uEDLColor;\nuniform sampler2D uEDLDepth;\n\nvarying vec2 vUv;\n\nuniform int useEDL;\n\nfloat response(float depth){\n\tvec2 uvRadius = radius / resolution; //vec2(screenWidth, screenHeight);\n\t\n\tfloat sum = 0.0;\n\t\n\tfor(int i = 0; i < NEIGHBOUR_COUNT; i++){\n\t\tvec2 uvNeighbor = vUv + uvRadius * neighbours[i];\n\t\t//\u83B7\u53D6\u5468\u56F4\u516B\u4E2A\u683C\u5B50\u7684\u503C\n\t\tfloat neighbourDepth = texture2D(uEDLColor, uvNeighbor).a;\n\t\tneighbourDepth = (neighbourDepth == 1.0) ? 0.0 : neighbourDepth;\n\n\t\tif(neighbourDepth != 0.0){\n\t\t\t //if(depth == 0.0){\n\t\t\t //\tsum += 100.0;\n\t\t\t //}else{\n\t\t\t\tsum += max(0.0, depth - neighbourDepth); //\u83B7\u53D6\u5DEE\u503C\n\t\t\t //}\n\t\t}\n\t}\n\t\n\treturn sum / float(NEIGHBOUR_COUNT);\n}\n\nvoid main(){\n\tvec4 cEDL = texture2D(uEDLColor, vUv);\n\t\n\tfloat depth = cEDL.a;\n\tdepth = (depth == 1.0) ? 0.0 : depth;\n \n if(depth == 0.0){ //\u53BB\u6389\u8FD9\u53E5\u5C31\u80FD\u5728\u65E0\u70B9\u4E91\u50CF\u7D20\u7684\u5730\u65B9\u6E32\u67D3outline\uFF0C\u4F46\u4F1A\u906E\u4F4F\u5176\u4ED6mesh\n\t\tdiscard;\n\t}\n \n \n if(useEDL == 1){\n float res = response(depth); \n float shade = exp(-res * 300.0 * edlStrength); //\u81EA\u7136\u5E38\u6570e\u4E3A\u5E95\u7684\u6307\u6570\u51FD\u6570 \n const float min = 0.2; //add \u4F7F\u8FB9\u7F18\u8272\u53D8\u6D45 \u8303\u56F4\u4ECE0-1 \u53D8\u4E3Amin-1\n shade = shade * (1.0-min) + min;\n gl_FragColor = vec4(cEDL.rgb * shade, opacity); \n }else{//\u52A0 \u4E0D\u6539\u989C\u8272\u7684\u60C5\u51B5 \n gl_FragColor = vec4(cEDL.rgb, opacity);\n } \n //\u6CE8\u610F\uFF0CedlStrength\u8D8A\u5F3A\uFF0C\u5728\u76F8\u540Cdepth\u7684\u53E0\u653E\u7684\u70B9\u4E91\u95F4\u7684\u8F6E\u5ED3\u7EBF\u989C\u8272\u8D8A\u6DF1\n //\u4F5C\u7528\uFF1A\u52FE\u52D2\u8FB9\u7F18\uFF0C\u5F3A\u5316\u6DF1\u5EA6\u5DEE\u5F02\uFF0C\u6A21\u62DF\u9634\u5F71\uFF0C\u52A0\u5F3A\u7ED3\u6784\u7ACB\u4F53\u611F\n \n { // write regular hyperbolic depth values to depth buffer \u4FEE\u6539\u6DF1\u5EA6\n float dl = pow(2.0, depth);\n\n vec4 dp = uProj * vec4(0.0, 0.0, -dl, 1.0);\n float pz = dp.z / dp.w;\n float fragDepth = (pz + 1.0) / 2.0;\n\n gl_FragDepthEXT = fragDepth;\n }\n\t\n}\n";
  13230. Shaders["blur.vs"] = "\nvarying vec2 vUv;\n\nvoid main() {\n\tvUv = uv;\n\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);\n}";
  13231. Shaders["blur.fs"] = "\nuniform mat4 projectionMatrix;\n\nuniform float screenWidth;\nuniform float screenHeight;\nuniform float near;\nuniform float far;\n\nuniform sampler2D map;\n\nvarying vec2 vUv;\n\nvoid main() {\n\n\tfloat dx = 1.0 / screenWidth;\n\tfloat dy = 1.0 / screenHeight;\n\n\tvec3 color = vec3(0.0, 0.0, 0.0);\n\tcolor += texture2D(map, vUv + vec2(-dx, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, -dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(-dx, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, 0)).rgb;\n\tcolor += texture2D(map, vUv + vec2(-dx, dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2( 0, dy)).rgb;\n\tcolor += texture2D(map, vUv + vec2(+dx, dy)).rgb;\n\n\tcolor = color / 9.0;\n\t\n\tgl_FragColor = vec4(color, 1.0);\n}";
  13232. Shaders["depthBasic.vs"] = "\n \n\nvarying vec2 vUv;\nvoid main() {\n \n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n ";
  13233. Shaders["depthBasic.fs"] = "varying vec2 vUv;\nuniform float opacity;\nuniform float mapScale;\nuniform vec3 baseColor;\n\n#if defined use_map\n uniform sampler2D map; \n \n vec4 getMapColor(vec4 color){ \n if(mapScale == 1.0){\n color = texture2D(map, vUv) * color; \n return color;\n }else{ \n vec2 uv = (vUv - 0.5) / mapScale + 0.5; \n if(uv.x > 1.0 || uv.y > 1.0 || uv.x < 0.0 || uv.y < 0.0){\n //color = vec4(0.0,0.0,0.0,0.0);\n discard;\n }else{\n color = texture2D(map, uv) * color; \n }\n return color; \n }\n }\n#endif\n \n\n #if defined(GL_EXT_frag_depth) && defined(useDepth)\n //\u4F3C\u4E4E\u901A\u8FC7gl.getExtension('EXT_frag_depth')\u5F97\u5230\u7684GL_EXT_frag_depth\n \n uniform sampler2D depthTexture;\n uniform float nearPlane;\n uniform float farPlane; \n uniform vec2 resolution;\n uniform vec2 viewportOffset; // viewportOffset \u8303\u56F4\u4ECE0-\u6574\u4E2A\u753B\u5E03\u7684\u50CF\u7D20\n uniform vec3 backColor;\n uniform float occlusionDistance;\n uniform float clipDistance;\n uniform float maxClipFactor;\n uniform float maxOcclusionFactor;\n //uniform bool uUseOrthographicCamera; \n\n float convertToLinear(float zValue)\n {\n //if(uUseOrthographicCamera){\n // return zValue*(farPlane-nearPlane)+nearPlane;\n //}else{ \n float z = zValue * 2.0 - 1.0;\n return (2.0 * nearPlane * farPlane) / (farPlane + nearPlane - z * (farPlane - nearPlane));\n //} \n }\n#endif\n \n \n \nvoid main() {\n \n \n vec4 color = vec4(baseColor, opacity);\n \n \n \n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n // mixFactor and clipFactor define the color mixing proportion between the states of\n // full visibility and occluded visibility\n // and\n // full visibility and total invisibility\n \n float mixFactor = 0.0;\n float clipFactor = 0.0;\n \n \n // The linear depth value of the current fragment\n float fragDepth = convertToLinear(gl_FragCoord.z);\n\n // The coordinates of the current fragment in the depth texture\n vec2 depthTxtCoords = vec2(gl_FragCoord.x-viewportOffset.x, gl_FragCoord.y - viewportOffset.y) / resolution;\n //gl_FragCoord\u5927\u5C0F\u4E3A viewport client\u5927\u5C0F \n \n // The linear depth value of the pixel occupied by this fragment in the depth buffer\n float textureDepth = convertToLinear(texture2D(depthTexture, depthTxtCoords).r);\n\n // The difference between the two depths\n float delta = fragDepth - textureDepth;\n\n if (delta > 0.0)//\u5DEE\u8DDD\n {\n // occlusionDistance and clipDistance define the width of the respective zones and\n // mixFactor and clipFactor express the interpolation between the two colors depending on the position\n // of the current fragment withing those zones.\n \n \n mixFactor = clamp(delta / occlusionDistance, 0.0, maxOcclusionFactor);\n clipFactor = clamp(delta / clipDistance, 0.0, maxClipFactor);\n }\n \n // If the fragment is totally transparent, don't bother drawing it\n if (clipFactor == 1.0)\n {\n discard;\n }else{\n \n #if defined use_map\n color = getMapColor(color); \n #endif\n \n \n color = vec4(mix(color.rgb, backColor, mixFactor), color.a * (1.0 - clipFactor));\n }\n \n #else\n #if defined use_map\n color = getMapColor(color); \n #endif \n #endif\n \n gl_FragColor = color;\n \n}\n";
  13234. Shaders["copyCubeMap.vs"] = "varying vec3 vWorldPos;\nvec3 transformAxis( vec3 direction ) //navvis->4dkk\n{\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n}\nvoid main() {\n vWorldPos = vec3(-position.x, -position.y, position.z);\n //vWorldPos = transformAxis(vWorldPos);\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n ";
  13235. Shaders["copyCubeMap.fs"] = "varying vec3 vWorldPos;\nuniform float alpha;\nuniform samplerCube tDiffuse;\n\n\nvoid main() {\n vec4 texColor = textureCube(tDiffuse, vWorldPos);\n gl_FragColor = vec4(texColor.rgb, texColor.a * alpha);\n} \n ";
  13236. Shaders["basicTextured.vs"] = "varying vec2 vUv;\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n} \n ";
  13237. Shaders["basicTextured.fs"] = "varying vec2 vUv;\nuniform float opacity;\n \n\n#ifdef HasMap\n uniform sampler2D map; \n#endif\n#ifdef HasColor\n uniform vec3 color;\n#endif\n\nvoid main() {\n vec4 color_;\n #ifdef HasColor\n color_ = vec4(color, opacity); \n #else\n color_ = vec4(1.0,1.0,1.0, opacity);\n #endif\n \n #ifdef HasMap\n vec4 texColor = texture2D(map, vUv); \n gl_FragColor = texColor * color_;\n #else\n gl_FragColor = color_;\n #endif\n \n \n}\n";
  13238. Shaders["skybox.vs"] = "uniform mat4 matrix; \nvarying vec3 vWorldPosition;\n\n\n\nvoid main() \n{ \n \n vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz ; // - cameraPosition; \n vWorldPosition = (vec4(vWorldPosition, 1.0) * matrix).xyz;\n vWorldPosition.x *= -1.0;\n\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  13239. Shaders["skybox.fs"] = "varying vec3 vWorldPosition;\nuniform sampler2D tDiffuse; \n\n#define PI 3.141592653 \n\n/*vec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;\n float ty=acos(direction.y)/PI;\n\n return vec2(tx,ty);\n}*/\nvec2 getSamplerCoord( vec3 direction ) \n{\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n} \nvoid main() \n{\n vec2 samplerCoord = getSamplerCoord(vWorldPosition);\n vec4 color = texture2D(tDiffuse, samplerCoord);\n //gl_FragColor = RGBEToLinear( color ); //\u5BF9\u4E8Ehdr\u5FC5\u987B\u52A0\u8FD9\u4E00\u53E5\uFF0C\u5426\u5219\u6548\u679C\u5F88\u5947\u602A\u3002copy\u81EAmeshBasicMaterial\u91CC\u7684mat_fragment\u7684mapTexelToLinear\u51FD\u6570\uFF0C\u53EA\u8981\u6709map\u5C31\u4F1A\u4F7F\u7528\u8BE5\u51FD\u6570\n gl_FragColor = color;\n //#include <tonemapping_fragment>\n //////#include <encodings_fragment>\n\n} \n";
  13240. var ClassificationScheme = {
  13241. DEFAULT: {
  13242. 0: {
  13243. visible: true,
  13244. name: 'never classified',
  13245. color: [0.5, 0.5, 0.5, 1.0]
  13246. },
  13247. 1: {
  13248. visible: true,
  13249. name: 'unclassified',
  13250. color: [0.5, 0.5, 0.5, 1.0]
  13251. },
  13252. 2: {
  13253. visible: true,
  13254. name: 'ground',
  13255. color: [0.63, 0.32, 0.18, 1.0]
  13256. },
  13257. 3: {
  13258. visible: true,
  13259. name: 'low vegetation',
  13260. color: [0.0, 1.0, 0.0, 1.0]
  13261. },
  13262. 4: {
  13263. visible: true,
  13264. name: 'medium vegetation',
  13265. color: [0.0, 0.8, 0.0, 1.0]
  13266. },
  13267. 5: {
  13268. visible: true,
  13269. name: 'high vegetation',
  13270. color: [0.0, 0.6, 0.0, 1.0]
  13271. },
  13272. 6: {
  13273. visible: true,
  13274. name: 'building',
  13275. color: [1.0, 0.66, 0.0, 1.0]
  13276. },
  13277. 7: {
  13278. visible: true,
  13279. name: 'low point(noise)',
  13280. color: [1.0, 0.0, 1.0, 1.0]
  13281. },
  13282. 8: {
  13283. visible: true,
  13284. name: 'key-point',
  13285. color: [1.0, 0.0, 0.0, 1.0]
  13286. },
  13287. 9: {
  13288. visible: true,
  13289. name: 'water',
  13290. color: [0.0, 0.0, 1.0, 1.0]
  13291. },
  13292. 12: {
  13293. visible: true,
  13294. name: 'overlap',
  13295. color: [1.0, 1.0, 0.0, 1.0]
  13296. },
  13297. DEFAULT: {
  13298. visible: true,
  13299. name: 'default',
  13300. color: [0.3, 0.6, 0.6, 0.5]
  13301. }
  13302. }
  13303. };
  13304. Object.defineProperty(ClassificationScheme, 'RANDOM', {
  13305. get: function get() {
  13306. var scheme = {};
  13307. for (var i = 0; i <= 255; i++) {
  13308. scheme[i] = new Vector4(Math.random(), Math.random(), Math.random());
  13309. }
  13310. scheme["DEFAULT"] = new Vector4(Math.random(), Math.random(), Math.random());
  13311. return scheme;
  13312. }
  13313. });
  13314. class EnumItem {
  13315. constructor(object) {
  13316. for (var key of Object.keys(object)) {
  13317. this[key] = object[key];
  13318. }
  13319. }
  13320. inspect() {
  13321. return "Enum(".concat(this.name, ": ").concat(this.value, ")");
  13322. }
  13323. }
  13324. ;
  13325. class Enum {
  13326. constructor(object) {
  13327. this.object = object;
  13328. for (var key of Object.keys(object)) {
  13329. var value = object[key];
  13330. if (typeof value === "object") {
  13331. value.name = key;
  13332. } else {
  13333. value = {
  13334. name: key,
  13335. value: value
  13336. };
  13337. }
  13338. this[key] = new EnumItem(value);
  13339. }
  13340. }
  13341. fromValue(value) {
  13342. for (var key of Object.keys(this.object)) {
  13343. if (this[key].value === value) {
  13344. return this[key];
  13345. }
  13346. }
  13347. throw new Error("No enum for value: ".concat(value));
  13348. }
  13349. }
  13350. ;
  13351. var CameraMode = {
  13352. ORTHOGRAPHIC: 0,
  13353. PERSPECTIVE: 1,
  13354. VR: 2
  13355. };
  13356. var ClipTask = {
  13357. NONE: 0,
  13358. HIGHLIGHT: 1,
  13359. SHOW_INSIDE: 2,
  13360. SHOW_OUTSIDE: 3
  13361. };
  13362. var ClipMethod = {
  13363. INSIDE_ANY: 0,
  13364. INSIDE_ALL: 1
  13365. };
  13366. var ElevationGradientRepeat = {
  13367. CLAMP: 0,
  13368. REPEAT: 1,
  13369. MIRRORED_REPEAT: 2
  13370. };
  13371. var MOUSE$1 = {
  13372. LEFT: 0b0001,
  13373. RIGHT: 0b0010,
  13374. MIDDLE: 0b0100
  13375. };
  13376. var PointSizeType = {
  13377. FIXED: 0,
  13378. ATTENUATED: 1,
  13379. ADAPTIVE: 2
  13380. };
  13381. var PointShape$1 = {
  13382. SQUARE: 0,
  13383. CIRCLE: 1,
  13384. PARABOLOID: 2
  13385. };
  13386. var TreeType = {
  13387. OCTREE: 0,
  13388. KDTREE: 1
  13389. };
  13390. var LengthUnits = {
  13391. METER: {
  13392. code: 'm',
  13393. unitspermeter: 1.0
  13394. },
  13395. FEET: {
  13396. code: 'ft',
  13397. unitspermeter: 3.28084
  13398. },
  13399. INCH: {
  13400. code: '\u2033',
  13401. unitspermeter: 39.3701
  13402. }
  13403. };
  13404. //
  13405. // how to calculate the radius of a projected sphere in screen space
  13406. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  13407. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  13408. //
  13409. class PointCloudMaterial$1 extends RawShaderMaterial {
  13410. //base
  13411. constructor() {
  13412. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  13413. super();
  13414. this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new Color(0xffffff));
  13415. this.visibleNodesTexture.minFilter = NearestFilter;
  13416. this.visibleNodesTexture.magFilter = NearestFilter;
  13417. var getValid = (a, b) => {
  13418. if (a !== undefined) {
  13419. return a;
  13420. } else {
  13421. return b;
  13422. }
  13423. };
  13424. var pointSize = getValid(parameters.size, 1.0);
  13425. var minSize = getValid(parameters.minSize, 2.0);
  13426. var maxSize = getValid(parameters.maxSize, 50.0);
  13427. var treeType = getValid(parameters.treeType, TreeType.OCTREE);
  13428. this._pointSizeType = PointSizeType.FIXED;
  13429. this._shape = PointShape$1.SQUARE;
  13430. this._useClipBox = false;
  13431. this.clipBoxes = [];
  13432. this.clipPolygons = [];
  13433. this._weighted = false;
  13434. this._gradient = Gradients.SPECTRAL;
  13435. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  13436. //this._matcap = "matcap.jpg";
  13437. //this.matcapTexture = PointCloudMaterial.generateMatcapTexture(this._matcap);
  13438. this.lights = false;
  13439. this.fog = false;
  13440. this._treeType = treeType;
  13441. this._useEDL = false;
  13442. this.defines = new Map();
  13443. this.ranges = new Map();
  13444. this._activeAttributeName = null;
  13445. this._defaultIntensityRangeChanged = false;
  13446. this._defaultElevationRangeChanged = false;
  13447. {
  13448. var [width, height] = [256, 1];
  13449. var data = new Uint8Array(width * 4);
  13450. var texture = new DataTexture(data, width, height, RGBAFormat);
  13451. texture.magFilter = NearestFilter;
  13452. texture.needsUpdate = true;
  13453. this.classificationTexture = texture;
  13454. }
  13455. this.attributes = {
  13456. position: {
  13457. type: 'fv',
  13458. value: []
  13459. },
  13460. color: {
  13461. type: 'fv',
  13462. value: []
  13463. },
  13464. normal: {
  13465. type: 'fv',
  13466. value: []
  13467. },
  13468. intensity: {
  13469. type: 'f',
  13470. value: []
  13471. },
  13472. classification: {
  13473. type: 'f',
  13474. value: []
  13475. },
  13476. returnNumber: {
  13477. type: 'f',
  13478. value: []
  13479. },
  13480. numberOfReturns: {
  13481. type: 'f',
  13482. value: []
  13483. },
  13484. pointSourceID: {
  13485. type: 'f',
  13486. value: []
  13487. },
  13488. indices: {
  13489. type: 'fv',
  13490. value: []
  13491. }
  13492. };
  13493. this.uniforms = {
  13494. level: {
  13495. type: "f",
  13496. value: 0.0
  13497. },
  13498. vnStart: {
  13499. type: "f",
  13500. value: 0.0
  13501. },
  13502. spacing: {
  13503. type: "f",
  13504. value: 1.0
  13505. },
  13506. blendHardness: {
  13507. type: "f",
  13508. value: 2.0
  13509. },
  13510. blendDepthSupplement: {
  13511. type: "f",
  13512. value: 0.0
  13513. },
  13514. fov: {
  13515. type: "f",
  13516. value: 1.0
  13517. },
  13518. screenWidth: {
  13519. type: "f",
  13520. value: 1.0
  13521. },
  13522. screenHeight: {
  13523. type: "f",
  13524. value: 1.0
  13525. },
  13526. near: {
  13527. type: "f",
  13528. value: 0.1
  13529. },
  13530. far: {
  13531. type: "f",
  13532. value: 1.0
  13533. },
  13534. uColor: {
  13535. type: "c",
  13536. value: new Color(0xffffff)
  13537. },
  13538. uOpacity: {
  13539. type: "f",
  13540. value: 1.0
  13541. },
  13542. size: {
  13543. type: "f",
  13544. value: pointSize
  13545. },
  13546. minSize: {
  13547. type: "f",
  13548. value: minSize
  13549. },
  13550. maxSize: {
  13551. type: "f",
  13552. value: maxSize
  13553. },
  13554. octreeSize: {
  13555. type: "f",
  13556. value: 0
  13557. },
  13558. bbSize: {
  13559. type: "fv",
  13560. value: [0, 0, 0]
  13561. },
  13562. elevationRange: {
  13563. type: "2fv",
  13564. value: [0, 0]
  13565. },
  13566. clipBoxCount: {
  13567. type: "f",
  13568. value: 0
  13569. },
  13570. //clipSphereCount: { type: "f", value: 0 },
  13571. clipPolygonCount: {
  13572. type: "i",
  13573. value: 0
  13574. },
  13575. clipBoxes: {
  13576. type: "Matrix4fv",
  13577. value: []
  13578. },
  13579. //clipSpheres: { type: "Matrix4fv", value: [] },
  13580. clipPolygons: {
  13581. type: "3fv",
  13582. value: []
  13583. },
  13584. clipPolygonVCount: {
  13585. type: "iv",
  13586. value: []
  13587. },
  13588. clipPolygonVP: {
  13589. type: "Matrix4fv",
  13590. value: []
  13591. },
  13592. visibleNodes: {
  13593. type: "t",
  13594. value: this.visibleNodesTexture
  13595. },
  13596. pcIndex: {
  13597. type: "f",
  13598. value: 0
  13599. },
  13600. gradient: {
  13601. type: "t",
  13602. value: this.gradientTexture
  13603. },
  13604. classificationLUT: {
  13605. type: "t",
  13606. value: this.classificationTexture
  13607. },
  13608. uHQDepthMap: {
  13609. type: "t",
  13610. value: null
  13611. },
  13612. toModel: {
  13613. type: "Matrix4f",
  13614. value: []
  13615. },
  13616. diffuse: {
  13617. type: "fv",
  13618. value: [1, 1, 1]
  13619. },
  13620. transition: {
  13621. type: "f",
  13622. value: 0.5
  13623. },
  13624. intensityRange: {
  13625. type: "fv",
  13626. value: [Infinity, -Infinity]
  13627. },
  13628. intensity_gbc: {
  13629. type: "fv",
  13630. value: [1, 0, 0]
  13631. },
  13632. uRGB_gbc: {
  13633. type: "fv",
  13634. value: [1, 0, 0]
  13635. },
  13636. // intensityGamma: { type: "f", value: 1 },
  13637. // intensityContrast: { type: "f", value: 0 },
  13638. // intensityBrightness:{ type: "f", value: 0 },
  13639. // rgbGamma: { type: "f", value: 1 },
  13640. // rgbContrast: { type: "f", value: 0 },
  13641. // rgbBrightness: { type: "f", value: 0 },
  13642. wRGB: {
  13643. type: "f",
  13644. value: 1
  13645. },
  13646. wIntensity: {
  13647. type: "f",
  13648. value: 0
  13649. },
  13650. wElevation: {
  13651. type: "f",
  13652. value: 0
  13653. },
  13654. wClassification: {
  13655. type: "f",
  13656. value: 0
  13657. },
  13658. wReturnNumber: {
  13659. type: "f",
  13660. value: 0
  13661. },
  13662. wSourceID: {
  13663. type: "f",
  13664. value: 0
  13665. },
  13666. useOrthographicCamera: {
  13667. type: "b",
  13668. value: false
  13669. },
  13670. elevationGradientRepat: {
  13671. type: "i",
  13672. value: ElevationGradientRepeat.CLAMP
  13673. },
  13674. clipTask: {
  13675. type: "i",
  13676. value: 1
  13677. },
  13678. clipMethod: {
  13679. type: "i",
  13680. value: 1
  13681. },
  13682. uShadowColor: {
  13683. type: "3fv",
  13684. value: [0, 0, 0]
  13685. },
  13686. uExtraScale: {
  13687. type: "f",
  13688. value: 1
  13689. },
  13690. uExtraOffset: {
  13691. type: "f",
  13692. value: 0
  13693. },
  13694. uExtraRange: {
  13695. type: "2fv",
  13696. value: [0, 1]
  13697. },
  13698. uExtraGammaBrightContr: {
  13699. type: "3fv",
  13700. value: [1, 0, 0]
  13701. },
  13702. uFilterReturnNumberRange: {
  13703. type: "fv",
  13704. value: [0, 7]
  13705. },
  13706. uFilterNumberOfReturnsRange: {
  13707. type: "fv",
  13708. value: [0, 7]
  13709. },
  13710. uFilterGPSTimeClipRange: {
  13711. type: "fv",
  13712. value: [0, 7]
  13713. },
  13714. uFilterPointSourceIDClipRange: {
  13715. type: "fv",
  13716. value: [0, 65535]
  13717. },
  13718. //matcapTextureUniform: { type: "t", value: this.matcapTexture },
  13719. backfaceCulling: {
  13720. type: "b",
  13721. value: false
  13722. }
  13723. };
  13724. this.classification = ClassificationScheme.DEFAULT;
  13725. this.defaultAttributeValues.normal = [0, 0, 0];
  13726. this.defaultAttributeValues.classification = [0, 0, 0];
  13727. this.defaultAttributeValues.indices = [0, 0, 0, 0];
  13728. this.vertexShader = Shaders['pointcloud.vs'];
  13729. this.fragmentShader = Shaders['pointcloud.fs'];
  13730. this.vertexColors = VertexColors;
  13731. this.updateShaderSource();
  13732. }
  13733. setDefine(key, value) {
  13734. if (value !== undefined && value !== null) {
  13735. if (this.defines.get(key) !== value) {
  13736. this.defines.set(key, value);
  13737. this.updateShaderSource();
  13738. }
  13739. } else {
  13740. this.removeDefine(key);
  13741. }
  13742. }
  13743. removeDefine(key) {
  13744. this.defines.delete(key);
  13745. }
  13746. updateShaderSource() {
  13747. var vs = Shaders['pointcloud.vs'];
  13748. var fs = Shaders['pointcloud.fs'];
  13749. var definesString = this.getDefines();
  13750. var vsVersionIndex = vs.indexOf("#version ");
  13751. var fsVersionIndex = fs.indexOf("#version ");
  13752. if (vsVersionIndex >= 0) {
  13753. vs = vs.replace(/(#version .*)/, "$1\n".concat(definesString));
  13754. } else {
  13755. vs = "".concat(definesString, "\n").concat(vs);
  13756. }
  13757. if (fsVersionIndex >= 0) {
  13758. fs = fs.replace(/(#version .*)/, "$1\n".concat(definesString));
  13759. } else {
  13760. fs = "".concat(definesString, "\n").concat(fs);
  13761. }
  13762. this.vertexShader = vs;
  13763. this.fragmentShader = fs;
  13764. if (this.opacity === 1.0) {
  13765. this.blending = NoBlending;
  13766. this.transparent = false;
  13767. this.depthTest = true;
  13768. this.depthWrite = true;
  13769. this.depthFunc = LessEqualDepth;
  13770. } else if (this.opacity < 1.0 && !this.useEDL) {
  13771. this.blending = AdditiveBlending;
  13772. this.transparent = true;
  13773. this.depthTest = false;
  13774. this.depthWrite = true;
  13775. this.depthFunc = AlwaysDepth;
  13776. }
  13777. if (this.weighted) {
  13778. this.blending = AdditiveBlending;
  13779. this.transparent = true;
  13780. this.depthTest = true;
  13781. this.depthWrite = false;
  13782. }
  13783. this.needsUpdate = true;
  13784. }
  13785. getDefines() {
  13786. var defines = [];
  13787. if (this.pointSizeType === PointSizeType.FIXED) {
  13788. defines.push('#define fixed_point_size');
  13789. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  13790. defines.push('#define attenuated_point_size');
  13791. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  13792. defines.push('#define adaptive_point_size');
  13793. }
  13794. if (this.shape === PointShape$1.SQUARE) {
  13795. defines.push('#define square_point_shape');
  13796. } else if (this.shape === PointShape$1.CIRCLE) {
  13797. defines.push('#define circle_point_shape');
  13798. } else if (this.shape === PointShape$1.PARABOLOID) {
  13799. defines.push('#define paraboloid_point_shape');
  13800. }
  13801. if (this._useEDL) {
  13802. defines.push('#define use_edl');
  13803. }
  13804. if (this.activeAttributeName) {
  13805. var attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  13806. defines.push("#define color_type_".concat(attributeName));
  13807. }
  13808. if (this._treeType === TreeType.OCTREE) {
  13809. defines.push('#define tree_type_octree');
  13810. } else if (this._treeType === TreeType.KDTREE) {
  13811. defines.push('#define tree_type_kdtree');
  13812. }
  13813. if (this.weighted) {
  13814. defines.push('#define weighted_splats');
  13815. }
  13816. for (var [key, value] of this.defines) {
  13817. defines.push(value);
  13818. }
  13819. return defines.join("\n");
  13820. }
  13821. setClipBoxes(clipBoxes) {
  13822. if (!clipBoxes) {
  13823. return;
  13824. }
  13825. var doUpdate = this.clipBoxes.length !== clipBoxes.length && (clipBoxes.length === 0 || this.clipBoxes.length === 0);
  13826. this.uniforms.clipBoxCount.value = this.clipBoxes.length;
  13827. this.clipBoxes = clipBoxes;
  13828. if (doUpdate) {
  13829. this.updateShaderSource();
  13830. }
  13831. this.uniforms.clipBoxes.value = new Float32Array(this.clipBoxes.length * 16);
  13832. for (var i = 0; i < this.clipBoxes.length; i++) {
  13833. var box = clipBoxes[i];
  13834. this.uniforms.clipBoxes.value.set(box.inverse.elements, 16 * i);
  13835. }
  13836. for (var _i = 0; _i < this.uniforms.clipBoxes.value.length; _i++) {
  13837. if (Number.isNaN(this.uniforms.clipBoxes.value[_i])) {
  13838. this.uniforms.clipBoxes.value[_i] = Infinity;
  13839. }
  13840. }
  13841. }
  13842. setClipPolygons(clipPolygons, maxPolygonVertices) {
  13843. if (!clipPolygons) {
  13844. return;
  13845. }
  13846. this.clipPolygons = clipPolygons;
  13847. var doUpdate = this.clipPolygons.length !== clipPolygons.length;
  13848. if (doUpdate) {
  13849. this.updateShaderSource();
  13850. }
  13851. }
  13852. get gradient() {
  13853. return this._gradient;
  13854. }
  13855. set gradient(value) {
  13856. //海拔贴图
  13857. if (this._gradient !== value) {
  13858. this._gradient = value;
  13859. this.gradientTexture = PointCloudMaterial$1.generateGradientTexture(this._gradient);
  13860. this.uniforms.gradient.value = this.gradientTexture;
  13861. }
  13862. }
  13863. /* get matcap(){
  13864. return this._matcap;
  13865. }
  13866. set matcap (value) {
  13867. if (this._matcap !== value) {
  13868. this._matcap = value;
  13869. this.matcapTexture = Potree.PointCloudMaterial.generateMatcapTexture(this._matcap);
  13870. this.uniforms.matcapTextureUniform.value = this.matcapTexture;
  13871. }
  13872. } */
  13873. get useOrthographicCamera() {
  13874. return this.uniforms.useOrthographicCamera.value;
  13875. }
  13876. set useOrthographicCamera(value) {
  13877. if (this.uniforms.useOrthographicCamera.value !== value) {
  13878. this.uniforms.useOrthographicCamera.value = value;
  13879. }
  13880. }
  13881. get backfaceCulling() {
  13882. return this.uniforms.backfaceCulling.value;
  13883. }
  13884. set backfaceCulling(value) {
  13885. if (this.uniforms.backfaceCulling.value !== value) {
  13886. this.uniforms.backfaceCulling.value = value;
  13887. this.dispatchEvent({
  13888. type: 'backface_changed',
  13889. target: this
  13890. });
  13891. }
  13892. }
  13893. recomputeClassification() {
  13894. var classification = this.classification;
  13895. var data = this.classificationTexture.image.data;
  13896. var width = 256;
  13897. var black = [1, 1, 1, 1];
  13898. var valuesChanged = false;
  13899. for (var i = 0; i < width; i++) {
  13900. var color = void 0;
  13901. var visible = true;
  13902. if (classification[i]) {
  13903. color = classification[i].color;
  13904. visible = classification[i].visible;
  13905. } else if (classification[i % 32]) {
  13906. color = classification[i % 32].color;
  13907. visible = classification[i % 32].visible;
  13908. } else if (classification.DEFAULT) {
  13909. color = classification.DEFAULT.color;
  13910. visible = classification.DEFAULT.visible;
  13911. } else {
  13912. color = black;
  13913. }
  13914. var r = parseInt(255 * color[0]);
  13915. var g = parseInt(255 * color[1]);
  13916. var b = parseInt(255 * color[2]);
  13917. var a = visible ? parseInt(255 * color[3]) : 0;
  13918. if (data[4 * i + 0] !== r) {
  13919. data[4 * i + 0] = r;
  13920. valuesChanged = true;
  13921. }
  13922. if (data[4 * i + 1] !== g) {
  13923. data[4 * i + 1] = g;
  13924. valuesChanged = true;
  13925. }
  13926. if (data[4 * i + 2] !== b) {
  13927. data[4 * i + 2] = b;
  13928. valuesChanged = true;
  13929. }
  13930. if (data[4 * i + 3] !== a) {
  13931. data[4 * i + 3] = a;
  13932. valuesChanged = true;
  13933. }
  13934. }
  13935. if (valuesChanged) {
  13936. this.classificationTexture.needsUpdate = true;
  13937. this.dispatchEvent({
  13938. type: 'material_property_changed',
  13939. target: this
  13940. });
  13941. }
  13942. }
  13943. get spacing() {
  13944. return this.uniforms.spacing.value;
  13945. }
  13946. set spacing(value) {
  13947. if (this.uniforms.spacing.value !== value) {
  13948. // 即 uOctreeSpacing 来自cloud.js里
  13949. this.uniforms.spacing.value = value;
  13950. }
  13951. }
  13952. get useClipBox() {
  13953. return this._useClipBox;
  13954. }
  13955. set useClipBox(value) {
  13956. if (this._useClipBox !== value) {
  13957. this._useClipBox = value;
  13958. this.updateShaderSource();
  13959. }
  13960. }
  13961. get clipTask() {
  13962. return this.uniforms.clipTask.value;
  13963. }
  13964. set clipTask(mode) {
  13965. this.uniforms.clipTask.value = mode;
  13966. }
  13967. get elevationGradientRepat() {
  13968. return this.uniforms.elevationGradientRepat.value;
  13969. }
  13970. set elevationGradientRepat(mode) {
  13971. this.uniforms.elevationGradientRepat.value = mode;
  13972. }
  13973. get clipMethod() {
  13974. return this.uniforms.clipMethod.value;
  13975. }
  13976. set clipMethod(mode) {
  13977. this.uniforms.clipMethod.value = mode;
  13978. }
  13979. get weighted() {
  13980. return this._weighted;
  13981. }
  13982. set weighted(value) {
  13983. if (this._weighted !== value) {
  13984. this._weighted = value;
  13985. this.updateShaderSource();
  13986. }
  13987. }
  13988. get fov() {
  13989. return this.uniforms.fov.value;
  13990. }
  13991. set fov(value) {
  13992. if (this.uniforms.fov.value !== value) {
  13993. this.uniforms.fov.value = value;
  13994. // this.updateShaderSource();
  13995. }
  13996. }
  13997. get screenWidth() {
  13998. return this.uniforms.screenWidth.value;
  13999. }
  14000. set screenWidth(value) {
  14001. if (this.uniforms.screenWidth.value !== value) {
  14002. this.uniforms.screenWidth.value = value;
  14003. // this.updateShaderSource();
  14004. }
  14005. }
  14006. get screenHeight() {
  14007. return this.uniforms.screenHeight.value;
  14008. }
  14009. set screenHeight(value) {
  14010. if (this.uniforms.screenHeight.value !== value) {
  14011. this.uniforms.screenHeight.value = value;
  14012. // this.updateShaderSource();
  14013. }
  14014. }
  14015. get near() {
  14016. return this.uniforms.near.value;
  14017. }
  14018. set near(value) {
  14019. if (this.uniforms.near.value !== value) {
  14020. this.uniforms.near.value = value;
  14021. }
  14022. }
  14023. get far() {
  14024. return this.uniforms.far.value;
  14025. }
  14026. set far(value) {
  14027. if (this.uniforms.far.value !== value) {
  14028. this.uniforms.far.value = value;
  14029. }
  14030. }
  14031. get opacity() {
  14032. return this.uniforms.uOpacity.value;
  14033. }
  14034. set opacity(value) {
  14035. if (this.uniforms && this.uniforms.uOpacity) {
  14036. if (this.uniforms.uOpacity.value !== value) {
  14037. this.uniforms.uOpacity.value = value;
  14038. this.updateShaderSource();
  14039. this.dispatchEvent({
  14040. type: 'opacity_changed',
  14041. target: this
  14042. });
  14043. this.dispatchEvent({
  14044. type: 'material_property_changed',
  14045. target: this
  14046. });
  14047. }
  14048. }
  14049. }
  14050. get activeAttributeName() {
  14051. return this._activeAttributeName;
  14052. }
  14053. set activeAttributeName(value) {
  14054. if (this._activeAttributeName !== value) {
  14055. this._activeAttributeName = value;
  14056. this.updateShaderSource();
  14057. this.dispatchEvent({
  14058. type: 'active_attribute_changed',
  14059. target: this
  14060. });
  14061. this.dispatchEvent({
  14062. type: 'material_property_changed',
  14063. target: this
  14064. });
  14065. }
  14066. }
  14067. get pointSizeType() {
  14068. return this._pointSizeType;
  14069. }
  14070. set pointSizeType(value) {
  14071. if (this._pointSizeType !== value) {
  14072. this._pointSizeType = value;
  14073. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  14074. this.dispatchEvent({
  14075. type: 'point_size_type_changed',
  14076. target: this
  14077. });
  14078. this.dispatchEvent({
  14079. type: 'material_property_changed',
  14080. target: this
  14081. });
  14082. }
  14083. }
  14084. get useEDL() {
  14085. return this._useEDL;
  14086. }
  14087. set useEDL(value) {
  14088. if (this._useEDL !== value) {
  14089. this._useEDL = value;
  14090. this.updateShaderSource();
  14091. }
  14092. }
  14093. get color() {
  14094. return this.uniforms.uColor.value;
  14095. }
  14096. set color(value) {
  14097. if (!this.uniforms.uColor.value.equals(value)) {
  14098. this.uniforms.uColor.value.copy(value);
  14099. this.dispatchEvent({
  14100. type: 'color_changed',
  14101. target: this
  14102. });
  14103. this.dispatchEvent({
  14104. type: 'material_property_changed',
  14105. target: this
  14106. });
  14107. }
  14108. }
  14109. get shape() {
  14110. return this._shape;
  14111. }
  14112. set shape(value) {
  14113. if (this._shape !== value) {
  14114. this._shape = value;
  14115. this.updateShaderSource();
  14116. this.dispatchEvent({
  14117. type: 'point_shape_changed',
  14118. target: this
  14119. });
  14120. this.dispatchEvent({
  14121. type: 'material_property_changed',
  14122. target: this
  14123. });
  14124. }
  14125. }
  14126. get treeType() {
  14127. return this._treeType;
  14128. }
  14129. set treeType(value) {
  14130. if (this._treeType !== value) {
  14131. this._treeType = value;
  14132. this.updateShaderSource();
  14133. }
  14134. }
  14135. get bbSize() {
  14136. return this.uniforms.bbSize.value;
  14137. }
  14138. set bbSize(value) {
  14139. this.uniforms.bbSize.value = value;
  14140. }
  14141. get size() {
  14142. return this.uniforms.size.value;
  14143. }
  14144. set size(value) {
  14145. if (this.uniforms.size.value !== value) {
  14146. this.uniforms.size.value = value;
  14147. this.dispatchEvent({
  14148. type: 'point_size_changed',
  14149. target: this
  14150. });
  14151. this.dispatchEvent({
  14152. type: 'material_property_changed',
  14153. target: this
  14154. });
  14155. }
  14156. }
  14157. get minSize() {
  14158. return this.uniforms.minSize.value;
  14159. }
  14160. set minSize(value) {
  14161. if (this.uniforms.minSize.value !== value) {
  14162. this.uniforms.minSize.value = value;
  14163. this.dispatchEvent({
  14164. type: 'point_size_changed',
  14165. target: this
  14166. });
  14167. this.dispatchEvent({
  14168. type: 'material_property_changed',
  14169. target: this
  14170. });
  14171. }
  14172. }
  14173. get elevationRange() {
  14174. return this.uniforms.elevationRange.value;
  14175. }
  14176. set elevationRange(value) {
  14177. var changed = this.uniforms.elevationRange.value[0] !== value[0] || this.uniforms.elevationRange.value[1] !== value[1];
  14178. if (changed) {
  14179. this.uniforms.elevationRange.value = value;
  14180. this._defaultElevationRangeChanged = true;
  14181. this.dispatchEvent({
  14182. type: 'material_property_changed',
  14183. target: this
  14184. });
  14185. }
  14186. }
  14187. get heightMin() {
  14188. return this.uniforms.elevationRange.value[0];
  14189. }
  14190. set heightMin(value) {
  14191. this.elevationRange = [value, this.elevationRange[1]];
  14192. }
  14193. get heightMax() {
  14194. return this.uniforms.elevationRange.value[1];
  14195. }
  14196. set heightMax(value) {
  14197. this.elevationRange = [this.elevationRange[0], value];
  14198. }
  14199. get transition() {
  14200. return this.uniforms.transition.value;
  14201. }
  14202. set transition(value) {
  14203. this.uniforms.transition.value = value;
  14204. }
  14205. get intensityRange() {
  14206. return this.uniforms.intensityRange.value;
  14207. }
  14208. set intensityRange(value) {
  14209. if (!(value instanceof Array && value.length === 2)) {
  14210. return;
  14211. }
  14212. if (value[0] === this.uniforms.intensityRange.value[0] && value[1] === this.uniforms.intensityRange.value[1]) {
  14213. return;
  14214. }
  14215. this.uniforms.intensityRange.value = value;
  14216. this._defaultIntensityRangeChanged = true;
  14217. this.dispatchEvent({
  14218. type: 'material_property_changed',
  14219. target: this
  14220. });
  14221. }
  14222. get intensityGamma() {
  14223. return this.uniforms.intensity_gbc.value[0];
  14224. }
  14225. set intensityGamma(value) {
  14226. if (this.uniforms.intensity_gbc.value[0] !== value) {
  14227. this.uniforms.intensity_gbc.value[0] = value;
  14228. this.dispatchEvent({
  14229. type: 'material_property_changed',
  14230. target: this
  14231. });
  14232. }
  14233. }
  14234. get intensityContrast() {
  14235. return this.uniforms.intensity_gbc.value[2];
  14236. }
  14237. set intensityContrast(value) {
  14238. if (this.uniforms.intensity_gbc.value[2] !== value) {
  14239. this.uniforms.intensity_gbc.value[2] = value;
  14240. this.dispatchEvent({
  14241. type: 'material_property_changed',
  14242. target: this
  14243. });
  14244. }
  14245. }
  14246. get intensityBrightness() {
  14247. return this.uniforms.intensity_gbc.value[1];
  14248. }
  14249. set intensityBrightness(value) {
  14250. if (this.uniforms.intensity_gbc.value[1] !== value) {
  14251. this.uniforms.intensity_gbc.value[1] = value;
  14252. this.dispatchEvent({
  14253. type: 'material_property_changed',
  14254. target: this
  14255. });
  14256. }
  14257. }
  14258. get rgbGamma() {
  14259. return this.uniforms.uRGB_gbc.value[0];
  14260. }
  14261. set rgbGamma(value) {
  14262. if (this.uniforms.uRGB_gbc.value[0] !== value) {
  14263. this.uniforms.uRGB_gbc.value[0] = value;
  14264. this.dispatchEvent({
  14265. type: 'material_property_changed',
  14266. target: this
  14267. });
  14268. }
  14269. }
  14270. get rgbContrast() {
  14271. return this.uniforms.uRGB_gbc.value[2];
  14272. }
  14273. set rgbContrast(value) {
  14274. if (this.uniforms.uRGB_gbc.value[2] !== value) {
  14275. this.uniforms.uRGB_gbc.value[2] = value;
  14276. this.dispatchEvent({
  14277. type: 'material_property_changed',
  14278. target: this
  14279. });
  14280. }
  14281. }
  14282. get rgbBrightness() {
  14283. return this.uniforms.uRGB_gbc.value[1];
  14284. }
  14285. set rgbBrightness(value) {
  14286. if (this.uniforms.uRGB_gbc.value[1] !== value) {
  14287. this.uniforms.uRGB_gbc.value[1] = value;
  14288. this.dispatchEvent({
  14289. type: 'material_property_changed',
  14290. target: this
  14291. });
  14292. }
  14293. }
  14294. get extraGamma() {
  14295. return this.uniforms.uExtraGammaBrightContr.value[0];
  14296. }
  14297. set extraGamma(value) {
  14298. if (this.uniforms.uExtraGammaBrightContr.value[0] !== value) {
  14299. this.uniforms.uExtraGammaBrightContr.value[0] = value;
  14300. this.dispatchEvent({
  14301. type: 'material_property_changed',
  14302. target: this
  14303. });
  14304. }
  14305. }
  14306. get extraBrightness() {
  14307. return this.uniforms.uExtraGammaBrightContr.value[1];
  14308. }
  14309. set extraBrightness(value) {
  14310. if (this.uniforms.uExtraGammaBrightContr.value[1] !== value) {
  14311. this.uniforms.uExtraGammaBrightContr.value[1] = value;
  14312. this.dispatchEvent({
  14313. type: 'material_property_changed',
  14314. target: this
  14315. });
  14316. }
  14317. }
  14318. get extraContrast() {
  14319. return this.uniforms.uExtraGammaBrightContr.value[2];
  14320. }
  14321. set extraContrast(value) {
  14322. if (this.uniforms.uExtraGammaBrightContr.value[2] !== value) {
  14323. this.uniforms.uExtraGammaBrightContr.value[2] = value;
  14324. this.dispatchEvent({
  14325. type: 'material_property_changed',
  14326. target: this
  14327. });
  14328. }
  14329. }
  14330. getRange(attributeName) {
  14331. return this.ranges.get(attributeName);
  14332. }
  14333. setRange(attributeName, newRange) {
  14334. var rangeChanged = false;
  14335. var oldRange = this.ranges.get(attributeName);
  14336. if (oldRange != null && newRange != null) {
  14337. rangeChanged = oldRange[0] !== newRange[0] || oldRange[1] !== newRange[1];
  14338. } else {
  14339. rangeChanged = true;
  14340. }
  14341. this.ranges.set(attributeName, newRange);
  14342. if (rangeChanged) {
  14343. this.dispatchEvent({
  14344. type: 'material_property_changed',
  14345. target: this
  14346. });
  14347. }
  14348. }
  14349. get extraRange() {
  14350. return this.uniforms.uExtraRange.value;
  14351. }
  14352. set extraRange(value) {
  14353. if (!(value instanceof Array && value.length === 2)) {
  14354. return;
  14355. }
  14356. if (value[0] === this.uniforms.uExtraRange.value[0] && value[1] === this.uniforms.uExtraRange.value[1]) {
  14357. return;
  14358. }
  14359. this.uniforms.uExtraRange.value = value;
  14360. this._defaultExtraRangeChanged = true;
  14361. this.dispatchEvent({
  14362. type: 'material_property_changed',
  14363. target: this
  14364. });
  14365. }
  14366. get weightRGB() {
  14367. return this.uniforms.wRGB.value;
  14368. }
  14369. set weightRGB(value) {
  14370. if (this.uniforms.wRGB.value !== value) {
  14371. this.uniforms.wRGB.value = value;
  14372. this.dispatchEvent({
  14373. type: 'material_property_changed',
  14374. target: this
  14375. });
  14376. }
  14377. }
  14378. get weightIntensity() {
  14379. return this.uniforms.wIntensity.value;
  14380. }
  14381. set weightIntensity(value) {
  14382. if (this.uniforms.wIntensity.value !== value) {
  14383. this.uniforms.wIntensity.value = value;
  14384. this.dispatchEvent({
  14385. type: 'material_property_changed',
  14386. target: this
  14387. });
  14388. }
  14389. }
  14390. get weightElevation() {
  14391. return this.uniforms.wElevation.value;
  14392. }
  14393. set weightElevation(value) {
  14394. if (this.uniforms.wElevation.value !== value) {
  14395. this.uniforms.wElevation.value = value;
  14396. this.dispatchEvent({
  14397. type: 'material_property_changed',
  14398. target: this
  14399. });
  14400. }
  14401. }
  14402. get weightClassification() {
  14403. return this.uniforms.wClassification.value;
  14404. }
  14405. set weightClassification(value) {
  14406. if (this.uniforms.wClassification.value !== value) {
  14407. this.uniforms.wClassification.value = value;
  14408. this.dispatchEvent({
  14409. type: 'material_property_changed',
  14410. target: this
  14411. });
  14412. }
  14413. }
  14414. get weightReturnNumber() {
  14415. return this.uniforms.wReturnNumber.value;
  14416. }
  14417. set weightReturnNumber(value) {
  14418. if (this.uniforms.wReturnNumber.value !== value) {
  14419. this.uniforms.wReturnNumber.value = value;
  14420. this.dispatchEvent({
  14421. type: 'material_property_changed',
  14422. target: this
  14423. });
  14424. }
  14425. }
  14426. get weightSourceID() {
  14427. return this.uniforms.wSourceID.value;
  14428. }
  14429. set weightSourceID(value) {
  14430. if (this.uniforms.wSourceID.value !== value) {
  14431. this.uniforms.wSourceID.value = value;
  14432. this.dispatchEvent({
  14433. type: 'material_property_changed',
  14434. target: this
  14435. });
  14436. }
  14437. }
  14438. static generateGradientTexture(gradient) {
  14439. var size = 64;
  14440. // create canvas
  14441. var canvas = document.createElement('canvas');
  14442. canvas.width = size;
  14443. canvas.height = size;
  14444. // get context
  14445. var context = canvas.getContext('2d');
  14446. // draw gradient
  14447. context.rect(0, 0, size, size);
  14448. var ctxGradient = context.createLinearGradient(0, 0, size, size);
  14449. for (var i = 0; i < gradient.length; i++) {
  14450. var step = gradient[i];
  14451. ctxGradient.addColorStop(step[0], '#' + step[1].getHexString());
  14452. }
  14453. context.fillStyle = ctxGradient;
  14454. context.fill();
  14455. //let texture = new THREE.Texture(canvas);
  14456. var texture = new CanvasTexture(canvas);
  14457. texture.needsUpdate = true;
  14458. texture.minFilter = LinearFilter;
  14459. texture.wrap = RepeatWrapping;
  14460. texture.repeat = 2;
  14461. // textureImage = texture.image;
  14462. return texture;
  14463. }
  14464. static generateMatcapTexture(matcap) {
  14465. var url = new URL(Potree.resourcePath + "/textures/matcap/" + matcap).href;
  14466. var texture = new TextureLoader().load(url);
  14467. texture.magFilter = texture.minFilter = LinearFilter;
  14468. texture.needsUpdate = true;
  14469. // PotreeConverter_1.6_2018_07_29_windows_x64\PotreeConverter.exe autzen_xyzrgbXYZ_ascii.xyz -f xyzrgbXYZ -a RGB NORMAL -o autzen_xyzrgbXYZ_ascii_a -p index --overwrite
  14470. // Switch matcap texture on the fly : viewer.scene.pointclouds[0].material.matcap = 'matcap1.jpg';
  14471. // For non power of 2, use LinearFilter and dont generate mipmaps, For power of 2, use NearestFilter and generate mipmaps : matcap2.jpg 1 2 8 11 12 13
  14472. return texture;
  14473. }
  14474. disableEvents() {
  14475. if (this._hiddenListeners === undefined) {
  14476. this._hiddenListeners = this._listeners;
  14477. this._listeners = {};
  14478. }
  14479. }
  14480. enableEvents() {
  14481. this._listeners = this._hiddenListeners;
  14482. this._hiddenListeners = undefined;
  14483. }
  14484. } // copyFrom(from){
  14485. // var a = 10;
  14486. // for(let name of Object.keys(this.uniforms)){
  14487. // this.uniforms[name].value = from.uniforms[name].value;
  14488. // }
  14489. // }
  14490. // copy(from){
  14491. // this.copyFrom(from);
  14492. // }
  14493. //见ExtendPointCloudOctree
  14494. class PointCloudOctreeNode extends PointCloudTreeNode {
  14495. constructor() {
  14496. super();
  14497. //this.children = {};
  14498. this.children = [];
  14499. this.sceneNode = null;
  14500. this.octree = null;
  14501. }
  14502. getNumPoints() {
  14503. return this.geometryNode.numPoints;
  14504. }
  14505. isLoaded() {
  14506. return true;
  14507. }
  14508. isTreeNode() {
  14509. return true;
  14510. }
  14511. isGeometryNode() {
  14512. return false;
  14513. }
  14514. getLevel() {
  14515. return this.geometryNode.level;
  14516. }
  14517. getBoundingSphere() {
  14518. return this.geometryNode.boundingSphere;
  14519. }
  14520. getBoundingBox() {
  14521. return this.geometryNode.boundingBox;
  14522. }
  14523. getChildren() {
  14524. var children = [];
  14525. for (var i = 0; i < 8; i++) {
  14526. if (this.children[i]) {
  14527. children.push(this.children[i]);
  14528. }
  14529. }
  14530. return children;
  14531. }
  14532. getPointsInBox(boxNode) {
  14533. if (!this.sceneNode) {
  14534. return null;
  14535. }
  14536. var buffer = this.geometryNode.buffer;
  14537. var posOffset = buffer.offset("position");
  14538. var stride = buffer.stride;
  14539. var view = new DataView(buffer.data);
  14540. var worldToBox = boxNode.matrixWorld.clone().invert();
  14541. var objectToBox = new Matrix4().multiplyMatrices(worldToBox, this.sceneNode.matrixWorld);
  14542. var inBox = [];
  14543. var pos = new Vector4();
  14544. for (var i = 0; i < buffer.numElements; i++) {
  14545. var x = view.getFloat32(i * stride + posOffset + 0, true);
  14546. var y = view.getFloat32(i * stride + posOffset + 4, true);
  14547. var z = view.getFloat32(i * stride + posOffset + 8, true);
  14548. pos.set(x, y, z, 1);
  14549. pos.applyMatrix4(objectToBox);
  14550. if (-0.5 < pos.x && pos.x < 0.5) {
  14551. if (-0.5 < pos.y && pos.y < 0.5) {
  14552. if (-0.5 < pos.z && pos.z < 0.5) {
  14553. pos.set(x, y, z, 1).applyMatrix4(this.sceneNode.matrixWorld);
  14554. inBox.push(new Vector3(pos.x, pos.y, pos.z));
  14555. }
  14556. }
  14557. }
  14558. }
  14559. return inBox;
  14560. }
  14561. get name() {
  14562. return this.geometryNode.name;
  14563. }
  14564. }
  14565. ;
  14566. class PointCloudOctree extends PointCloudTree {
  14567. //base
  14568. constructor(geometry, material) {
  14569. var _this2;
  14570. super();
  14571. _this2 = this;
  14572. this.pointBudget = Infinity; //一直是这个值
  14573. this.pcoGeometry = geometry;
  14574. this.boundingBox = this.pcoGeometry.boundingBox;
  14575. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  14576. this.material = material || new PointCloudMaterial$1();
  14577. this.visiblePointsTarget = 2 * 1000 * 1000;
  14578. this.minimumNodePixelSize = 150;
  14579. this.level = 0;
  14580. this.position.copy(geometry.offset);
  14581. this.updateMatrix();
  14582. {
  14583. var priorityQueue = ["rgba", "rgb", "intensity", "classification"];
  14584. var selected = "rgba";
  14585. var _loop = function _loop(attributeName) {
  14586. var attribute = _this2.pcoGeometry.pointAttributes.attributes.find(a => a.name === attributeName);
  14587. if (!attribute) {
  14588. return 0; // continue
  14589. }
  14590. var min = attribute.range[0].constructor.name === "Array" ? attribute.range[0] : [attribute.range[0]];
  14591. var max = attribute.range[1].constructor.name === "Array" ? attribute.range[1] : [attribute.range[1]];
  14592. var range_min = new Vector3(...min);
  14593. var range_max = new Vector3(...max);
  14594. var range = range_min.distanceTo(range_max);
  14595. if (range === 0) {
  14596. return 0; // continue
  14597. }
  14598. selected = attributeName;
  14599. return 1; // break
  14600. },
  14601. _ret;
  14602. for (var attributeName of priorityQueue) {
  14603. _ret = _loop(attributeName);
  14604. if (_ret === 0) continue;
  14605. if (_ret === 1) break;
  14606. }
  14607. this.material.activeAttributeName = selected;
  14608. }
  14609. this.showBoundingBox = false;
  14610. this.boundingBoxNodes = [];
  14611. this.loadQueue = [];
  14612. this.visibleBounds = new Box3();
  14613. this.visibleNodes = [];
  14614. this.visibleGeometry = [];
  14615. this.generateDEM = false;
  14616. this.profileRequests = [];
  14617. this.name = '';
  14618. this._visible = true;
  14619. {
  14620. var box = [this.pcoGeometry.tightBoundingBox, this.getBoundingBoxWorld()].find(v => v !== undefined);
  14621. this.updateMatrixWorld(true);
  14622. box = Utils.computeTransformedBoundingBox(box, this.matrixWorld);
  14623. var bMin = box.min.z;
  14624. var bMax = box.max.z;
  14625. this.material.heightMin = bMin;
  14626. this.material.heightMax = bMax;
  14627. }
  14628. // TODO read projection from file instead
  14629. this.projection = geometry.projection;
  14630. this.fallbackProjection = geometry.fallbackProjection;
  14631. this.root = this.pcoGeometry.root;
  14632. }
  14633. setName(name) {
  14634. if (this.name !== name) {
  14635. this.name = name;
  14636. this.dispatchEvent({
  14637. type: 'name_changed',
  14638. name: name,
  14639. pointcloud: this
  14640. });
  14641. }
  14642. }
  14643. getName() {
  14644. return this.name;
  14645. }
  14646. getAttribute(name) {
  14647. var attribute = this.pcoGeometry.pointAttributes.attributes.find(a => a.name === name);
  14648. if (attribute) {
  14649. return attribute;
  14650. } else {
  14651. return null;
  14652. }
  14653. }
  14654. getAttributes() {
  14655. return this.pcoGeometry.pointAttributes;
  14656. }
  14657. toTreeNode(geometryNode, parent) {
  14658. var node = new PointCloudOctreeNode();
  14659. // if(geometryNode.name === "r40206"){
  14660. // console.log("creating node for r40206");
  14661. // }
  14662. var sceneNode = new Points(geometryNode.geometry, this.material);
  14663. sceneNode.name = geometryNode.name;
  14664. sceneNode.position.copy(geometryNode.boundingBox.min);
  14665. sceneNode.frustumCulled = false;
  14666. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  14667. if (material.program) {
  14668. _this.getContext().useProgram(material.program.program);
  14669. if (material.program.getUniforms().map.level) {
  14670. var level = geometryNode.getLevel();
  14671. material.uniforms.level.value = level;
  14672. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  14673. }
  14674. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  14675. var vnStart = this.visibleNodeTextureOffsets.get(node);
  14676. material.uniforms.vnStart.value = vnStart;
  14677. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  14678. }
  14679. if (material.program.getUniforms().map.pcIndex) {
  14680. var i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  14681. material.uniforms.pcIndex.value = i;
  14682. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  14683. }
  14684. }
  14685. };
  14686. // { // DEBUG
  14687. // let sg = new THREE.SphereGeometry(1, 16, 16);
  14688. // let sm = new THREE.MeshNormalMaterial();
  14689. // let s = new THREE.Mesh(sg, sm);
  14690. // s.scale.set(5, 5, 5);
  14691. // s.position.copy(geometryNode.mean)
  14692. // .add(this.position)
  14693. // .add(geometryNode.boundingBox.min);
  14694. //
  14695. // viewer.scene.scene.add(s);
  14696. // }
  14697. node.geometryNode = geometryNode;
  14698. node.sceneNode = sceneNode;
  14699. node.pointcloud = this;
  14700. node.children = [];
  14701. //for (let key in geometryNode.children) {
  14702. // node.children[key] = geometryNode.children[key];
  14703. //}
  14704. for (var i = 0; i < 8; i++) {
  14705. node.children[i] = geometryNode.children[i];
  14706. }
  14707. if (!parent) {
  14708. this.root = node;
  14709. this.add(sceneNode);
  14710. } else {
  14711. var childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  14712. parent.sceneNode.add(sceneNode);
  14713. parent.children[childIndex] = node;
  14714. }
  14715. var disposeListener = function disposeListener() {
  14716. var childIndex = parseInt(geometryNode.name[geometryNode.name.length - 1]);
  14717. parent.sceneNode.remove(node.sceneNode);
  14718. parent.children[childIndex] = geometryNode;
  14719. };
  14720. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  14721. return node;
  14722. }
  14723. updateVisibleBounds() {
  14724. var leafNodes = [];
  14725. for (var i = 0; i < this.visibleNodes.length; i++) {
  14726. var node = this.visibleNodes[i];
  14727. var isLeaf = true;
  14728. for (var j = 0; j < node.children.length; j++) {
  14729. var child = node.children[j];
  14730. if (child instanceof PointCloudOctreeNode) {
  14731. isLeaf = isLeaf && !child.sceneNode.visible;
  14732. } else if (child instanceof PointCloudOctreeGeometryNode) {
  14733. isLeaf = true;
  14734. }
  14735. }
  14736. if (isLeaf) {
  14737. leafNodes.push(node);
  14738. }
  14739. }
  14740. this.visibleBounds.min = new Vector3(Infinity, Infinity, Infinity);
  14741. this.visibleBounds.max = new Vector3(-Infinity, -Infinity, -Infinity);
  14742. for (var _i = 0; _i < leafNodes.length; _i++) {
  14743. var _node = leafNodes[_i];
  14744. this.visibleBounds.expandByPoint(_node.getBoundingBox().min);
  14745. this.visibleBounds.expandByPoint(_node.getBoundingBox().max);
  14746. }
  14747. }
  14748. updateMaterial(material, visibleNodes, camera, renderer) {
  14749. material.fov = camera.fov * (Math.PI / 180);
  14750. material.screenWidth = renderer.domElement.clientWidth;
  14751. material.screenHeight = renderer.domElement.clientHeight;
  14752. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  14753. material.near = camera.near;
  14754. material.far = camera.far;
  14755. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  14756. }
  14757. computeVisibilityTextureData(nodes, camera) {
  14758. if (Potree.measureTimings) performance.mark("computeVisibilityTextureData-start");
  14759. var data = new Uint8Array(nodes.length * 4);
  14760. var visibleNodeTextureOffsets = new Map();
  14761. // copy array
  14762. nodes = nodes.slice();
  14763. // sort by level and index, e.g. r, r0, r3, r4, r01, r07, r30, ...
  14764. var sort = function sort(a, b) {
  14765. var na = a.geometryNode.name;
  14766. var nb = b.geometryNode.name;
  14767. if (na.length !== nb.length) return na.length - nb.length;
  14768. if (na < nb) return -1;
  14769. if (na > nb) return 1;
  14770. return 0;
  14771. };
  14772. nodes.sort(sort);
  14773. var worldDir = new Vector3();
  14774. var nodeMap = new Map();
  14775. var offsetsToChild = new Array(nodes.length).fill(Infinity);
  14776. for (var i = 0; i < nodes.length; i++) {
  14777. var node = nodes[i];
  14778. nodeMap.set(node.name, node);
  14779. visibleNodeTextureOffsets.set(node, i);
  14780. if (i > 0) {
  14781. var index = parseInt(node.name.slice(-1));
  14782. var parentName = node.name.slice(0, -1);
  14783. var parent = nodeMap.get(parentName);
  14784. var parentOffset = visibleNodeTextureOffsets.get(parent);
  14785. var parentOffsetToChild = i - parentOffset;
  14786. offsetsToChild[parentOffset] = Math.min(offsetsToChild[parentOffset], parentOffsetToChild);
  14787. data[parentOffset * 4 + 0] = data[parentOffset * 4 + 0] | 1 << index;
  14788. data[parentOffset * 4 + 1] = offsetsToChild[parentOffset] >> 8;
  14789. data[parentOffset * 4 + 2] = offsetsToChild[parentOffset] % 256;
  14790. }
  14791. var density = node.geometryNode.density;
  14792. if (typeof density === "number") {
  14793. var lodOffset = Math.log2(density) / 2 - 1.5;
  14794. var offsetUint8 = (lodOffset + 10) * 10;
  14795. data[i * 4 + 3] = offsetUint8;
  14796. } else {
  14797. data[i * 4 + 3] = 100;
  14798. }
  14799. }
  14800. if (Potree.measureTimings) {
  14801. performance.mark("computeVisibilityTextureData-end");
  14802. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  14803. }
  14804. return {
  14805. data: data,
  14806. offsets: visibleNodeTextureOffsets
  14807. };
  14808. }
  14809. nodeIntersectsProfile(node, profile) {
  14810. var bbWorld = node.boundingBox.clone().applyMatrix4(this.matrixWorld);
  14811. var bsWorld = bbWorld.getBoundingSphere(new Sphere());
  14812. var intersects = false;
  14813. for (var i = 0; i < profile.points.length - 1; i++) {
  14814. var start = new Vector3(profile.points[i + 0].x, profile.points[i + 0].y, bsWorld.center.z);
  14815. var end = new Vector3(profile.points[i + 1].x, profile.points[i + 1].y, bsWorld.center.z);
  14816. var closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  14817. var distance = closest.distanceTo(bsWorld.center);
  14818. intersects = intersects || distance < bsWorld.radius + profile.width;
  14819. }
  14820. //console.log(`${node.name}: ${intersects}`);
  14821. return intersects;
  14822. }
  14823. deepestNodeAt(position) {
  14824. var toObjectSpace = this.matrixWorld.clone().invert();
  14825. var objPos = position.clone().applyMatrix4(toObjectSpace);
  14826. var current = this.root;
  14827. while (true) {
  14828. var containingChild = null;
  14829. for (var child of current.children) {
  14830. if (child !== undefined) {
  14831. if (child.getBoundingBox().containsPoint(objPos)) {
  14832. containingChild = child;
  14833. }
  14834. }
  14835. }
  14836. if (containingChild !== null && containingChild instanceof PointCloudOctreeNode) {
  14837. current = containingChild;
  14838. } else {
  14839. break;
  14840. }
  14841. }
  14842. var deepest = current;
  14843. return deepest;
  14844. }
  14845. nodesOnRay(nodes, ray) {
  14846. var nodesOnRay = [];
  14847. var _ray = ray.clone();
  14848. for (var i = 0; i < nodes.length; i++) {
  14849. var node = nodes[i];
  14850. var sphere = node.getBoundingSphere().clone().applyMatrix4(this.matrixWorld);
  14851. if (_ray.intersectsSphere(sphere)) {
  14852. nodesOnRay.push(node);
  14853. }
  14854. }
  14855. return nodesOnRay;
  14856. }
  14857. updateMatrixWorld(force) {
  14858. if (this.matrixAutoUpdate === true) this.updateMatrix();
  14859. if (this.matrixWorldNeedsUpdate === true || force === true) {
  14860. if (!this.parent) {
  14861. this.matrixWorld.copy(this.matrix);
  14862. } else {
  14863. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  14864. }
  14865. this.matrixWorldNeedsUpdate = false;
  14866. force = true;
  14867. }
  14868. }
  14869. hideDescendants(object) {
  14870. var stack = [];
  14871. for (var i = 0; i < object.children.length; i++) {
  14872. var child = object.children[i];
  14873. if (child.visible) {
  14874. stack.push(child);
  14875. }
  14876. }
  14877. while (stack.length > 0) {
  14878. var _object = stack.shift();
  14879. _object.visible = false;
  14880. for (var _i2 = 0; _i2 < _object.children.length; _i2++) {
  14881. var _child = _object.children[_i2];
  14882. if (_child.visible) {
  14883. stack.push(_child);
  14884. }
  14885. }
  14886. }
  14887. }
  14888. moveToOrigin() {
  14889. this.position.set(0, 0, 0);
  14890. this.updateMatrixWorld(true);
  14891. var box = this.boundingBox;
  14892. var transform = this.matrixWorld;
  14893. var tBox = Utils.computeTransformedBoundingBox(box, transform);
  14894. this.position.set(0, 0, 0).sub(tBox.getCenter(new Vector3()));
  14895. }
  14896. moveToGroundPlane() {
  14897. this.updateMatrixWorld(true);
  14898. var box = this.boundingBox;
  14899. var transform = this.matrixWorld;
  14900. var tBox = Utils.computeTransformedBoundingBox(box, transform);
  14901. this.position.y += -tBox.min.y;
  14902. }
  14903. getBoundingBoxWorld() {
  14904. this.updateMatrixWorld(true);
  14905. var box = this.boundingBox;
  14906. var transform = this.matrixWorld;
  14907. var tBox = Utils.computeTransformedBoundingBox(box, transform);
  14908. return tBox;
  14909. }
  14910. /**
  14911. * returns points inside the profile points
  14912. *
  14913. * maxDepth: search points up to the given octree depth
  14914. *
  14915. *
  14916. * The return value is an array with all segments of the profile path
  14917. * let segment = {
  14918. * start: THREE.Vector3,
  14919. * end: THREE.Vector3,
  14920. * points: {}
  14921. * project: function()
  14922. * };
  14923. *
  14924. * The project() function inside each segment can be used to transform
  14925. * that segments point coordinates to line up along the x-axis.
  14926. *
  14927. *
  14928. */
  14929. getPointsInProfile(profile, maxDepth, callback) {
  14930. if (callback) {
  14931. var request = new Potree.ProfileRequest(this, profile, maxDepth, callback);
  14932. this.profileRequests.push(request);
  14933. return request;
  14934. }
  14935. var points = {
  14936. segments: [],
  14937. boundingBox: new Box3(),
  14938. projectedBoundingBox: new Box2()
  14939. };
  14940. // evaluate segments
  14941. for (var i = 0; i < profile.points.length - 1; i++) {
  14942. var start = profile.points[i];
  14943. var end = profile.points[i + 1];
  14944. var ps = this.getProfile(start, end, profile.width, maxDepth);
  14945. var segment = {
  14946. start: start,
  14947. end: end,
  14948. points: ps,
  14949. project: null
  14950. };
  14951. points.segments.push(segment);
  14952. points.boundingBox.expandByPoint(ps.boundingBox.min);
  14953. points.boundingBox.expandByPoint(ps.boundingBox.max);
  14954. }
  14955. // add projection functions to the segments
  14956. var mileage = new Vector3();
  14957. for (var _i3 = 0; _i3 < points.segments.length; _i3++) {
  14958. var _segment = points.segments[_i3];
  14959. var _start2 = _segment.start;
  14960. var _end2 = _segment.end;
  14961. var project = function (_start, _end, _mileage, _boundingBox) {
  14962. var start = _start;
  14963. var end = _end;
  14964. var mileage = _mileage;
  14965. var boundingBox = _boundingBox;
  14966. var xAxis = new Vector3(1, 0, 0);
  14967. var dir = new Vector3().subVectors(end, start);
  14968. dir.y = 0;
  14969. dir.normalize();
  14970. var alpha = Math.acos(xAxis.dot(dir));
  14971. if (dir.z > 0) {
  14972. alpha = -alpha;
  14973. }
  14974. return function (position) {
  14975. var toOrigin = new Matrix4().makeTranslation(-start.x, -boundingBox.min.y, -start.z);
  14976. var alignWithX = new Matrix4().makeRotationY(-alpha);
  14977. var applyMileage = new Matrix4().makeTranslation(mileage.x, 0, 0);
  14978. var pos = position.clone();
  14979. pos.applyMatrix4(toOrigin);
  14980. pos.applyMatrix4(alignWithX);
  14981. pos.applyMatrix4(applyMileage);
  14982. return pos;
  14983. };
  14984. }(_start2, _end2, mileage.clone(), points.boundingBox.clone());
  14985. _segment.project = project;
  14986. mileage.x += new Vector3(_start2.x, 0, _start2.z).distanceTo(new Vector3(_end2.x, 0, _end2.z));
  14987. mileage.y += _end2.y - _start2.y;
  14988. }
  14989. points.projectedBoundingBox.min.x = 0;
  14990. points.projectedBoundingBox.min.y = points.boundingBox.min.y;
  14991. points.projectedBoundingBox.max.x = mileage.x;
  14992. points.projectedBoundingBox.max.y = points.boundingBox.max.y;
  14993. return points;
  14994. }
  14995. /**
  14996. * returns points inside the given profile bounds.
  14997. *
  14998. * start:
  14999. * end:
  15000. * width:
  15001. * depth: search points up to the given octree depth
  15002. * callback: if specified, points are loaded before searching
  15003. *
  15004. *
  15005. */
  15006. getProfile(start, end, width, depth, callback) {
  15007. var request = new Potree.ProfileRequest(start, end, width, depth, callback);
  15008. this.profileRequests.push(request);
  15009. }
  15010. getVisibleExtent() {
  15011. return this.visibleBounds.applyMatrix4(this.matrixWorld);
  15012. }
  15013. intersectsPoint(position) {
  15014. var rootAvailable = this.pcoGeometry.root && this.pcoGeometry.root.geometry;
  15015. if (!rootAvailable) {
  15016. return false;
  15017. }
  15018. if (typeof this.signedDistanceField === "undefined") {
  15019. var resolution = 32;
  15020. var field = new Float32Array(resolution ** 3).fill(Infinity);
  15021. var positions = this.pcoGeometry.root.geometry.attributes.position;
  15022. var boundingBox = this.boundingBox;
  15023. var n = positions.count;
  15024. for (var i = 0; i < n; i = i + 3) {
  15025. var x = positions.array[3 * i + 0];
  15026. var y = positions.array[3 * i + 1];
  15027. var z = positions.array[3 * i + 2];
  15028. var ix = parseInt(Math.min(resolution * (x / boundingBox.max.x), resolution - 1));
  15029. var iy = parseInt(Math.min(resolution * (y / boundingBox.max.y), resolution - 1));
  15030. var iz = parseInt(Math.min(resolution * (z / boundingBox.max.z), resolution - 1));
  15031. var index = ix + iy * resolution + iz * resolution * resolution;
  15032. field[index] = 0;
  15033. }
  15034. var sdf = {
  15035. resolution: resolution,
  15036. field: field
  15037. };
  15038. this.signedDistanceField = sdf;
  15039. }
  15040. {
  15041. var _sdf = this.signedDistanceField;
  15042. var _boundingBox2 = this.boundingBox;
  15043. var toObjectSpace = this.matrixWorld.clone().invert();
  15044. var objPos = position.clone().applyMatrix4(toObjectSpace);
  15045. var _resolution = _sdf.resolution;
  15046. var _ix = parseInt(_resolution * (objPos.x / _boundingBox2.max.x));
  15047. var _iy = parseInt(_resolution * (objPos.y / _boundingBox2.max.y));
  15048. var _iz = parseInt(_resolution * (objPos.z / _boundingBox2.max.z));
  15049. if (_ix < 0 || _iy < 0 || _iz < 0) {
  15050. return false;
  15051. }
  15052. if (_ix >= _resolution || _iy >= _resolution || _iz >= _resolution) {
  15053. return false;
  15054. }
  15055. var _index = _ix + _iy * _resolution + _iz * _resolution * _resolution;
  15056. var value = _sdf.field[_index];
  15057. if (value === 0) {
  15058. return true;
  15059. }
  15060. }
  15061. return false;
  15062. }
  15063. /**
  15064. *
  15065. *
  15066. *
  15067. * params.pickWindowSize: Look for points inside a pixel window of this size.
  15068. * Use odd values: 1, 3, 5, ...
  15069. *
  15070. *
  15071. * TODO: only draw pixels that are actually read with readPixels().
  15072. *
  15073. */
  15074. pick(viewer, camera, ray) {
  15075. var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  15076. var renderer = viewer.renderer;
  15077. var pRenderer = viewer.pRenderer;
  15078. performance.mark("pick-start");
  15079. var getVal = (a, b) => a !== undefined ? a : b;
  15080. var pickWindowSize = getVal(params.pickWindowSize, 65);
  15081. var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  15082. var size = renderer.getSize(new Vector2());
  15083. var width = Math.ceil(getVal(params.width, size.width));
  15084. var height = Math.ceil(getVal(params.height, size.height));
  15085. var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  15086. var pointSize = getVal(params.pointSize, this.material.size);
  15087. var nodes = this.nodesOnRay(this.visibleNodes, ray);
  15088. if (nodes.length === 0) {
  15089. return null;
  15090. }
  15091. if (!this.pickState) {
  15092. var scene = new Scene();
  15093. var material = new Potree.PointCloudMaterial();
  15094. material.activeAttributeName = "indices";
  15095. var renderTarget = new WebGLRenderTarget(1, 1, {
  15096. minFilter: LinearFilter,
  15097. magFilter: NearestFilter,
  15098. format: RGBAFormat
  15099. });
  15100. this.pickState = {
  15101. renderTarget: renderTarget,
  15102. material: material,
  15103. scene: scene
  15104. };
  15105. }
  15106. ;
  15107. var pickState = this.pickState;
  15108. var pickMaterial = pickState.material;
  15109. {
  15110. // update pick material
  15111. pickMaterial.pointSizeType = pointSizeType;
  15112. //pickMaterial.shape = this.material.shape;
  15113. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  15114. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  15115. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  15116. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  15117. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  15118. pickMaterial.activeAttributeName = "indices";
  15119. pickMaterial.size = pointSize;
  15120. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  15121. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  15122. pickMaterial.classification = this.material.classification;
  15123. pickMaterial.recomputeClassification();
  15124. if (params.pickClipped) {
  15125. pickMaterial.clipBoxes = this.material.clipBoxes;
  15126. pickMaterial.uniforms.clipBoxes = this.material.uniforms.clipBoxes;
  15127. if (this.material.clipTask === Potree.ClipTask.HIGHLIGHT) {
  15128. pickMaterial.clipTask = Potree.ClipTask.NONE;
  15129. } else {
  15130. pickMaterial.clipTask = this.material.clipTask;
  15131. }
  15132. pickMaterial.clipMethod = this.material.clipMethod;
  15133. } else {
  15134. pickMaterial.clipBoxes = [];
  15135. }
  15136. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  15137. }
  15138. pickState.renderTarget.setSize(width, height);
  15139. var pixelPos = new Vector2(params.x, params.y);
  15140. var gl = renderer.getContext();
  15141. gl.enable(gl.SCISSOR_TEST);
  15142. gl.scissor(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize));
  15143. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  15144. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  15145. renderer.state.setBlending(NoBlending);
  15146. {
  15147. // RENDER
  15148. renderer.setRenderTarget(pickState.renderTarget);
  15149. gl.clearColor(0, 0, 0, 0);
  15150. renderer.clear(true, true, true);
  15151. var tmp = this.material;
  15152. this.material = pickMaterial;
  15153. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  15154. this.material = tmp;
  15155. }
  15156. var clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  15157. var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  15158. var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  15159. var w = parseInt(Math.min(x + pickWindowSize, width) - x);
  15160. var h = parseInt(Math.min(y + pickWindowSize, height) - y);
  15161. var pixelCount = w * h;
  15162. var buffer = new Uint8Array(4 * pixelCount);
  15163. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  15164. renderer.setRenderTarget(null);
  15165. renderer.state.reset();
  15166. renderer.setScissorTest(false);
  15167. gl.disable(gl.SCISSOR_TEST);
  15168. var pixels = buffer;
  15169. var ibuffer = new Uint32Array(buffer.buffer);
  15170. // find closest hit inside pixelWindow boundaries
  15171. var min = Number.MAX_VALUE;
  15172. var hits = [];
  15173. for (var u = 0; u < pickWindowSize; u++) {
  15174. for (var v = 0; v < pickWindowSize; v++) {
  15175. var offset = u + v * pickWindowSize;
  15176. var distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  15177. var pcIndex = pixels[4 * offset + 3];
  15178. pixels[4 * offset + 3] = 0;
  15179. var pIndex = ibuffer[offset];
  15180. if (!(pcIndex === 0 && pIndex === 0) && pcIndex !== undefined && pIndex !== undefined) {
  15181. var hit = {
  15182. pIndex: pIndex,
  15183. pcIndex: pcIndex,
  15184. distanceToCenter: distance
  15185. };
  15186. if (params.all) {
  15187. hits.push(hit);
  15188. } else {
  15189. if (hits.length > 0) {
  15190. if (distance < hits[0].distanceToCenter) {
  15191. hits[0] = hit;
  15192. }
  15193. } else {
  15194. hits.push(hit);
  15195. }
  15196. }
  15197. }
  15198. }
  15199. }
  15200. // { // DEBUG: show panel with pick image
  15201. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  15202. // let screenshot = img.src;
  15203. // if(!this.debugDIV){
  15204. // this.debugDIV = $(`
  15205. // <div id="pickDebug"
  15206. // style="position: absolute;
  15207. // right: 400px; width: 300px;
  15208. // bottom: 44px; width: 300px;
  15209. // z-index: 1000;
  15210. // "></div>`);
  15211. // $(document.body).append(this.debugDIV);
  15212. // }
  15213. // this.debugDIV.empty();
  15214. // this.debugDIV.append($(`<img src="${screenshot}"
  15215. // style="transform: scaleY(-1); width: 300px"/>`));
  15216. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  15217. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  15218. // }
  15219. for (var _hit of hits) {
  15220. var point = {};
  15221. if (!nodes[_hit.pcIndex]) {
  15222. return null;
  15223. }
  15224. var node = nodes[_hit.pcIndex];
  15225. var pc = node.sceneNode;
  15226. var geometry = node.geometryNode.geometry;
  15227. var _loop2 = function _loop2() {
  15228. var attribute = geometry.attributes[attributeName];
  15229. if (attributeName === 'position') {
  15230. var _x = attribute.array[3 * _hit.pIndex + 0];
  15231. var _y = attribute.array[3 * _hit.pIndex + 1];
  15232. var z = attribute.array[3 * _hit.pIndex + 2];
  15233. var position = new Vector3(_x, _y, z);
  15234. position.applyMatrix4(pc.matrixWorld);
  15235. point[attributeName] = position;
  15236. } else if (attributeName === 'indices') {} else {
  15237. var values = attribute.array.slice(attribute.itemSize * _hit.pIndex, attribute.itemSize * (_hit.pIndex + 1));
  15238. if (attribute.potree) {
  15239. var {
  15240. scale,
  15241. offset: _offset
  15242. } = attribute.potree;
  15243. values = values.map(v => v / scale + _offset);
  15244. }
  15245. point[attributeName] = values;
  15246. //debugger;
  15247. //if (values.itemSize === 1) {
  15248. // point[attribute.name] = values.array[hit.pIndex];
  15249. //} else {
  15250. // let value = [];
  15251. // for (let j = 0; j < values.itemSize; j++) {
  15252. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  15253. // }
  15254. // point[attribute.name] = value;
  15255. //}
  15256. }
  15257. };
  15258. for (var attributeName in geometry.attributes) {
  15259. _loop2();
  15260. }
  15261. _hit.point = point;
  15262. }
  15263. performance.mark("pick-end");
  15264. performance.measure("pick", "pick-start", "pick-end");
  15265. if (params.all) {
  15266. return hits.map(hit => hit.point);
  15267. } else {
  15268. if (hits.length === 0) {
  15269. return null;
  15270. } else {
  15271. return hits[0].point;
  15272. //let sorted = hits.sort( (a, b) => a.distanceToCenter - b.distanceToCenter);
  15273. //return sorted[0].point;
  15274. }
  15275. }
  15276. }
  15277. *getFittedBoxGen(boxNode) {
  15278. var start = performance.now();
  15279. var shrinkedLocalBounds = new Box3();
  15280. var worldToBox = boxNode.matrixWorld.clone().invert();
  15281. for (var node of this.visibleNodes) {
  15282. if (!node.sceneNode) {
  15283. continue;
  15284. }
  15285. var buffer = node.geometryNode.buffer;
  15286. var posOffset = buffer.offset("position");
  15287. var stride = buffer.stride;
  15288. var view = new DataView(buffer.data);
  15289. var objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  15290. var pos = new Vector4();
  15291. for (var i = 0; i < buffer.numElements; i++) {
  15292. var x = view.getFloat32(i * stride + posOffset + 0, true);
  15293. var y = view.getFloat32(i * stride + posOffset + 4, true);
  15294. var z = view.getFloat32(i * stride + posOffset + 8, true);
  15295. pos.set(x, y, z, 1);
  15296. pos.applyMatrix4(objectToBox);
  15297. if (-0.5 < pos.x && pos.x < 0.5) {
  15298. if (-0.5 < pos.y && pos.y < 0.5) {
  15299. if (-0.5 < pos.z && pos.z < 0.5) {
  15300. shrinkedLocalBounds.expandByPoint(pos);
  15301. }
  15302. }
  15303. }
  15304. }
  15305. yield;
  15306. }
  15307. var fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  15308. var fitted = new Object3D();
  15309. fitted.position.copy(fittedPosition);
  15310. fitted.scale.copy(boxNode.scale);
  15311. fitted.rotation.copy(boxNode.rotation);
  15312. var ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  15313. fitted.scale.multiply(ds);
  15314. var duration = performance.now() - start;
  15315. console.log("duration: ", duration);
  15316. yield fitted;
  15317. }
  15318. getFittedBox(boxNode) {
  15319. var maxLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Infinity;
  15320. maxLevel = Infinity;
  15321. var start = performance.now();
  15322. var shrinkedLocalBounds = new Box3();
  15323. var worldToBox = boxNode.matrixWorld.clone().invert();
  15324. for (var node of this.visibleNodes) {
  15325. if (!node.sceneNode || node.getLevel() > maxLevel) {
  15326. continue;
  15327. }
  15328. var buffer = node.geometryNode.buffer;
  15329. var posOffset = buffer.offset("position");
  15330. var stride = buffer.stride;
  15331. var view = new DataView(buffer.data);
  15332. var objectToBox = new Matrix4().multiplyMatrices(worldToBox, node.sceneNode.matrixWorld);
  15333. var pos = new Vector4();
  15334. for (var i = 0; i < buffer.numElements; i++) {
  15335. var x = view.getFloat32(i * stride + posOffset + 0, true);
  15336. var y = view.getFloat32(i * stride + posOffset + 4, true);
  15337. var z = view.getFloat32(i * stride + posOffset + 8, true);
  15338. pos.set(x, y, z, 1);
  15339. pos.applyMatrix4(objectToBox);
  15340. if (-0.5 < pos.x && pos.x < 0.5) {
  15341. if (-0.5 < pos.y && pos.y < 0.5) {
  15342. if (-0.5 < pos.z && pos.z < 0.5) {
  15343. shrinkedLocalBounds.expandByPoint(pos);
  15344. }
  15345. }
  15346. }
  15347. }
  15348. }
  15349. var fittedPosition = shrinkedLocalBounds.getCenter(new Vector3()).applyMatrix4(boxNode.matrixWorld);
  15350. var fitted = new Object3D();
  15351. fitted.position.copy(fittedPosition);
  15352. fitted.scale.copy(boxNode.scale);
  15353. fitted.rotation.copy(boxNode.rotation);
  15354. var ds = new Vector3().subVectors(shrinkedLocalBounds.max, shrinkedLocalBounds.min);
  15355. fitted.scale.multiply(ds);
  15356. var duration = performance.now() - start;
  15357. console.log("duration: ", duration);
  15358. return fitted;
  15359. }
  15360. get progress() {
  15361. return this.visibleNodes.length / this.visibleGeometry.length;
  15362. }
  15363. find(name) {
  15364. var node = null;
  15365. for (var char of name) {
  15366. if (char === "r") {
  15367. node = this.root;
  15368. } else {
  15369. node = node.children[char];
  15370. }
  15371. }
  15372. return node;
  15373. }
  15374. get visible() {
  15375. return this._visible;
  15376. }
  15377. set visible(value) {
  15378. if (value !== this._visible) {
  15379. this._visible = value;
  15380. this.dispatchEvent({
  15381. type: 'visibility_changed',
  15382. pointcloud: this
  15383. });
  15384. }
  15385. }
  15386. }
  15387. class PointCloudArena4DNode extends PointCloudTreeNode {
  15388. constructor() {
  15389. super();
  15390. this.left = null;
  15391. this.right = null;
  15392. this.sceneNode = null;
  15393. this.kdtree = null;
  15394. }
  15395. getNumPoints() {
  15396. return this.geometryNode.numPoints;
  15397. }
  15398. isLoaded() {
  15399. return true;
  15400. }
  15401. isTreeNode() {
  15402. return true;
  15403. }
  15404. isGeometryNode() {
  15405. return false;
  15406. }
  15407. getLevel() {
  15408. return this.geometryNode.level;
  15409. }
  15410. getBoundingSphere() {
  15411. return this.geometryNode.boundingSphere;
  15412. }
  15413. getBoundingBox() {
  15414. return this.geometryNode.boundingBox;
  15415. }
  15416. toTreeNode(child) {
  15417. var geometryNode = null;
  15418. if (this.left === child) {
  15419. geometryNode = this.left;
  15420. } else if (this.right === child) {
  15421. geometryNode = this.right;
  15422. }
  15423. if (!geometryNode.loaded) {
  15424. return;
  15425. }
  15426. var node = new PointCloudArena4DNode();
  15427. var sceneNode = PointCloud(geometryNode.geometry, this.kdtree.material);
  15428. sceneNode.visible = false;
  15429. node.kdtree = this.kdtree;
  15430. node.geometryNode = geometryNode;
  15431. node.sceneNode = sceneNode;
  15432. node.parent = this;
  15433. node.left = this.geometryNode.left;
  15434. node.right = this.geometryNode.right;
  15435. }
  15436. getChildren() {
  15437. var children = [];
  15438. if (this.left) {
  15439. children.push(this.left);
  15440. }
  15441. if (this.right) {
  15442. children.push(this.right);
  15443. }
  15444. return children;
  15445. }
  15446. }
  15447. ;
  15448. class PointCloudArena4D$1 extends PointCloudTree {
  15449. constructor(geometry) {
  15450. super();
  15451. this.root = null;
  15452. if (geometry.root) {
  15453. this.root = geometry.root;
  15454. } else {
  15455. geometry.addEventListener('hierarchy_loaded', () => {
  15456. this.root = geometry.root;
  15457. });
  15458. }
  15459. this.visiblePointsTarget = 2 * 1000 * 1000;
  15460. this.minimumNodePixelSize = 150;
  15461. this.position.sub(geometry.offset);
  15462. this.updateMatrix();
  15463. this.numVisibleNodes = 0;
  15464. this.numVisiblePoints = 0;
  15465. this.boundingBoxNodes = [];
  15466. this.loadQueue = [];
  15467. this.visibleNodes = [];
  15468. this.pcoGeometry = geometry;
  15469. this.boundingBox = this.pcoGeometry.boundingBox;
  15470. this.boundingSphere = this.pcoGeometry.boundingSphere;
  15471. this.material = new PointCloudMaterial$1({
  15472. vertexColors: VertexColors,
  15473. size: 0.05,
  15474. treeType: TreeType.KDTREE
  15475. });
  15476. this.material.sizeType = PointSizeType.ATTENUATED;
  15477. this.material.size = 0.05;
  15478. this.profileRequests = [];
  15479. this.name = '';
  15480. }
  15481. getBoundingBoxWorld() {
  15482. this.updateMatrixWorld(true);
  15483. var box = this.boundingBox;
  15484. var transform = this.matrixWorld;
  15485. var tBox = Utils.computeTransformedBoundingBox(box, transform);
  15486. return tBox;
  15487. }
  15488. setName(name) {
  15489. if (this.name !== name) {
  15490. this.name = name;
  15491. this.dispatchEvent({
  15492. type: 'name_changed',
  15493. name: name,
  15494. pointcloud: this
  15495. });
  15496. }
  15497. }
  15498. getName() {
  15499. return this.name;
  15500. }
  15501. getLevel() {
  15502. return this.level;
  15503. }
  15504. toTreeNode(geometryNode, parent) {
  15505. var node = new PointCloudArena4DNode();
  15506. var sceneNode = new Points(geometryNode.geometry, this.material);
  15507. sceneNode.frustumCulled = false;
  15508. sceneNode.onBeforeRender = (_this, scene, camera, geometry, material, group) => {
  15509. if (material.program) {
  15510. _this.getContext().useProgram(material.program.program);
  15511. if (material.program.getUniforms().map.level) {
  15512. var level = geometryNode.getLevel();
  15513. material.uniforms.level.value = level;
  15514. material.program.getUniforms().map.level.setValue(_this.getContext(), level);
  15515. }
  15516. if (this.visibleNodeTextureOffsets && material.program.getUniforms().map.vnStart) {
  15517. var vnStart = this.visibleNodeTextureOffsets.get(node);
  15518. material.uniforms.vnStart.value = vnStart;
  15519. material.program.getUniforms().map.vnStart.setValue(_this.getContext(), vnStart);
  15520. }
  15521. if (material.program.getUniforms().map.pcIndex) {
  15522. var i = node.pcIndex ? node.pcIndex : this.visibleNodes.indexOf(node);
  15523. material.uniforms.pcIndex.value = i;
  15524. material.program.getUniforms().map.pcIndex.setValue(_this.getContext(), i);
  15525. }
  15526. }
  15527. };
  15528. node.geometryNode = geometryNode;
  15529. node.sceneNode = sceneNode;
  15530. node.pointcloud = this;
  15531. node.left = geometryNode.left;
  15532. node.right = geometryNode.right;
  15533. if (!parent) {
  15534. this.root = node;
  15535. this.add(sceneNode);
  15536. } else {
  15537. parent.sceneNode.add(sceneNode);
  15538. if (parent.left === geometryNode) {
  15539. parent.left = node;
  15540. } else if (parent.right === geometryNode) {
  15541. parent.right = node;
  15542. }
  15543. }
  15544. var disposeListener = function disposeListener() {
  15545. parent.sceneNode.remove(node.sceneNode);
  15546. if (parent.left === node) {
  15547. parent.left = geometryNode;
  15548. } else if (parent.right === node) {
  15549. parent.right = geometryNode;
  15550. }
  15551. };
  15552. geometryNode.oneTimeDisposeHandlers.push(disposeListener);
  15553. return node;
  15554. }
  15555. updateMaterial(material, visibleNodes, camera, renderer) {
  15556. material.fov = camera.fov * (Math.PI / 180);
  15557. material.screenWidth = renderer.domElement.clientWidth;
  15558. material.screenHeight = renderer.domElement.clientHeight;
  15559. material.spacing = this.pcoGeometry.spacing;
  15560. material.near = camera.near;
  15561. material.far = camera.far;
  15562. // reduce shader source updates by setting maxLevel slightly higher than actually necessary
  15563. if (this.maxLevel > material.levels) {
  15564. material.levels = this.maxLevel + 2;
  15565. }
  15566. // material.uniforms.octreeSize.value = this.boundingBox.size().x;
  15567. var bbSize = this.boundingBox.getSize(new Vector3());
  15568. material.bbSize = [bbSize.x, bbSize.y, bbSize.z];
  15569. }
  15570. updateVisibleBounds() {}
  15571. hideDescendants(object) {
  15572. var stack = [];
  15573. for (var i = 0; i < object.children.length; i++) {
  15574. var child = object.children[i];
  15575. if (child.visible) {
  15576. stack.push(child);
  15577. }
  15578. }
  15579. while (stack.length > 0) {
  15580. var _child = stack.shift();
  15581. _child.visible = false;
  15582. if (_child.boundingBoxNode) {
  15583. _child.boundingBoxNode.visible = false;
  15584. }
  15585. for (var _i = 0; _i < _child.children.length; _i++) {
  15586. var childOfChild = _child.children[_i];
  15587. if (childOfChild.visible) {
  15588. stack.push(childOfChild);
  15589. }
  15590. }
  15591. }
  15592. }
  15593. updateMatrixWorld(force) {
  15594. // node.matrixWorld.multiplyMatrices( node.parent.matrixWorld, node.matrix );
  15595. if (this.matrixAutoUpdate === true) this.updateMatrix();
  15596. if (this.matrixWorldNeedsUpdate === true || force === true) {
  15597. if (this.parent === undefined) {
  15598. this.matrixWorld.copy(this.matrix);
  15599. } else {
  15600. this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix);
  15601. }
  15602. this.matrixWorldNeedsUpdate = false;
  15603. force = true;
  15604. }
  15605. }
  15606. nodesOnRay(nodes, ray) {
  15607. var nodesOnRay = [];
  15608. var _ray = ray.clone();
  15609. for (var i = 0; i < nodes.length; i++) {
  15610. var node = nodes[i];
  15611. var sphere = node.getBoundingSphere().clone().applyMatrix4(node.sceneNode.matrixWorld);
  15612. // TODO Unused: let box = node.getBoundingBox().clone().applyMatrix4(node.sceneNode.matrixWorld);
  15613. if (_ray.intersectsSphere(sphere)) {
  15614. nodesOnRay.push(node);
  15615. }
  15616. // if(_ray.isIntersectionBox(box)){
  15617. // nodesOnRay.push(node);
  15618. // }
  15619. }
  15620. return nodesOnRay;
  15621. }
  15622. pick(viewer, camera, ray) {
  15623. var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  15624. var renderer = viewer.renderer;
  15625. var pRenderer = viewer.pRenderer;
  15626. performance.mark("pick-start");
  15627. var getVal = (a, b) => a !== undefined ? a : b;
  15628. var pickWindowSize = getVal(params.pickWindowSize, 17);
  15629. var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  15630. var size = renderer.getSize(new Vector2());
  15631. var width = Math.ceil(getVal(params.width, size.width));
  15632. var height = Math.ceil(getVal(params.height, size.height));
  15633. var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  15634. var pointSize = getVal(params.pointSize, this.material.size);
  15635. var nodes = this.nodesOnRay(this.visibleNodes, ray);
  15636. if (nodes.length === 0) {
  15637. return null;
  15638. }
  15639. if (!this.pickState) {
  15640. var scene = new Scene();
  15641. var material = new PointCloudMaterial$1();
  15642. material.activeAttributeName = "indices";
  15643. var renderTarget = new WebGLRenderTarget(1, 1, {
  15644. minFilter: LinearFilter,
  15645. magFilter: NearestFilter,
  15646. format: RGBAFormat
  15647. });
  15648. this.pickState = {
  15649. renderTarget: renderTarget,
  15650. material: material,
  15651. scene: scene
  15652. };
  15653. }
  15654. ;
  15655. var pickState = this.pickState;
  15656. var pickMaterial = pickState.material;
  15657. {
  15658. // update pick material
  15659. pickMaterial.pointSizeType = pointSizeType;
  15660. pickMaterial.shape = this.material.shape;
  15661. pickMaterial.size = pointSize;
  15662. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  15663. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  15664. pickMaterial.classification = this.material.classification;
  15665. if (params.pickClipped) {
  15666. pickMaterial.clipBoxes = this.material.clipBoxes;
  15667. if (this.material.clipTask === ClipTask.HIGHLIGHT) {
  15668. pickMaterial.clipTask = ClipTask.NONE;
  15669. } else {
  15670. pickMaterial.clipTask = this.material.clipTask;
  15671. }
  15672. } else {
  15673. pickMaterial.clipBoxes = [];
  15674. }
  15675. this.updateMaterial(pickMaterial, nodes, camera, renderer);
  15676. }
  15677. pickState.renderTarget.setSize(width, height);
  15678. var pixelPos = new Vector2(params.x, params.y);
  15679. var gl = renderer.getContext();
  15680. gl.enable(gl.SCISSOR_TEST);
  15681. gl.scissor(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize));
  15682. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  15683. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  15684. renderer.state.setBlending(NoBlending);
  15685. renderer.clearTarget(pickState.renderTarget, true, true, true);
  15686. {
  15687. // RENDER
  15688. renderer.setRenderTarget(pickState.renderTarget);
  15689. gl.clearColor(0, 0, 0, 0);
  15690. renderer.clearTarget(pickState.renderTarget, true, true, true);
  15691. var tmp = this.material;
  15692. this.material = pickMaterial;
  15693. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget);
  15694. this.material = tmp;
  15695. }
  15696. var clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  15697. var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  15698. var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  15699. var w = parseInt(Math.min(x + pickWindowSize, width) - x);
  15700. var h = parseInt(Math.min(y + pickWindowSize, height) - y);
  15701. var pixelCount = w * h;
  15702. var buffer = new Uint8Array(4 * pixelCount);
  15703. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
  15704. renderer.setRenderTarget(null);
  15705. renderer.state.reset();
  15706. renderer.setScissorTest(false);
  15707. gl.disable(gl.SCISSOR_TEST);
  15708. var pixels = buffer;
  15709. var ibuffer = new Uint32Array(buffer.buffer);
  15710. // find closest hit inside pixelWindow boundaries
  15711. var min = Number.MAX_VALUE;
  15712. var hits = [];
  15713. for (var u = 0; u < pickWindowSize; u++) {
  15714. for (var v = 0; v < pickWindowSize; v++) {
  15715. var offset = u + v * pickWindowSize;
  15716. var distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  15717. var pcIndex = pixels[4 * offset + 3];
  15718. pixels[4 * offset + 3] = 0;
  15719. var pIndex = ibuffer[offset];
  15720. if (!(pcIndex === 0 && pIndex === 0) && pcIndex !== undefined && pIndex !== undefined) {
  15721. var hit = {
  15722. pIndex: pIndex,
  15723. pcIndex: pcIndex,
  15724. distanceToCenter: distance
  15725. };
  15726. if (params.all) {
  15727. hits.push(hit);
  15728. } else {
  15729. if (hits.length > 0) {
  15730. if (distance < hits[0].distanceToCenter) {
  15731. hits[0] = hit;
  15732. }
  15733. } else {
  15734. hits.push(hit);
  15735. }
  15736. }
  15737. }
  15738. }
  15739. }
  15740. for (var _hit of hits) {
  15741. var point = {};
  15742. if (!nodes[_hit.pcIndex]) {
  15743. return null;
  15744. }
  15745. var node = nodes[_hit.pcIndex];
  15746. var pc = node.sceneNode;
  15747. var geometry = node.geometryNode.geometry;
  15748. for (var attributeName in geometry.attributes) {
  15749. var attribute = geometry.attributes[attributeName];
  15750. if (attributeName === 'position') {
  15751. var _x = attribute.array[3 * _hit.pIndex + 0];
  15752. var _y = attribute.array[3 * _hit.pIndex + 1];
  15753. var z = attribute.array[3 * _hit.pIndex + 2];
  15754. var position = new Vector3(_x, _y, z);
  15755. position.applyMatrix4(pc.matrixWorld);
  15756. point[attributeName] = position;
  15757. } else if (attributeName === 'indices') {} else {
  15758. //if (values.itemSize === 1) {
  15759. // point[attribute.name] = values.array[hit.pIndex];
  15760. //} else {
  15761. // let value = [];
  15762. // for (let j = 0; j < values.itemSize; j++) {
  15763. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  15764. // }
  15765. // point[attribute.name] = value;
  15766. //}
  15767. }
  15768. }
  15769. _hit.point = point;
  15770. }
  15771. performance.mark("pick-end");
  15772. performance.measure("pick", "pick-start", "pick-end");
  15773. if (params.all) {
  15774. return hits.map(hit => hit.point);
  15775. } else {
  15776. if (hits.length === 0) {
  15777. return null;
  15778. } else {
  15779. return hits[0].point;
  15780. }
  15781. }
  15782. }
  15783. computeVisibilityTextureData(nodes) {
  15784. if (exports.measureTimings) performance.mark("computeVisibilityTextureData-start");
  15785. var data = new Uint8Array(nodes.length * 3);
  15786. var visibleNodeTextureOffsets = new Map();
  15787. // copy array
  15788. nodes = nodes.slice();
  15789. // sort by level and number
  15790. var sort = function sort(a, b) {
  15791. var la = a.geometryNode.level;
  15792. var lb = b.geometryNode.level;
  15793. var na = a.geometryNode.number;
  15794. var nb = b.geometryNode.number;
  15795. if (la !== lb) return la - lb;
  15796. if (na < nb) return -1;
  15797. if (na > nb) return 1;
  15798. return 0;
  15799. };
  15800. nodes.sort(sort);
  15801. var visibleNodeNames = [];
  15802. for (var i = 0; i < nodes.length; i++) {
  15803. visibleNodeNames.push(nodes[i].geometryNode.number);
  15804. }
  15805. for (var _i2 = 0; _i2 < nodes.length; _i2++) {
  15806. var node = nodes[_i2];
  15807. visibleNodeTextureOffsets.set(node, _i2);
  15808. var b1 = 0; // children
  15809. var b2 = 0; // offset to first child
  15810. var b3 = 0; // split
  15811. if (node.geometryNode.left && visibleNodeNames.indexOf(node.geometryNode.left.number) > 0) {
  15812. b1 += 1;
  15813. b2 = visibleNodeNames.indexOf(node.geometryNode.left.number) - _i2;
  15814. }
  15815. if (node.geometryNode.right && visibleNodeNames.indexOf(node.geometryNode.right.number) > 0) {
  15816. b1 += 2;
  15817. b2 = b2 === 0 ? visibleNodeNames.indexOf(node.geometryNode.right.number) - _i2 : b2;
  15818. }
  15819. if (node.geometryNode.split === 'X') {
  15820. b3 = 1;
  15821. } else if (node.geometryNode.split === 'Y') {
  15822. b3 = 2;
  15823. } else if (node.geometryNode.split === 'Z') {
  15824. b3 = 4;
  15825. }
  15826. data[_i2 * 3 + 0] = b1;
  15827. data[_i2 * 3 + 1] = b2;
  15828. data[_i2 * 3 + 2] = b3;
  15829. }
  15830. if (exports.measureTimings) {
  15831. performance.mark("computeVisibilityTextureData-end");
  15832. performance.measure("render.computeVisibilityTextureData", "computeVisibilityTextureData-start", "computeVisibilityTextureData-end");
  15833. }
  15834. return {
  15835. data: data,
  15836. offsets: visibleNodeTextureOffsets
  15837. };
  15838. }
  15839. get progress() {
  15840. if (this.pcoGeometry.root) {
  15841. return exports.numNodesLoading > 0 ? 0 : 1;
  15842. } else {
  15843. return 0;
  15844. }
  15845. }
  15846. }
  15847. ;
  15848. // Copied from three.js: WebGLRenderer.js
  15849. function paramThreeToGL(_gl, p) {
  15850. var extension;
  15851. if (p === RepeatWrapping) return _gl.REPEAT;
  15852. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  15853. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  15854. if (p === NearestFilter) return _gl.NEAREST;
  15855. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  15856. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  15857. if (p === LinearFilter) return _gl.LINEAR;
  15858. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  15859. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  15860. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  15861. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15862. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15863. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  15864. if (p === ByteType) return _gl.BYTE;
  15865. if (p === ShortType) return _gl.SHORT;
  15866. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  15867. if (p === IntType) return _gl.INT;
  15868. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  15869. if (p === FloatType) return _gl.FLOAT;
  15870. if (p === HalfFloatType) {
  15871. extension = extensions.get('OES_texture_half_float');
  15872. if (extension !== null) return extension.HALF_FLOAT_OES;
  15873. }
  15874. if (p === AlphaFormat) return _gl.ALPHA;
  15875. if (p === RGBFormat) return _gl.RGB;
  15876. if (p === RGBAFormat) return _gl.RGBA;
  15877. if (p === LuminanceFormat) return _gl.LUMINANCE;
  15878. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  15879. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  15880. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  15881. if (p === AddEquation) return _gl.FUNC_ADD;
  15882. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  15883. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  15884. if (p === ZeroFactor) return _gl.ZERO;
  15885. if (p === OneFactor) return _gl.ONE;
  15886. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  15887. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  15888. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  15889. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  15890. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  15891. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  15892. if (p === DstColorFactor) return _gl.DST_COLOR;
  15893. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  15894. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  15895. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  15896. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  15897. if (extension !== null) {
  15898. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15899. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15900. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15901. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15902. }
  15903. }
  15904. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  15905. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  15906. if (extension !== null) {
  15907. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15908. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15909. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15910. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15911. }
  15912. }
  15913. if (p === RGB_ETC1_Format) {
  15914. extension = extensions.get('WEBGL_compressed_texture_etc1');
  15915. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15916. }
  15917. if (p === MinEquation || p === MaxEquation) {
  15918. extension = extensions.get('EXT_blend_minmax');
  15919. if (extension !== null) {
  15920. if (p === MinEquation) return extension.MIN_EXT;
  15921. if (p === MaxEquation) return extension.MAX_EXT;
  15922. }
  15923. }
  15924. if (p === UnsignedInt248Type) {
  15925. extension = extensions.get('WEBGL_depth_texture');
  15926. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  15927. }
  15928. return 0;
  15929. }
  15930. ;
  15931. var attributeLocations = {
  15932. "position": {
  15933. name: "position",
  15934. location: 0
  15935. },
  15936. "color": {
  15937. name: "color",
  15938. location: 1
  15939. },
  15940. "rgba": {
  15941. name: "color",
  15942. location: 1
  15943. },
  15944. "intensity": {
  15945. name: "intensity",
  15946. location: 2
  15947. },
  15948. "classification": {
  15949. name: "classification",
  15950. location: 3
  15951. },
  15952. "returnNumber": {
  15953. name: "returnNumber",
  15954. location: 4
  15955. },
  15956. "return number": {
  15957. name: "returnNumber",
  15958. location: 4
  15959. },
  15960. "returns": {
  15961. name: "returnNumber",
  15962. location: 4
  15963. },
  15964. "numberOfReturns": {
  15965. name: "numberOfReturns",
  15966. location: 5
  15967. },
  15968. "number of returns": {
  15969. name: "numberOfReturns",
  15970. location: 5
  15971. },
  15972. "pointSourceID": {
  15973. name: "pointSourceID",
  15974. location: 6
  15975. },
  15976. "source id": {
  15977. name: "pointSourceID",
  15978. location: 6
  15979. },
  15980. "point source id": {
  15981. name: "pointSourceID",
  15982. location: 6
  15983. },
  15984. "indices": {
  15985. name: "indices",
  15986. location: 7
  15987. },
  15988. "normal": {
  15989. name: "normal",
  15990. location: 8
  15991. },
  15992. "spacing": {
  15993. name: "spacing",
  15994. location: 9
  15995. },
  15996. "gps-time": {
  15997. name: "gpsTime",
  15998. location: 10
  15999. },
  16000. "aExtra": {
  16001. name: "aExtra",
  16002. location: 11
  16003. }
  16004. };
  16005. class Shader {
  16006. constructor(gl, name, vsSource, fsSource) {
  16007. this.gl = gl;
  16008. this.name = name;
  16009. this.vsSource = vsSource;
  16010. this.fsSource = fsSource;
  16011. this.cache = new Map();
  16012. this.vs = null;
  16013. this.fs = null;
  16014. this.program = null;
  16015. this.uniformLocations = {};
  16016. this.attributeLocations = {};
  16017. this.uniformBlockIndices = {};
  16018. this.uniformBlocks = {};
  16019. this.uniforms = {};
  16020. this.update(vsSource, fsSource);
  16021. }
  16022. update(vsSource, fsSource) {
  16023. this.vsSource = vsSource;
  16024. this.fsSource = fsSource;
  16025. this.linkProgram();
  16026. }
  16027. compileShader(shader, source) {
  16028. var gl = this.gl;
  16029. gl.shaderSource(shader, source);
  16030. gl.compileShader(shader);
  16031. var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  16032. if (!success) {
  16033. var info = gl.getShaderInfoLog(shader);
  16034. var numberedSource = source.split("\n").map((a, i) => "".concat(i + 1).padEnd(5) + a).join("\n");
  16035. throw "could not compile shader ".concat(this.name, ": ").concat(info, ", \n").concat(numberedSource);
  16036. }
  16037. }
  16038. linkProgram() {
  16039. var tStart = performance.now();
  16040. var gl = this.gl;
  16041. this.uniformLocations = {};
  16042. this.attributeLocations = {};
  16043. this.uniforms = {};
  16044. gl.useProgram(null);
  16045. var cached = this.cache.get("".concat(this.vsSource, ", ").concat(this.fsSource));
  16046. if (cached) {
  16047. this.program = cached.program;
  16048. this.vs = cached.vs;
  16049. this.fs = cached.fs;
  16050. this.attributeLocations = cached.attributeLocations;
  16051. this.uniformLocations = cached.uniformLocations;
  16052. this.uniformBlocks = cached.uniformBlocks;
  16053. this.uniforms = cached.uniforms;
  16054. return;
  16055. } else {
  16056. this.vs = gl.createShader(gl.VERTEX_SHADER);
  16057. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  16058. this.program = gl.createProgram();
  16059. for (var name of Object.keys(attributeLocations)) {
  16060. var location = attributeLocations[name].location;
  16061. var glslName = attributeLocations[name].name;
  16062. gl.bindAttribLocation(this.program, location, glslName);
  16063. }
  16064. this.compileShader(this.vs, this.vsSource);
  16065. this.compileShader(this.fs, this.fsSource);
  16066. var program = this.program;
  16067. gl.attachShader(program, this.vs);
  16068. gl.attachShader(program, this.fs);
  16069. gl.linkProgram(program);
  16070. gl.detachShader(program, this.vs);
  16071. gl.detachShader(program, this.fs);
  16072. var success = gl.getProgramParameter(program, gl.LINK_STATUS);
  16073. if (!success) {
  16074. var info = gl.getProgramInfoLog(program);
  16075. throw "could not link program ".concat(this.name, ": ").concat(info);
  16076. }
  16077. {
  16078. // attribute locations
  16079. var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  16080. for (var i = 0; i < numAttributes; i++) {
  16081. var attribute = gl.getActiveAttrib(program, i);
  16082. var _location = gl.getAttribLocation(program, attribute.name);
  16083. this.attributeLocations[attribute.name] = _location;
  16084. }
  16085. }
  16086. {
  16087. // uniform locations
  16088. var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  16089. for (var _i = 0; _i < numUniforms; _i++) {
  16090. var uniform = gl.getActiveUniform(program, _i);
  16091. var _location2 = gl.getUniformLocation(program, uniform.name);
  16092. this.uniformLocations[uniform.name] = _location2;
  16093. this.uniforms[uniform.name] = {
  16094. location: _location2,
  16095. value: null
  16096. };
  16097. }
  16098. }
  16099. // uniform blocks
  16100. if (typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext) {
  16101. var numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  16102. for (var _i2 = 0; _i2 < numBlocks; _i2++) {
  16103. var blockName = gl.getActiveUniformBlockName(program, _i2);
  16104. var blockIndex = gl.getUniformBlockIndex(program, blockName);
  16105. this.uniformBlockIndices[blockName] = blockIndex;
  16106. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  16107. var dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  16108. var uBuffer = gl.createBuffer();
  16109. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  16110. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  16111. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  16112. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  16113. this.uniformBlocks[blockName] = {
  16114. name: blockName,
  16115. index: blockIndex,
  16116. dataSize: dataSize,
  16117. buffer: uBuffer
  16118. };
  16119. }
  16120. }
  16121. var _cached = {
  16122. program: this.program,
  16123. vs: this.vs,
  16124. fs: this.fs,
  16125. attributeLocations: this.attributeLocations,
  16126. uniformLocations: this.uniformLocations,
  16127. uniforms: this.uniforms,
  16128. uniformBlocks: this.uniformBlocks
  16129. };
  16130. this.cache.set("".concat(this.vsSource, ", ").concat(this.fsSource), _cached);
  16131. }
  16132. var tEnd = performance.now();
  16133. var duration = tEnd - tStart;
  16134. console.log("shader compile duration: ".concat(duration.toFixed(3)));
  16135. }
  16136. setUniformMatrix4(name, value) {
  16137. var gl = this.gl;
  16138. var location = this.uniformLocations[name];
  16139. if (location == null) {
  16140. return;
  16141. }
  16142. var tmp = new Float32Array(value.elements);
  16143. gl.uniformMatrix4fv(location, false, tmp);
  16144. }
  16145. setUniform1f(name, value) {
  16146. var gl = this.gl;
  16147. var uniform = this.uniforms[name];
  16148. if (uniform === undefined) {
  16149. return;
  16150. }
  16151. if (uniform.value === value) {
  16152. return;
  16153. }
  16154. uniform.value = value;
  16155. gl.uniform1f(uniform.location, value);
  16156. }
  16157. setUniformBoolean(name, value) {
  16158. var gl = this.gl;
  16159. var uniform = this.uniforms[name];
  16160. if (uniform === undefined) {
  16161. return;
  16162. }
  16163. if (uniform.value === value) {
  16164. return;
  16165. }
  16166. uniform.value = value;
  16167. gl.uniform1i(uniform.location, value);
  16168. }
  16169. setUniformTexture(name, value) {
  16170. var gl = this.gl;
  16171. var location = this.uniformLocations[name];
  16172. if (location == null) {
  16173. return;
  16174. }
  16175. gl.uniform1i(location, value);
  16176. }
  16177. setUniform2f(name, value) {
  16178. var gl = this.gl;
  16179. var location = this.uniformLocations[name];
  16180. if (location == null) {
  16181. return;
  16182. }
  16183. gl.uniform2f(location, value[0], value[1]);
  16184. }
  16185. setUniform3f(name, value) {
  16186. var gl = this.gl;
  16187. var location = this.uniformLocations[name];
  16188. if (location == null) {
  16189. return;
  16190. }
  16191. gl.uniform3f(location, value[0], value[1], value[2]);
  16192. }
  16193. setUniform(name, value) {
  16194. if (value.constructor === Matrix4) {
  16195. this.setUniformMatrix4(name, value);
  16196. } else if (typeof value === "number") {
  16197. this.setUniform1f(name, value);
  16198. } else if (typeof value === "boolean") {
  16199. this.setUniformBoolean(name, value);
  16200. } else if (value instanceof WebGLTexture) {
  16201. this.setUniformTexture(name, value);
  16202. } else if (value instanceof Array) {
  16203. if (value.length === 2) {
  16204. this.setUniform2f(name, value);
  16205. } else if (value.length === 3) {
  16206. this.setUniform3f(name, value);
  16207. }
  16208. } else {
  16209. console.error("unhandled uniform type: ", name, value);
  16210. }
  16211. }
  16212. setUniform1i(name, value) {
  16213. var gl = this.gl;
  16214. var location = this.uniformLocations[name];
  16215. if (location == null) {
  16216. return;
  16217. }
  16218. gl.uniform1i(location, value);
  16219. }
  16220. }
  16221. ;
  16222. class WebGLTexture {
  16223. constructor(gl, texture) {
  16224. this.gl = gl;
  16225. this.texture = texture;
  16226. this.id = gl.createTexture();
  16227. this.target = gl.TEXTURE_2D;
  16228. this.version = -1;
  16229. this.update(texture);
  16230. }
  16231. update() {
  16232. if (!this.texture.image) {
  16233. this.version = this.texture.version;
  16234. return;
  16235. }
  16236. var gl = this.gl;
  16237. var texture = this.texture;
  16238. if (this.version === texture.version) {
  16239. return;
  16240. }
  16241. this.target = gl.TEXTURE_2D;
  16242. gl.bindTexture(this.target, this.id);
  16243. var level = 0;
  16244. var internalFormat = paramThreeToGL(gl, texture.format);
  16245. var width = texture.image.width;
  16246. var height = texture.image.height;
  16247. var border = 0;
  16248. var srcFormat = internalFormat;
  16249. var srcType = paramThreeToGL(gl, texture.type);
  16250. var data;
  16251. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  16252. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  16253. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  16254. if (texture instanceof DataTexture) {
  16255. data = texture.image.data;
  16256. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16257. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16258. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  16259. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  16260. gl.texImage2D(this.target, level, internalFormat, width, height, border, srcFormat, srcType, data);
  16261. } else if (texture instanceof CanvasTexture || texture instanceof Texture) {
  16262. data = texture.image;
  16263. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL(gl, texture.wrapS));
  16264. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL(gl, texture.wrapT));
  16265. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL(gl, texture.magFilter));
  16266. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL(gl, texture.minFilter));
  16267. gl.texImage2D(this.target, level, internalFormat, internalFormat, srcType, data);
  16268. if (texture instanceof Texture) {
  16269. gl.generateMipmap(gl.TEXTURE_2D);
  16270. }
  16271. }
  16272. gl.bindTexture(this.target, null);
  16273. this.version = texture.version;
  16274. }
  16275. }
  16276. ;
  16277. class WebGLBuffer {
  16278. constructor() {
  16279. this.numElements = 0;
  16280. this.vao = null;
  16281. this.vbos = new Map();
  16282. }
  16283. }
  16284. ;
  16285. class Renderer {
  16286. constructor(threeRenderer) {
  16287. this.threeRenderer = threeRenderer;
  16288. this.gl = this.threeRenderer.getContext();
  16289. this.buffers = new Map();
  16290. this.shaders = new Map();
  16291. this.textures = new Map();
  16292. this.glTypeMapping = new Map();
  16293. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  16294. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  16295. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  16296. this.toggle = 0;
  16297. }
  16298. deleteBuffer(geometry) {
  16299. var gl = this.gl;
  16300. var webglBuffer = this.buffers.get(geometry);
  16301. if (webglBuffer != null) {
  16302. for (var attributeName in geometry.attributes) {
  16303. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  16304. }
  16305. this.buffers.delete(geometry);
  16306. }
  16307. }
  16308. createBuffer(geometry) {
  16309. var gl = this.gl;
  16310. var webglBuffer = new WebGLBuffer();
  16311. webglBuffer.vao = gl.createVertexArray();
  16312. webglBuffer.numElements = geometry.attributes.position.count;
  16313. gl.bindVertexArray(webglBuffer.vao);
  16314. for (var attributeName in geometry.attributes) {
  16315. var bufferAttribute = geometry.attributes[attributeName];
  16316. var vbo = gl.createBuffer();
  16317. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  16318. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  16319. var normalized = bufferAttribute.normalized;
  16320. var type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  16321. if (attributeLocations[attributeName] === undefined) {
  16322. //attributeLocation = attributeLocations["aExtra"];
  16323. } else {
  16324. var attributeLocation = attributeLocations[attributeName].location;
  16325. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  16326. gl.enableVertexAttribArray(attributeLocation);
  16327. }
  16328. webglBuffer.vbos.set(attributeName, {
  16329. handle: vbo,
  16330. name: attributeName,
  16331. count: bufferAttribute.count,
  16332. itemSize: bufferAttribute.itemSize,
  16333. type: geometry.attributes.position.array.constructor,
  16334. version: 0
  16335. });
  16336. }
  16337. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  16338. gl.bindVertexArray(null);
  16339. var disposeHandler = event => {
  16340. this.deleteBuffer(geometry);
  16341. geometry.removeEventListener("dispose", disposeHandler);
  16342. };
  16343. geometry.addEventListener("dispose", disposeHandler);
  16344. return webglBuffer;
  16345. }
  16346. updateBuffer(geometry) {
  16347. var gl = this.gl;
  16348. var webglBuffer = this.buffers.get(geometry);
  16349. gl.bindVertexArray(webglBuffer.vao);
  16350. for (var attributeName in geometry.attributes) {
  16351. var bufferAttribute = geometry.attributes[attributeName];
  16352. var normalized = bufferAttribute.normalized;
  16353. var type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  16354. var vbo = null;
  16355. if (!webglBuffer.vbos.has(attributeName)) {
  16356. vbo = gl.createBuffer();
  16357. webglBuffer.vbos.set(attributeName, {
  16358. handle: vbo,
  16359. name: attributeName,
  16360. count: bufferAttribute.count,
  16361. itemSize: bufferAttribute.itemSize,
  16362. type: geometry.attributes.position.array.constructor,
  16363. version: bufferAttribute.version
  16364. });
  16365. } else {
  16366. vbo = webglBuffer.vbos.get(attributeName).handle;
  16367. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  16368. }
  16369. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  16370. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  16371. if (attributeLocations[attributeName] === undefined) {
  16372. //attributeLocation = attributeLocations["aExtra"];
  16373. } else {
  16374. var attributeLocation = attributeLocations[attributeName].location;
  16375. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  16376. gl.enableVertexAttribArray(attributeLocation);
  16377. }
  16378. }
  16379. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  16380. gl.bindVertexArray(null);
  16381. }
  16382. traverse(scene) {
  16383. var octrees = [];
  16384. var stack = [scene];
  16385. while (stack.length > 0) {
  16386. var node = stack.pop();
  16387. if (node instanceof PointCloudTree) {
  16388. octrees.push(node);
  16389. continue;
  16390. }
  16391. var visibleChildren = node.children.filter(c => c.visible);
  16392. stack.push(...visibleChildren);
  16393. }
  16394. var result = {
  16395. octrees: octrees
  16396. };
  16397. return result;
  16398. }
  16399. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  16400. var _this = this;
  16401. if (exports.measureTimings) performance.mark("renderNodes-start");
  16402. var gl = this.gl;
  16403. var material = params.material ? params.material : octree.material;
  16404. var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  16405. var view = camera.matrixWorldInverse;
  16406. if (params.viewOverride) {
  16407. view = params.viewOverride;
  16408. }
  16409. var worldView = new Matrix4();
  16410. var mat4holder = new Float32Array(16);
  16411. var i = 0;
  16412. var _loop = function _loop() {
  16413. if (exports.debug.allowedNodes !== undefined) {
  16414. if (!exports.debug.allowedNodes.includes(node.name)) {
  16415. return 1; // continue
  16416. }
  16417. }
  16418. var world = node.sceneNode.matrixWorld;
  16419. worldView.multiplyMatrices(view, world);
  16420. if (visibilityTextureData) {
  16421. var vnStart = visibilityTextureData.offsets.get(node);
  16422. shader.setUniform1f("uVNStart", vnStart);
  16423. }
  16424. var level = node.getLevel();
  16425. if (node.debug) {
  16426. shader.setUniform("uDebug", true);
  16427. } else {
  16428. shader.setUniform("uDebug", false);
  16429. }
  16430. // let isLeaf = false;
  16431. // if(node instanceof PointCloudOctreeNode){
  16432. // isLeaf = Object.keys(node.children).length === 0;
  16433. // }else if(node instanceof PointCloudArena4DNode){
  16434. // isLeaf = node.geometryNode.isLeaf;
  16435. // }
  16436. // shader.setUniform("uIsLeafNode", isLeaf);
  16437. // let isLeaf = node.children.filter(n => n != null).length === 0;
  16438. // if(!isLeaf){
  16439. // continue;
  16440. // }
  16441. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  16442. var lModel = shader.uniformLocations["modelMatrix"];
  16443. if (lModel) {
  16444. mat4holder.set(world.elements);
  16445. gl.uniformMatrix4fv(lModel, false, mat4holder);
  16446. }
  16447. var lModelView = shader.uniformLocations["modelViewMatrix"];
  16448. //mat4holder.set(worldView.elements);
  16449. // faster then set in chrome 63
  16450. for (var j = 0; j < 16; j++) {
  16451. mat4holder[j] = worldView.elements[j];
  16452. }
  16453. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  16454. {
  16455. // Clip Polygons
  16456. if (material.clipPolygons && material.clipPolygons.length > 0) {
  16457. var clipPolygonVCount = [];
  16458. var worldViewProjMatrices = [];
  16459. for (var clipPolygon of material.clipPolygons) {
  16460. var _view = clipPolygon.viewMatrix;
  16461. var proj = clipPolygon.projMatrix;
  16462. var worldViewProj = proj.clone().multiply(_view).multiply(world);
  16463. clipPolygonVCount.push(clipPolygon.markers.length);
  16464. worldViewProjMatrices.push(worldViewProj);
  16465. }
  16466. var flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  16467. var flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  16468. for (var _i3 = 0; _i3 < material.clipPolygons.length; _i3++) {
  16469. var _clipPolygon = material.clipPolygons[_i3];
  16470. for (var _j = 0; _j < _clipPolygon.markers.length; _j++) {
  16471. flattenedVertices[_i3 * 24 + (_j * 3 + 0)] = _clipPolygon.markers[_j].position.x;
  16472. flattenedVertices[_i3 * 24 + (_j * 3 + 1)] = _clipPolygon.markers[_j].position.y;
  16473. flattenedVertices[_i3 * 24 + (_j * 3 + 2)] = _clipPolygon.markers[_j].position.z;
  16474. }
  16475. }
  16476. var lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  16477. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  16478. var lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  16479. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  16480. var lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  16481. gl.uniform3fv(lClipPolygons, flattenedVertices);
  16482. }
  16483. }
  16484. //shader.setUniformMatrix4("modelMatrix", world);
  16485. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  16486. shader.setUniform1f("uLevel", level);
  16487. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  16488. shader.setUniform1f("uPCIndex", i);
  16489. // uBBSize
  16490. if (shadowMaps.length > 0) {
  16491. var lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  16492. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  16493. var bindingStart = 5;
  16494. var bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => a + i);
  16495. gl.uniform1iv(lShadowMap, bindingPoints);
  16496. for (var _i4 = 0; _i4 < shadowMaps.length; _i4++) {
  16497. var shadowMap = shadowMaps[_i4];
  16498. var bindingPoint = bindingPoints[_i4];
  16499. var glTexture = _this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  16500. gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]);
  16501. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  16502. }
  16503. {
  16504. var worldViewMatrices = shadowMaps.map(sm => sm.camera.matrixWorldInverse).map(view => new Matrix4().multiplyMatrices(view, world));
  16505. var _flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  16506. var lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  16507. gl.uniformMatrix4fv(lWorldView, false, _flattenedMatrices);
  16508. }
  16509. {
  16510. var _flattenedMatrices2 = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  16511. var lProj = shader.uniformLocations["uShadowProj[0]"];
  16512. gl.uniformMatrix4fv(lProj, false, _flattenedMatrices2);
  16513. }
  16514. }
  16515. var geometry = node.geometryNode.geometry;
  16516. if (geometry.attributes["gps-time"]) {
  16517. var bufferAttribute = geometry.attributes["gps-time"];
  16518. var attGPS = octree.getAttribute("gps-time");
  16519. var initialRange = attGPS.initialRange;
  16520. var initialRangeSize = initialRange[1] - initialRange[0];
  16521. var globalRange = attGPS.range;
  16522. var globalRangeSize = globalRange[1] - globalRange[0];
  16523. var scale = initialRangeSize / globalRangeSize;
  16524. var offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  16525. scale = Number.isNaN(scale) ? 1 : scale;
  16526. offset = Number.isNaN(offset) ? 0 : offset;
  16527. shader.setUniform1f("uGpsScale", scale);
  16528. shader.setUniform1f("uGpsOffset", offset);
  16529. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  16530. var uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  16531. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  16532. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  16533. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  16534. var normalizedClipRange = [(uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize, (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize];
  16535. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  16536. // // ranges in full gps coordinate system
  16537. // const globalRange = attGPS.range;
  16538. // const bufferRange = bufferAttribute.potree.range;
  16539. // // ranges in [0, 1]
  16540. // // normalizedGlobalRange = [0, 1]
  16541. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  16542. // const globalWidth = globalRange[1] - globalRange[0];
  16543. // const normalizedBufferRange = [
  16544. // (bufferRange[0] - globalRange[0]) / globalWidth,
  16545. // (bufferRange[1] - globalRange[0]) / globalWidth,
  16546. // ];
  16547. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  16548. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  16549. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  16550. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  16551. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  16552. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  16553. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  16554. }
  16555. {
  16556. var uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  16557. var uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  16558. var uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  16559. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  16560. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  16561. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  16562. }
  16563. var webglBuffer = null;
  16564. if (!_this.buffers.has(geometry)) {
  16565. webglBuffer = _this.createBuffer(geometry);
  16566. _this.buffers.set(geometry, webglBuffer);
  16567. } else {
  16568. webglBuffer = _this.buffers.get(geometry);
  16569. for (var attributeName in geometry.attributes) {
  16570. var attribute = geometry.attributes[attributeName];
  16571. if (attribute.version > webglBuffer.vbos.get(attributeName).version) {
  16572. _this.updateBuffer(geometry);
  16573. }
  16574. }
  16575. }
  16576. gl.bindVertexArray(webglBuffer.vao);
  16577. var isExtraAttribute = attributeLocations[material.activeAttributeName] === undefined && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  16578. if (isExtraAttribute) {
  16579. var attributeLocation = attributeLocations["aExtra"].location;
  16580. for (var _attributeName in geometry.attributes) {
  16581. var _bufferAttribute = geometry.attributes[_attributeName];
  16582. var _vbo = webglBuffer.vbos.get(_attributeName);
  16583. gl.bindBuffer(gl.ARRAY_BUFFER, _vbo.handle);
  16584. gl.disableVertexAttribArray(attributeLocation);
  16585. }
  16586. var attName = material.activeAttributeName;
  16587. var _bufferAttribute2 = geometry.attributes[attName];
  16588. var vbo = webglBuffer.vbos.get(attName);
  16589. if (_bufferAttribute2 !== undefined && vbo !== undefined) {
  16590. var type = _this.glTypeMapping.get(_bufferAttribute2.array.constructor);
  16591. var normalized = _bufferAttribute2.normalized;
  16592. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  16593. gl.vertexAttribPointer(attributeLocation, _bufferAttribute2.itemSize, type, normalized, 0, 0);
  16594. gl.enableVertexAttribArray(attributeLocation);
  16595. }
  16596. {
  16597. var attExtra = octree.pcoGeometry.pointAttributes.attributes.find(a => a.name === attName);
  16598. var range = material.getRange(attName);
  16599. if (!range) {
  16600. range = attExtra.range;
  16601. }
  16602. if (!range) {
  16603. range = [0, 1];
  16604. }
  16605. var _initialRange = attExtra.initialRange;
  16606. var _initialRangeSize = _initialRange[1] - _initialRange[0];
  16607. var _globalRange = range;
  16608. var _globalRangeSize = _globalRange[1] - _globalRange[0];
  16609. var _scale = _initialRangeSize / _globalRangeSize;
  16610. var _offset = -(_globalRange[0] - _initialRange[0]) / _initialRangeSize;
  16611. _scale = Number.isNaN(_scale) ? 1 : _scale;
  16612. _offset = Number.isNaN(_offset) ? 0 : _offset;
  16613. shader.setUniform1f("uExtraScale", _scale);
  16614. shader.setUniform1f("uExtraOffset", _offset);
  16615. }
  16616. } else {
  16617. for (var _attributeName2 in geometry.attributes) {
  16618. var _bufferAttribute3 = geometry.attributes[_attributeName2];
  16619. var _vbo2 = webglBuffer.vbos.get(_attributeName2);
  16620. if (attributeLocations[_attributeName2] !== undefined) {
  16621. var _attributeLocation = attributeLocations[_attributeName2].location;
  16622. var _type = _this.glTypeMapping.get(_bufferAttribute3.array.constructor);
  16623. var _normalized = _bufferAttribute3.normalized;
  16624. gl.bindBuffer(gl.ARRAY_BUFFER, _vbo2.handle);
  16625. gl.vertexAttribPointer(_attributeLocation, _bufferAttribute3.itemSize, _type, _normalized, 0, 0);
  16626. gl.enableVertexAttribArray(_attributeLocation);
  16627. }
  16628. }
  16629. }
  16630. var numPoints = webglBuffer.numElements;
  16631. gl.drawArrays(gl.POINTS, 0, numPoints);
  16632. i++;
  16633. };
  16634. for (var node of nodes) {
  16635. if (_loop()) continue;
  16636. }
  16637. gl.bindVertexArray(null);
  16638. if (exports.measureTimings) {
  16639. performance.mark("renderNodes-end");
  16640. performance.measure("render.renderNodes", "renderNodes-start", "renderNodes-end");
  16641. }
  16642. }
  16643. renderOctree(octree, nodes, camera, target) {
  16644. var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  16645. var gl = this.gl;
  16646. var material = params.material ? params.material : octree.material;
  16647. var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  16648. var view = camera.matrixWorldInverse;
  16649. var viewInv = camera.matrixWorld;
  16650. if (params.viewOverride) {
  16651. view = params.viewOverride;
  16652. viewInv = view.clone().invert();
  16653. }
  16654. var proj = camera.projectionMatrix;
  16655. var projInv = proj.clone().invert();
  16656. //let worldView = new THREE.Matrix4();
  16657. var shader = null;
  16658. var visibilityTextureData = null;
  16659. var currentTextureBindingPoint = 0;
  16660. if (material.pointSizeType >= 0) {
  16661. if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  16662. var vnNodes = params.vnTextureNodes != null ? params.vnTextureNodes : nodes;
  16663. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  16664. var vnt = material.visibleNodesTexture;
  16665. var data = vnt.image.data;
  16666. data.set(visibilityTextureData.data);
  16667. vnt.needsUpdate = true;
  16668. }
  16669. }
  16670. {
  16671. // UPDATE SHADER AND TEXTURES
  16672. if (!this.shaders.has(material)) {
  16673. var [vs, fs] = [material.vertexShader, material.fragmentShader];
  16674. var _shader = new Shader(gl, "pointcloud", vs, fs);
  16675. this.shaders.set(material, _shader);
  16676. }
  16677. shader = this.shaders.get(material);
  16678. //if(material.needsUpdate){
  16679. {
  16680. var [_vs, _fs] = [material.vertexShader, material.fragmentShader];
  16681. var numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  16682. var numClipBoxes = material.clipBoxes && material.clipBoxes.length ? material.clipBoxes.length : 0;
  16683. var numClipSpheres = params.clipSpheres && params.clipSpheres.length ? params.clipSpheres.length : 0;
  16684. var numClipPolygons = material.clipPolygons && material.clipPolygons.length ? material.clipPolygons.length : 0;
  16685. var defines = ["#define num_shadowmaps ".concat(shadowMaps.length), "#define num_snapshots ".concat(numSnapshots), "#define num_clipboxes ".concat(numClipBoxes), "#define num_clipspheres ".concat(numClipSpheres), "#define num_clippolygons ".concat(numClipPolygons)];
  16686. if (octree.pcoGeometry.root.isLoaded()) {
  16687. var attributes = octree.pcoGeometry.root.geometry.attributes;
  16688. if (attributes["gps-time"]) {
  16689. defines.push("#define clip_gps_enabled");
  16690. }
  16691. if (attributes["return number"]) {
  16692. defines.push("#define clip_return_number_enabled");
  16693. }
  16694. if (attributes["number of returns"]) {
  16695. defines.push("#define clip_number_of_returns_enabled");
  16696. }
  16697. if (attributes["source id"] || attributes["point source id"]) {
  16698. defines.push("#define clip_point_source_id_enabled");
  16699. }
  16700. }
  16701. var definesString = defines.join("\n");
  16702. var vsVersionIndex = _vs.indexOf("#version ");
  16703. var fsVersionIndex = _fs.indexOf("#version ");
  16704. if (vsVersionIndex >= 0) {
  16705. _vs = _vs.replace(/(#version .*)/, "$1\n".concat(definesString));
  16706. } else {
  16707. _vs = "".concat(definesString, "\n").concat(_vs);
  16708. }
  16709. if (fsVersionIndex >= 0) {
  16710. _fs = _fs.replace(/(#version .*)/, "$1\n".concat(definesString));
  16711. } else {
  16712. _fs = "".concat(definesString, "\n").concat(_fs);
  16713. }
  16714. shader.update(_vs, _fs);
  16715. material.needsUpdate = false;
  16716. }
  16717. for (var uniformName of Object.keys(material.uniforms)) {
  16718. var uniform = material.uniforms[uniformName];
  16719. if (uniform.type == "t") {
  16720. var texture = uniform.value;
  16721. if (!texture) {
  16722. continue;
  16723. }
  16724. if (!this.textures.has(texture)) {
  16725. var webglTexture = new WebGLTexture(gl, texture);
  16726. this.textures.set(texture, webglTexture);
  16727. }
  16728. var webGLTexture = this.textures.get(texture);
  16729. webGLTexture.update();
  16730. }
  16731. }
  16732. }
  16733. gl.useProgram(shader.program);
  16734. var transparent = false;
  16735. if (params.transparent !== undefined) {
  16736. transparent = params.transparent && material.opacity < 1;
  16737. } else {
  16738. transparent = material.opacity < 1;
  16739. }
  16740. if (transparent) {
  16741. gl.enable(gl.BLEND);
  16742. gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
  16743. gl.depthMask(false);
  16744. gl.disable(gl.DEPTH_TEST);
  16745. } else {
  16746. gl.disable(gl.BLEND);
  16747. gl.depthMask(true);
  16748. gl.enable(gl.DEPTH_TEST);
  16749. }
  16750. if (params.blendFunc !== undefined) {
  16751. gl.enable(gl.BLEND);
  16752. gl.blendFunc(...params.blendFunc);
  16753. }
  16754. if (params.depthTest !== undefined) {
  16755. if (params.depthTest === true) {
  16756. gl.enable(gl.DEPTH_TEST);
  16757. } else {
  16758. gl.disable(gl.DEPTH_TEST);
  16759. }
  16760. }
  16761. if (params.depthWrite !== undefined) {
  16762. if (params.depthWrite === true) {
  16763. gl.depthMask(true);
  16764. } else {
  16765. gl.depthMask(false);
  16766. }
  16767. }
  16768. {
  16769. // UPDATE UNIFORMS
  16770. shader.setUniformMatrix4("projectionMatrix", proj);
  16771. shader.setUniformMatrix4("viewMatrix", view);
  16772. shader.setUniformMatrix4("uViewInv", viewInv);
  16773. shader.setUniformMatrix4("uProjInv", projInv);
  16774. var screenWidth = target ? target.width : material.screenWidth;
  16775. var screenHeight = target ? target.height : material.screenHeight;
  16776. shader.setUniform1f("uScreenWidth", screenWidth);
  16777. shader.setUniform1f("uScreenHeight", screenHeight);
  16778. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  16779. shader.setUniform1f("near", camera.near);
  16780. shader.setUniform1f("far", camera.far);
  16781. if (camera instanceof OrthographicCamera) {
  16782. shader.setUniform("uUseOrthographicCamera", true);
  16783. shader.setUniform("uOrthoWidth", camera.right - camera.left);
  16784. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  16785. } else {
  16786. shader.setUniform("uUseOrthographicCamera", false);
  16787. }
  16788. if (material.clipBoxes.length + material.clipPolygons.length === 0) {
  16789. shader.setUniform1i("clipTask", ClipTask.NONE);
  16790. } else {
  16791. shader.setUniform1i("clipTask", material.clipTask);
  16792. }
  16793. shader.setUniform1i("clipMethod", material.clipMethod);
  16794. if (material.clipBoxes && material.clipBoxes.length > 0) {
  16795. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  16796. //const lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  16797. //gl.uniformMatrix4fv(lClipBoxes, false, flattenedMatrices);
  16798. var lClipBoxes = shader.uniformLocations["clipBoxes[0]"];
  16799. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes.value);
  16800. }
  16801. // TODO CLIPSPHERES
  16802. if (params.clipSpheres && params.clipSpheres.length > 0) {
  16803. var clipSpheres = params.clipSpheres;
  16804. var matrices = [];
  16805. for (var clipSphere of clipSpheres) {
  16806. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  16807. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  16808. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  16809. var clipToWorld = clipSphere.matrixWorld;
  16810. var viewToWorld = camera.matrixWorld;
  16811. var worldToClip = clipToWorld.clone().invert();
  16812. var viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  16813. matrices.push(viewToClip);
  16814. }
  16815. var flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  16816. var lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  16817. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  16818. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  16819. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  16820. }
  16821. shader.setUniform1f("size", material.size);
  16822. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  16823. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  16824. // uniform float uPCIndex
  16825. shader.setUniform1f("uOctreeSpacing", material.spacing);
  16826. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  16827. //uniform vec3 uColor;
  16828. shader.setUniform3f("uColor", material.color.toArray());
  16829. //uniform float opacity;
  16830. shader.setUniform1f("uOpacity", material.opacity);
  16831. shader.setUniform2f("elevationRange", material.elevationRange);
  16832. shader.setUniform2f("intensityRange", material.intensityRange);
  16833. shader.setUniform3f("uIntensity_gbc", [material.intensityGamma, material.intensityBrightness, material.intensityContrast]);
  16834. shader.setUniform3f("uRGB_gbc", [material.rgbGamma, material.rgbBrightness, material.rgbContrast]);
  16835. shader.setUniform1f("uTransition", material.transition);
  16836. shader.setUniform1f("wRGB", material.weightRGB);
  16837. shader.setUniform1f("wIntensity", material.weightIntensity);
  16838. shader.setUniform1f("wElevation", material.weightElevation);
  16839. shader.setUniform1f("wClassification", material.weightClassification);
  16840. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  16841. shader.setUniform1f("wSourceID", material.weightSourceID);
  16842. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  16843. var vnWebGLTexture = this.textures.get(material.visibleNodesTexture);
  16844. if (vnWebGLTexture) {
  16845. shader.setUniform1i("visibleNodesTexture", currentTextureBindingPoint);
  16846. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  16847. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  16848. currentTextureBindingPoint++;
  16849. }
  16850. var gradientTexture = this.textures.get(material.gradientTexture);
  16851. shader.setUniform1i("gradient", currentTextureBindingPoint);
  16852. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  16853. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  16854. var repeat = material.elevationGradientRepeat;
  16855. if (repeat === ElevationGradientRepeat.REPEAT) {
  16856. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  16857. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  16858. } else if (repeat === ElevationGradientRepeat.MIRRORED_REPEAT) {
  16859. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  16860. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  16861. } else {
  16862. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16863. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16864. }
  16865. currentTextureBindingPoint++;
  16866. var classificationTexture = this.textures.get(material.classificationTexture);
  16867. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  16868. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  16869. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  16870. currentTextureBindingPoint++;
  16871. var matcapTexture = this.textures.get(material.matcapTexture);
  16872. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  16873. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  16874. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  16875. currentTextureBindingPoint++;
  16876. if (material.snapEnabled === true) {
  16877. {
  16878. var lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  16879. var lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  16880. var bindingStart = currentTextureBindingPoint;
  16881. var lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => a + i);
  16882. var lSnapshotDepthBindingPoints = new Array(5).fill(1 + Math.max(...lSnapshotBindingPoints)).map((a, i) => a + i);
  16883. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  16884. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  16885. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  16886. for (var i = 0; i < 5; i++) {
  16887. var _texture = material.uniforms["uSnapshot"].value[i];
  16888. var textureDepth = material.uniforms["uSnapshotDepth"].value[i];
  16889. if (!_texture) {
  16890. break;
  16891. }
  16892. var snapTexture = this.threeRenderer.properties.get(_texture).__webglTexture;
  16893. var snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  16894. var bindingPoint = lSnapshotBindingPoints[i];
  16895. var depthBindingPoint = lSnapshotDepthBindingPoints[i];
  16896. gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]);
  16897. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  16898. gl.activeTexture(gl["TEXTURE".concat(depthBindingPoint)]);
  16899. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  16900. }
  16901. }
  16902. {
  16903. var _flattenedMatrices3 = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  16904. var lSnapView = shader.uniformLocations["uSnapView[0]"];
  16905. gl.uniformMatrix4fv(lSnapView, false, _flattenedMatrices3);
  16906. }
  16907. {
  16908. var _flattenedMatrices4 = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  16909. var lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  16910. gl.uniformMatrix4fv(lSnapProj, false, _flattenedMatrices4);
  16911. }
  16912. {
  16913. var _flattenedMatrices5 = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  16914. var lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  16915. gl.uniformMatrix4fv(lSnapProjInv, false, _flattenedMatrices5);
  16916. }
  16917. {
  16918. var _flattenedMatrices6 = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  16919. var lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  16920. gl.uniformMatrix4fv(lSnapViewInv, false, _flattenedMatrices6);
  16921. }
  16922. }
  16923. }
  16924. this.renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params);
  16925. gl.activeTexture(gl.TEXTURE2);
  16926. gl.bindTexture(gl.TEXTURE_2D, null);
  16927. gl.activeTexture(gl.TEXTURE0);
  16928. }
  16929. render(scene, camera) {
  16930. var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  16931. var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  16932. var gl = this.gl;
  16933. // PREPARE
  16934. if (target != null) {
  16935. this.threeRenderer.setRenderTarget(target);
  16936. }
  16937. //camera.updateProjectionMatrix();
  16938. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  16939. var traversalResult = this.traverse(scene);
  16940. // RENDER
  16941. for (var octree of traversalResult.octrees) {
  16942. var nodes = octree.visibleNodes;
  16943. this.renderOctree(octree, nodes, camera, target, params);
  16944. }
  16945. // CLEANUP
  16946. gl.activeTexture(gl.TEXTURE1);
  16947. gl.bindTexture(gl.TEXTURE_2D, null);
  16948. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  16949. gl.bindVertexArray(null);
  16950. this.threeRenderer.resetState();
  16951. }
  16952. }
  16953. ;
  16954. function copyMaterial(source, target) {
  16955. for (var name of Object.keys(target.uniforms)) {
  16956. target.uniforms[name].value = source.uniforms[name].value;
  16957. }
  16958. target.gradientTexture = source.gradientTexture;
  16959. target.visibleNodesTexture = source.visibleNodesTexture;
  16960. target.classificationTexture = source.classificationTexture;
  16961. target.matcapTexture = source.matcapTexture;
  16962. target.activeAttributeName = source.activeAttributeName;
  16963. target.ranges = source.ranges;
  16964. //target.updateShaderSource();
  16965. }
  16966. class Batch {
  16967. constructor(geometry, material) {
  16968. this.geometry = geometry;
  16969. this.material = material;
  16970. this.sceneNode = new Points(geometry, material);
  16971. this.geometryNode = {
  16972. estimatedSpacing: 1.0,
  16973. geometry: geometry
  16974. };
  16975. }
  16976. getLevel() {
  16977. return 0;
  16978. }
  16979. }
  16980. class ProfileFakeOctree extends PointCloudTree {
  16981. constructor(octree) {
  16982. super();
  16983. this.trueOctree = octree;
  16984. this.pcoGeometry = octree.pcoGeometry;
  16985. this.points = [];
  16986. this.visibleNodes = [];
  16987. //this.material = this.trueOctree.material;
  16988. this.material = new PointCloudMaterial$1();
  16989. //this.material.copy(this.trueOctree.material);
  16990. copyMaterial(this.trueOctree.material, this.material);
  16991. this.material.pointSizeType = PointSizeType.FIXED;
  16992. this.batchSize = 100 * 1000;
  16993. this.currentBatch = null;
  16994. }
  16995. getAttribute(name) {
  16996. return this.trueOctree.getAttribute(name);
  16997. }
  16998. dispose() {
  16999. for (var node of this.visibleNodes) {
  17000. node.geometry.dispose();
  17001. }
  17002. this.visibleNodes = [];
  17003. this.currentBatch = null;
  17004. this.points = [];
  17005. }
  17006. addPoints(data) {
  17007. // since each call to addPoints can deliver very very few points,
  17008. // we're going to batch them into larger buffers for efficiency.
  17009. if (this.currentBatch === null) {
  17010. this.currentBatch = this.createNewBatch(data);
  17011. }
  17012. this.points.push(data);
  17013. var updateRange = {
  17014. start: this.currentBatch.geometry.drawRange.count,
  17015. count: 0
  17016. };
  17017. var projectedBox = new Box3();
  17018. var truePos = new Vector3();
  17019. for (var i = 0; i < data.numPoints; i++) {
  17020. if (updateRange.start + updateRange.count >= this.batchSize) {
  17021. // current batch full, start new batch
  17022. for (var key of Object.keys(this.currentBatch.geometry.attributes)) {
  17023. var attribute = this.currentBatch.geometry.attributes[key];
  17024. attribute.updateRange.offset = updateRange.start;
  17025. attribute.updateRange.count = updateRange.count;
  17026. attribute.needsUpdate = true;
  17027. }
  17028. this.currentBatch.geometry.computeBoundingBox();
  17029. this.currentBatch.geometry.computeBoundingSphere();
  17030. this.currentBatch = this.createNewBatch(data);
  17031. updateRange = {
  17032. start: 0,
  17033. count: 0
  17034. };
  17035. }
  17036. truePos.set(data.data.position[3 * i + 0] + this.trueOctree.position.x, data.data.position[3 * i + 1] + this.trueOctree.position.y, data.data.position[3 * i + 2] + this.trueOctree.position.z);
  17037. var x = data.data.mileage[i];
  17038. var y = 0;
  17039. var z = truePos.z;
  17040. projectedBox.expandByPoint(new Vector3(x, y, z));
  17041. var index = updateRange.start + updateRange.count;
  17042. var geometry = this.currentBatch.geometry;
  17043. for (var attributeName of Object.keys(data.data)) {
  17044. var source = data.data[attributeName];
  17045. var target = geometry.attributes[attributeName];
  17046. var numElements = target.itemSize;
  17047. for (var item = 0; item < numElements; item++) {
  17048. target.array[numElements * index + item] = source[numElements * i + item];
  17049. }
  17050. }
  17051. {
  17052. var position = geometry.attributes.position;
  17053. position.array[3 * index + 0] = x;
  17054. position.array[3 * index + 1] = y;
  17055. position.array[3 * index + 2] = z;
  17056. }
  17057. updateRange.count++;
  17058. this.currentBatch.geometry.drawRange.count++;
  17059. }
  17060. for (var _key of Object.keys(this.currentBatch.geometry.attributes)) {
  17061. var _attribute = this.currentBatch.geometry.attributes[_key];
  17062. _attribute.updateRange.offset = updateRange.start;
  17063. _attribute.updateRange.count = updateRange.count;
  17064. _attribute.needsUpdate = true;
  17065. }
  17066. data.projectedBox = projectedBox;
  17067. this.projectedBox = this.points.reduce((a, i) => a.union(i.projectedBox), new Box3());
  17068. }
  17069. createNewBatch(data) {
  17070. var geometry = new BufferGeometry();
  17071. // create new batches with batch_size elements of the same type as the attribute
  17072. for (var attributeName of Object.keys(data.data)) {
  17073. var buffer = data.data[attributeName];
  17074. var numElements = buffer.length / data.numPoints; // 3 for pos, 4 for col, 1 for scalars
  17075. var _constructor = buffer.constructor;
  17076. var normalized = false;
  17077. if (this.trueOctree.root.sceneNode) {
  17078. if (this.trueOctree.root.sceneNode.geometry.attributes[attributeName]) {
  17079. normalized = this.trueOctree.root.sceneNode.geometry.attributes[attributeName].normalized;
  17080. }
  17081. }
  17082. var batchBuffer = new _constructor(numElements * this.batchSize);
  17083. var bufferAttribute = new BufferAttribute(batchBuffer, numElements, normalized);
  17084. bufferAttribute.potree = {
  17085. range: [0, 1]
  17086. };
  17087. geometry.setAttribute(attributeName, bufferAttribute);
  17088. }
  17089. geometry.drawRange.start = 0;
  17090. geometry.drawRange.count = 0;
  17091. var batch = new Batch(geometry, this.material);
  17092. this.visibleNodes.push(batch);
  17093. return batch;
  17094. }
  17095. computeVisibilityTextureData() {
  17096. var data = new Uint8Array(this.visibleNodes.length * 4);
  17097. var offsets = new Map();
  17098. for (var i = 0; i < this.visibleNodes.length; i++) {
  17099. var node = this.visibleNodes[i];
  17100. offsets[node] = i;
  17101. }
  17102. return {
  17103. data: data,
  17104. offsets: offsets
  17105. };
  17106. }
  17107. }
  17108. class ProfileWindow extends EventDispatcher$1 {
  17109. constructor(viewer) {
  17110. super();
  17111. this.viewer = viewer;
  17112. this.elRoot = $('#profile_window');
  17113. this.renderArea = this.elRoot.find('#profileCanvasContainer');
  17114. this.svg = d3.select('svg#profileSVG');
  17115. this.mouseIsDown = false;
  17116. this.projectedBox = new Box3();
  17117. this.pointclouds = new Map();
  17118. this.numPoints = 0;
  17119. this.lastAddPointsTimestamp = undefined;
  17120. this.mouse = new Vector2(0, 0);
  17121. this.scale = new Vector3(1, 1, 1);
  17122. this.autoFitEnabled = true; // completely disable/enable
  17123. this.autoFit = false; // internal
  17124. var cwIcon = "".concat(exports.resourcePath, "/icons/arrow_cw.svg");
  17125. $('#potree_profile_rotate_cw').attr('src', cwIcon);
  17126. var ccwIcon = "".concat(exports.resourcePath, "/icons/arrow_ccw.svg");
  17127. $('#potree_profile_rotate_ccw').attr('src', ccwIcon);
  17128. var forwardIcon = "".concat(exports.resourcePath, "/icons/arrow_up.svg");
  17129. $('#potree_profile_move_forward').attr('src', forwardIcon);
  17130. var backwardIcon = "".concat(exports.resourcePath, "/icons/arrow_down.svg");
  17131. $('#potree_profile_move_backward').attr('src', backwardIcon);
  17132. var csvIcon = "".concat(exports.resourcePath, "/icons/file_csv_2d.svg");
  17133. $('#potree_download_csv_icon').attr('src', csvIcon);
  17134. var lasIcon = "".concat(exports.resourcePath, "/icons/file_las_3d.svg");
  17135. $('#potree_download_las_icon').attr('src', lasIcon);
  17136. var closeIcon = "".concat(exports.resourcePath, "/icons/close.svg");
  17137. $('#closeProfileContainer').attr("src", closeIcon);
  17138. this.initTHREE();
  17139. this.initSVG();
  17140. this.initListeners();
  17141. this.pRenderer = new Renderer(this.renderer);
  17142. this.elRoot.i18n();
  17143. }
  17144. initListeners() {
  17145. $(window).resize(() => {
  17146. if (this.enabled) {
  17147. this.render();
  17148. }
  17149. });
  17150. this.renderArea.mousedown(e => {
  17151. this.mouseIsDown = true;
  17152. });
  17153. this.renderArea.mouseup(e => {
  17154. this.mouseIsDown = false;
  17155. });
  17156. var viewerPickSphereSizeHandler = () => {
  17157. var camera = this.viewer.scene.getActiveCamera();
  17158. var domElement = this.viewer.renderer.domElement;
  17159. var distance = this.viewerPickSphere.position.distanceTo(camera.position);
  17160. var pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  17161. var scale = 10 / pr;
  17162. this.viewerPickSphere.scale.set(scale, scale, scale);
  17163. };
  17164. this.renderArea.mousemove(e => {
  17165. if (this.pointclouds.size === 0) {
  17166. return;
  17167. }
  17168. var rect = this.renderArea[0].getBoundingClientRect();
  17169. var x = e.clientX - rect.left;
  17170. var y = e.clientY - rect.top;
  17171. var newMouse = new Vector2(x, y);
  17172. if (this.mouseIsDown) {
  17173. // DRAG
  17174. this.autoFit = false;
  17175. this.lastDrag = new Date().getTime();
  17176. var cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  17177. var ncPos = [this.scaleX.invert(newMouse.x), this.scaleY.invert(newMouse.y)];
  17178. this.camera.position.x -= ncPos[0] - cPos[0];
  17179. this.camera.position.z -= ncPos[1] - cPos[1];
  17180. this.render();
  17181. } else if (this.pointclouds.size > 0) {
  17182. // FIND HOVERED POINT
  17183. var radius = Math.abs(this.scaleX.invert(0) - this.scaleX.invert(40));
  17184. var mileage = this.scaleX.invert(newMouse.x);
  17185. var elevation = this.scaleY.invert(newMouse.y);
  17186. var closest = this.selectPoint(mileage, elevation, radius);
  17187. if (closest) {
  17188. var point = closest.point;
  17189. var position = new Float64Array([point.position[0] + closest.pointcloud.position.x, point.position[1] + closest.pointcloud.position.y, point.position[2] + closest.pointcloud.position.z]);
  17190. this.elRoot.find('#profileSelectionProperties').fadeIn(200);
  17191. this.pickSphere.visible = true;
  17192. this.pickSphere.scale.set(0.5 * radius, 0.5 * radius, 0.5 * radius);
  17193. this.pickSphere.position.set(point.mileage, 0, position[2]);
  17194. this.viewerPickSphere.position.set(...position);
  17195. if (!this.viewer.scene.scene.children.includes(this.viewerPickSphere)) {
  17196. this.viewer.scene.scene.add(this.viewerPickSphere);
  17197. if (!this.viewer.hasEventListener("update", viewerPickSphereSizeHandler)) {
  17198. this.viewer.addEventListener("update", viewerPickSphereSizeHandler);
  17199. }
  17200. }
  17201. var info = this.elRoot.find('#profileSelectionProperties');
  17202. var html = '<table>';
  17203. var _loop = function _loop() {
  17204. var value = point[attributeName];
  17205. var attribute = closest.pointcloud.getAttribute(attributeName);
  17206. var transform = value => value;
  17207. if (attribute && attribute.type.size > 4) {
  17208. var range = attribute.initialRange;
  17209. var scale = 1 / (range[1] - range[0]);
  17210. var offset = range[0];
  17211. transform = value => value / scale + offset;
  17212. }
  17213. if (attributeName === 'position') {
  17214. var values = [...position].map(v => Utils.addCommas(v.toFixed(3)));
  17215. html += "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>x</td>\n\t\t\t\t\t\t\t\t\t<td>".concat(values[0], "</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>y</td>\n\t\t\t\t\t\t\t\t\t<td>").concat(values[1], "</td>\n\t\t\t\t\t\t\t\t</tr>\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>z</td>\n\t\t\t\t\t\t\t\t\t<td>").concat(values[2], "</td>\n\t\t\t\t\t\t\t\t</tr>");
  17216. } else if (attributeName === 'rgba') {
  17217. html += "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>".concat(attributeName, "</td>\n\t\t\t\t\t\t\t\t\t<td>").concat(value.join(', '), "</td>\n\t\t\t\t\t\t\t\t</tr>");
  17218. } else if (attributeName === 'normal') {
  17219. return 1; // continue
  17220. } else if (attributeName === 'mileage') {
  17221. html += "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>".concat(attributeName, "</td>\n\t\t\t\t\t\t\t\t\t<td>").concat(value.toFixed(3), "</td>\n\t\t\t\t\t\t\t\t</tr>");
  17222. } else {
  17223. html += "\n\t\t\t\t\t\t\t\t<tr>\n\t\t\t\t\t\t\t\t\t<td>".concat(attributeName, "</td>\n\t\t\t\t\t\t\t\t\t<td>").concat(transform(value), "</td>\n\t\t\t\t\t\t\t\t</tr>");
  17224. }
  17225. };
  17226. for (var attributeName of Object.keys(point)) {
  17227. if (_loop()) continue;
  17228. }
  17229. html += '</table>';
  17230. info.html(html);
  17231. this.selectedPoint = point;
  17232. } else {
  17233. // this.pickSphere.visible = false;
  17234. // this.selectedPoint = null;
  17235. this.viewer.scene.scene.add(this.viewerPickSphere);
  17236. var index = this.viewer.scene.scene.children.indexOf(this.viewerPickSphere);
  17237. if (index >= 0) {
  17238. this.viewer.scene.scene.children.splice(index, 1);
  17239. }
  17240. this.viewer.removeEventListener("update", viewerPickSphereSizeHandler);
  17241. }
  17242. this.render();
  17243. }
  17244. this.mouse.copy(newMouse);
  17245. });
  17246. var onWheel = e => {
  17247. this.autoFit = false;
  17248. var delta = 0;
  17249. if (e.wheelDelta !== undefined) {
  17250. // WebKit / Opera / Explorer 9
  17251. delta = e.wheelDelta;
  17252. } else if (e.detail !== undefined) {
  17253. // Firefox
  17254. delta = -e.detail;
  17255. }
  17256. var ndelta = Math.sign(delta);
  17257. var cPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  17258. if (ndelta > 0) {
  17259. // + 10%
  17260. this.scale.multiplyScalar(1.1);
  17261. } else {
  17262. // - 10%
  17263. this.scale.multiplyScalar(100 / 110);
  17264. }
  17265. this.updateScales();
  17266. var ncPos = [this.scaleX.invert(this.mouse.x), this.scaleY.invert(this.mouse.y)];
  17267. this.camera.position.x -= ncPos[0] - cPos[0];
  17268. this.camera.position.z -= ncPos[1] - cPos[1];
  17269. this.render();
  17270. this.updateScales();
  17271. };
  17272. $(this.renderArea)[0].addEventListener('mousewheel', onWheel, false);
  17273. $(this.renderArea)[0].addEventListener('DOMMouseScroll', onWheel, false); // Firefox
  17274. $('#closeProfileContainer').click(() => {
  17275. this.hide();
  17276. });
  17277. var getProfilePoints = () => {
  17278. var points = new Points$1();
  17279. for (var [pointcloud, entry] of this.pointclouds) {
  17280. for (var pointSet of entry.points) {
  17281. var originPos = pointSet.data.position;
  17282. var trueElevationPosition = new Float32Array(originPos);
  17283. for (var i = 0; i < pointSet.numPoints; i++) {
  17284. trueElevationPosition[3 * i + 2] += pointcloud.position.z;
  17285. }
  17286. pointSet.data.position = trueElevationPosition;
  17287. points.add(pointSet);
  17288. pointSet.data.position = originPos;
  17289. }
  17290. }
  17291. return points;
  17292. };
  17293. $('#potree_download_csv_icon').click(() => {
  17294. var points = getProfilePoints();
  17295. var string = CSVExporter.toString(points);
  17296. var blob = new Blob([string], {
  17297. type: "text/string"
  17298. });
  17299. $('#potree_download_profile_ortho_link').attr('href', URL.createObjectURL(blob));
  17300. });
  17301. $('#potree_download_las_icon').click(() => {
  17302. var points = getProfilePoints();
  17303. var buffer = LASExporter.toLAS(points);
  17304. var blob = new Blob([buffer], {
  17305. type: "application/octet-binary"
  17306. });
  17307. $('#potree_download_profile_link').attr('href', URL.createObjectURL(blob));
  17308. });
  17309. }
  17310. selectPoint(mileage, elevation, radius) {
  17311. var closest = {
  17312. distance: Infinity,
  17313. pointcloud: null,
  17314. points: null,
  17315. index: null
  17316. };
  17317. var pointBox = new Box2(new Vector2(mileage - radius, elevation - radius), new Vector2(mileage + radius, elevation + radius));
  17318. var numTested = 0;
  17319. var numSkipped = 0;
  17320. var numTestedPoints = 0;
  17321. var numSkippedPoints = 0;
  17322. for (var [pointcloud, entry] of this.pointclouds) {
  17323. for (var points of entry.points) {
  17324. var collisionBox = new Box2(new Vector2(points.projectedBox.min.x, points.projectedBox.min.z), new Vector2(points.projectedBox.max.x, points.projectedBox.max.z));
  17325. var intersects = collisionBox.intersectsBox(pointBox);
  17326. if (!intersects) {
  17327. numSkipped++;
  17328. numSkippedPoints += points.numPoints;
  17329. continue;
  17330. }
  17331. numTested++;
  17332. numTestedPoints += points.numPoints;
  17333. for (var i = 0; i < points.numPoints; i++) {
  17334. var m = points.data.mileage[i] - mileage;
  17335. var e = points.data.position[3 * i + 2] - elevation + pointcloud.position.z;
  17336. var r = Math.sqrt(m * m + e * e);
  17337. var withinDistance = r < radius && r < closest.distance;
  17338. var unfilteredClass = true;
  17339. if (points.data.classification) {
  17340. var classification = pointcloud.material.classification;
  17341. var pointClassID = points.data.classification[i];
  17342. var pointClassValue = classification[pointClassID];
  17343. if (pointClassValue && (!pointClassValue.visible || pointClassValue.color.w === 0)) {
  17344. unfilteredClass = false;
  17345. }
  17346. }
  17347. if (withinDistance && unfilteredClass) {
  17348. closest = {
  17349. distance: r,
  17350. pointcloud: pointcloud,
  17351. points: points,
  17352. index: i
  17353. };
  17354. }
  17355. }
  17356. }
  17357. }
  17358. //console.log(`nodes: ${numTested}, ${numSkipped} || points: ${numTestedPoints}, ${numSkippedPoints}`);
  17359. if (closest.distance < Infinity) {
  17360. var _points = closest.points;
  17361. var point = {};
  17362. var attributes = Object.keys(_points.data);
  17363. for (var attribute of attributes) {
  17364. var attributeData = _points.data[attribute];
  17365. var itemSize = attributeData.length / _points.numPoints;
  17366. var value = attributeData.subarray(itemSize * closest.index, itemSize * closest.index + itemSize);
  17367. if (value.length === 1) {
  17368. point[attribute] = value[0];
  17369. } else {
  17370. point[attribute] = value;
  17371. }
  17372. }
  17373. closest.point = point;
  17374. return closest;
  17375. } else {
  17376. return null;
  17377. }
  17378. }
  17379. initTHREE() {
  17380. this.renderer = new WebGLRenderer({
  17381. alpha: true,
  17382. premultipliedAlpha: false
  17383. });
  17384. this.renderer.setClearColor(0x000000, 0);
  17385. this.renderer.setSize(10, 10);
  17386. this.renderer.autoClear = false;
  17387. this.renderArea.append($(this.renderer.domElement));
  17388. this.renderer.domElement.tabIndex = '2222';
  17389. $(this.renderer.domElement).css('width', '100%');
  17390. $(this.renderer.domElement).css('height', '100%');
  17391. {
  17392. var gl = this.renderer.getContext();
  17393. if (gl.createVertexArray == null) {
  17394. var extVAO = gl.getExtension('OES_vertex_array_object');
  17395. if (!extVAO) {
  17396. throw new Error("OES_vertex_array_object extension not supported");
  17397. }
  17398. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  17399. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  17400. }
  17401. }
  17402. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  17403. this.camera.up.set(0, 0, 1);
  17404. this.camera.rotation.order = "ZXY";
  17405. this.camera.rotation.x = Math.PI / 2.0;
  17406. this.scene = new Scene();
  17407. this.profileScene = new Scene();
  17408. var sg = new SphereGeometry(1, 16, 16);
  17409. var sm = new MeshNormalMaterial();
  17410. this.pickSphere = new Mesh(sg, sm);
  17411. this.scene.add(this.pickSphere);
  17412. this.viewerPickSphere = new Mesh(sg, sm);
  17413. }
  17414. initSVG() {
  17415. var width = this.renderArea[0].clientWidth;
  17416. var height = this.renderArea[0].clientHeight;
  17417. var marginLeft = this.renderArea[0].offsetLeft;
  17418. this.svg.selectAll('*').remove();
  17419. this.scaleX = d3.scale.linear().domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x]).range([0, width]);
  17420. this.scaleY = d3.scale.linear().domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z]).range([height, 0]);
  17421. this.xAxis = d3.svg.axis().scale(this.scaleX).orient('bottom').innerTickSize(-height).outerTickSize(1).tickPadding(10).ticks(width / 50);
  17422. this.yAxis = d3.svg.axis().scale(this.scaleY).orient('left').innerTickSize(-width).outerTickSize(1).tickPadding(10).ticks(height / 20);
  17423. this.elXAxis = this.svg.append('g').attr('class', 'x axis').attr('transform', "translate(".concat(marginLeft, ", ").concat(height, ")")).call(this.xAxis);
  17424. this.elYAxis = this.svg.append('g').attr('class', 'y axis').attr('transform', "translate(".concat(marginLeft, ", 0)")).call(this.yAxis);
  17425. }
  17426. addPoints(pointcloud, points) {
  17427. if (points.numPoints === 0) {
  17428. return;
  17429. }
  17430. var entry = this.pointclouds.get(pointcloud);
  17431. if (!entry) {
  17432. entry = new ProfileFakeOctree(pointcloud);
  17433. this.pointclouds.set(pointcloud, entry);
  17434. this.profileScene.add(entry);
  17435. var materialChanged = () => {
  17436. this.render();
  17437. };
  17438. materialChanged();
  17439. pointcloud.material.addEventListener('material_property_changed', materialChanged);
  17440. this.addEventListener("on_reset_once", () => {
  17441. pointcloud.material.removeEventListener('material_property_changed', materialChanged);
  17442. });
  17443. }
  17444. entry.addPoints(points);
  17445. this.projectedBox.union(entry.projectedBox);
  17446. if (this.autoFit && this.autoFitEnabled) {
  17447. var width = this.renderArea[0].clientWidth;
  17448. var height = this.renderArea[0].clientHeight;
  17449. var size = this.projectedBox.getSize(new Vector3());
  17450. var sx = width / size.x;
  17451. var sy = height / size.z;
  17452. var scale = Math.min(sx, sy);
  17453. var center = this.projectedBox.getCenter(new Vector3());
  17454. this.scale.set(scale, scale, 1);
  17455. this.camera.position.copy(center);
  17456. //console.log("camera: ", this.camera.position.toArray().join(", "));
  17457. }
  17458. //console.log(entry);
  17459. this.render();
  17460. var numPoints = 0;
  17461. for (var [key, value] of this.pointclouds.entries()) {
  17462. numPoints += value.points.reduce((a, i) => a + i.numPoints, 0);
  17463. }
  17464. $("#profile_num_points").html(Utils.addCommas(numPoints));
  17465. }
  17466. reset() {
  17467. this.lastReset = new Date().getTime();
  17468. this.dispatchEvent({
  17469. type: "on_reset_once"
  17470. });
  17471. this.removeEventListeners("on_reset_once");
  17472. this.autoFit = true;
  17473. this.projectedBox = new Box3();
  17474. for (var [key, entry] of this.pointclouds) {
  17475. entry.dispose();
  17476. }
  17477. this.pointclouds.clear();
  17478. this.mouseIsDown = false;
  17479. this.mouse.set(0, 0);
  17480. if (this.autoFitEnabled) {
  17481. this.scale.set(1, 1, 1);
  17482. }
  17483. this.pickSphere.visible = false;
  17484. this.elRoot.find('#profileSelectionProperties').hide();
  17485. this.render();
  17486. }
  17487. show() {
  17488. this.elRoot.fadeIn();
  17489. this.enabled = true;
  17490. }
  17491. hide() {
  17492. this.elRoot.fadeOut();
  17493. this.enabled = false;
  17494. }
  17495. updateScales() {
  17496. var width = this.renderArea[0].clientWidth;
  17497. var height = this.renderArea[0].clientHeight;
  17498. var left = -width / 2 / this.scale.x;
  17499. var right = +width / 2 / this.scale.x;
  17500. var top = +height / 2 / this.scale.y;
  17501. var bottom = -height / 2 / this.scale.y;
  17502. this.camera.left = left;
  17503. this.camera.right = right;
  17504. this.camera.top = top;
  17505. this.camera.bottom = bottom;
  17506. this.camera.updateProjectionMatrix();
  17507. this.scaleX.domain([this.camera.left + this.camera.position.x, this.camera.right + this.camera.position.x]).range([0, width]);
  17508. this.scaleY.domain([this.camera.bottom + this.camera.position.z, this.camera.top + this.camera.position.z]).range([height, 0]);
  17509. var marginLeft = this.renderArea[0].offsetLeft;
  17510. this.xAxis.scale(this.scaleX).orient('bottom').innerTickSize(-height).outerTickSize(1).tickPadding(10).ticks(width / 50);
  17511. this.yAxis.scale(this.scaleY).orient('left').innerTickSize(-width).outerTickSize(1).tickPadding(10).ticks(height / 20);
  17512. this.elXAxis.attr('transform', "translate(".concat(marginLeft, ", ").concat(height, ")")).call(this.xAxis);
  17513. this.elYAxis.attr('transform', "translate(".concat(marginLeft, ", 0)")).call(this.yAxis);
  17514. }
  17515. requestScaleUpdate() {
  17516. var threshold = 100;
  17517. var allowUpdate = this.lastReset === undefined || this.lastScaleUpdate === undefined || new Date().getTime() - this.lastReset > threshold && new Date().getTime() - this.lastScaleUpdate > threshold;
  17518. if (allowUpdate) {
  17519. this.updateScales();
  17520. this.lastScaleUpdate = new Date().getTime();
  17521. this.scaleUpdatePending = false;
  17522. } else if (!this.scaleUpdatePending) {
  17523. setTimeout(this.requestScaleUpdate.bind(this), 100);
  17524. this.scaleUpdatePending = true;
  17525. }
  17526. }
  17527. render() {
  17528. var width = this.renderArea[0].clientWidth;
  17529. var height = this.renderArea[0].clientHeight;
  17530. var {
  17531. renderer,
  17532. pRenderer,
  17533. camera,
  17534. profileScene,
  17535. scene
  17536. } = this;
  17537. var {
  17538. scaleX,
  17539. pickSphere
  17540. } = this;
  17541. renderer.setSize(width, height);
  17542. renderer.setClearColor(0x000000, 0);
  17543. renderer.clear(true, true, false);
  17544. for (var pointcloud of this.pointclouds.keys()) {
  17545. var source = pointcloud.material;
  17546. var target = this.pointclouds.get(pointcloud).material;
  17547. copyMaterial(source, target);
  17548. target.size = 2;
  17549. }
  17550. pRenderer.render(profileScene, camera, null);
  17551. var radius = Math.abs(scaleX.invert(0) - scaleX.invert(5));
  17552. if (radius === 0) {
  17553. pickSphere.visible = false;
  17554. } else {
  17555. pickSphere.scale.set(radius, radius, radius);
  17556. pickSphere.visible = true;
  17557. }
  17558. renderer.render(scene, camera);
  17559. this.requestScaleUpdate();
  17560. }
  17561. }
  17562. ;
  17563. class ProfileWindowController {
  17564. constructor(viewer) {
  17565. this.viewer = viewer;
  17566. this.profileWindow = viewer.profileWindow;
  17567. this.profile = null;
  17568. this.numPoints = 0;
  17569. this.threshold = 60 * 1000;
  17570. this.rotateAmount = 10;
  17571. this.scheduledRecomputeTime = null;
  17572. this.enabled = true;
  17573. this.requests = [];
  17574. this._recompute = () => {
  17575. this.recompute();
  17576. };
  17577. this.viewer.addEventListener("scene_changed", e => {
  17578. e.oldScene.removeEventListener("pointcloud_added", this._recompute);
  17579. e.scene.addEventListener("pointcloud_added", this._recompute);
  17580. });
  17581. this.viewer.scene.addEventListener("pointcloud_added", this._recompute);
  17582. $("#potree_profile_rotate_amount").val(parseInt(this.rotateAmount));
  17583. $("#potree_profile_rotate_amount").on("input", e => {
  17584. var str = $("#potree_profile_rotate_amount").val();
  17585. if (!isNaN(str)) {
  17586. var value = parseFloat(str);
  17587. this.rotateAmount = value;
  17588. $("#potree_profile_rotate_amount").css("background-color", "");
  17589. } else {
  17590. $("#potree_profile_rotate_amount").css("background-color", "#ff9999");
  17591. }
  17592. });
  17593. var rotate = radians => {
  17594. var profile = this.profile;
  17595. var points = profile.points;
  17596. var start = points[0];
  17597. var end = points[points.length - 1];
  17598. var center = start.clone().add(end).multiplyScalar(0.5);
  17599. var mMoveOrigin = new Matrix4().makeTranslation(-center.x, -center.y, -center.z);
  17600. var mRotate = new Matrix4().makeRotationZ(radians);
  17601. var mMoveBack = new Matrix4().makeTranslation(center.x, center.y, center.z);
  17602. //const transform = mMoveOrigin.multiply(mRotate).multiply(mMoveBack);
  17603. var transform = mMoveBack.multiply(mRotate).multiply(mMoveOrigin);
  17604. var rotatedPoints = points.map(point => point.clone().applyMatrix4(transform));
  17605. this.profileWindow.autoFitEnabled = false;
  17606. for (var i = 0; i < points.length; i++) {
  17607. profile.setPosition(i, rotatedPoints[i]);
  17608. }
  17609. };
  17610. $("#potree_profile_rotate_cw").click(() => {
  17611. var radians = MathUtils.degToRad(this.rotateAmount);
  17612. rotate(-radians);
  17613. });
  17614. $("#potree_profile_rotate_ccw").click(() => {
  17615. var radians = MathUtils.degToRad(this.rotateAmount);
  17616. rotate(radians);
  17617. });
  17618. $("#potree_profile_move_forward").click(() => {
  17619. var profile = this.profile;
  17620. var points = profile.points;
  17621. var start = points[0];
  17622. var end = points[points.length - 1];
  17623. var dir = end.clone().sub(start).normalize();
  17624. var up = new Vector3(0, 0, 1);
  17625. var forward = up.cross(dir);
  17626. var move = forward.clone().multiplyScalar(profile.width / 2);
  17627. this.profileWindow.autoFitEnabled = false;
  17628. for (var i = 0; i < points.length; i++) {
  17629. profile.setPosition(i, points[i].clone().add(move));
  17630. }
  17631. });
  17632. $("#potree_profile_move_backward").click(() => {
  17633. var profile = this.profile;
  17634. var points = profile.points;
  17635. var start = points[0];
  17636. var end = points[points.length - 1];
  17637. var dir = end.clone().sub(start).normalize();
  17638. var up = new Vector3(0, 0, 1);
  17639. var forward = up.cross(dir);
  17640. var move = forward.clone().multiplyScalar(-profile.width / 2);
  17641. this.profileWindow.autoFitEnabled = false;
  17642. for (var i = 0; i < points.length; i++) {
  17643. profile.setPosition(i, points[i].clone().add(move));
  17644. }
  17645. });
  17646. }
  17647. setProfile(profile) {
  17648. if (this.profile !== null && this.profile !== profile) {
  17649. this.profile.removeEventListener('marker_moved', this._recompute);
  17650. this.profile.removeEventListener('marker_added', this._recompute);
  17651. this.profile.removeEventListener('marker_removed', this._recompute);
  17652. this.profile.removeEventListener('width_changed', this._recompute);
  17653. }
  17654. this.profile = profile;
  17655. {
  17656. this.profile.addEventListener('marker_moved', this._recompute);
  17657. this.profile.addEventListener('marker_added', this._recompute);
  17658. this.profile.addEventListener('marker_removed', this._recompute);
  17659. this.profile.addEventListener('width_changed', this._recompute);
  17660. }
  17661. this.recompute();
  17662. }
  17663. reset() {
  17664. this.profileWindow.reset();
  17665. this.numPoints = 0;
  17666. if (this.profile) {
  17667. for (var request of this.requests) {
  17668. request.cancel();
  17669. }
  17670. }
  17671. }
  17672. progressHandler(pointcloud, progress) {
  17673. for (var segment of progress.segments) {
  17674. this.profileWindow.addPoints(pointcloud, segment.points);
  17675. this.numPoints += segment.points.numPoints;
  17676. }
  17677. }
  17678. cancel() {
  17679. for (var request of this.requests) {
  17680. request.cancel();
  17681. // request.finishLevelThenCancel();
  17682. }
  17683. this.requests = [];
  17684. }
  17685. finishLevelThenCancel() {
  17686. for (var request of this.requests) {
  17687. request.finishLevelThenCancel();
  17688. }
  17689. this.requests = [];
  17690. }
  17691. recompute() {
  17692. var _this = this;
  17693. if (!this.profile) {
  17694. return;
  17695. }
  17696. if (this.scheduledRecomputeTime !== null && this.scheduledRecomputeTime > new Date().getTime()) {
  17697. return;
  17698. } else {
  17699. this.scheduledRecomputeTime = new Date().getTime() + 100;
  17700. }
  17701. this.scheduledRecomputeTime = null;
  17702. this.reset();
  17703. var _loop2 = function _loop2(pointcloud) {
  17704. var request = pointcloud.getPointsInProfile(_this.profile, null, {
  17705. 'onProgress': event => {
  17706. if (!_this.enabled) {
  17707. return;
  17708. }
  17709. _this.progressHandler(pointcloud, event.points);
  17710. if (_this.numPoints > _this.threshold) {
  17711. _this.finishLevelThenCancel();
  17712. }
  17713. },
  17714. 'onFinish': event => {
  17715. if (!_this.enabled) {}
  17716. },
  17717. 'onCancel': () => {
  17718. if (!_this.enabled) {}
  17719. }
  17720. });
  17721. _this.requests.push(request);
  17722. };
  17723. for (var pointcloud of this.viewer.scene.pointclouds.filter(p => p.visible)) {
  17724. _loop2(pointcloud);
  17725. }
  17726. }
  17727. }
  17728. ;
  17729. //import { EventDispatcher } from "../EventDispatcher.js";
  17730. class VolumeTool extends EventDispatcher {
  17731. constructor(viewer) {
  17732. super();
  17733. this.viewer = viewer;
  17734. this.renderer = viewer.renderer;
  17735. this.addEventListener('start_inserting_volume', e => {
  17736. this.viewer.dispatchEvent({
  17737. type: 'cancel_insertions'
  17738. });
  17739. });
  17740. this.scene = new Scene();
  17741. this.scene.name = 'scene_volume';
  17742. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  17743. this.onRemove = e => {
  17744. this.scene.remove(e.volume);
  17745. };
  17746. this.onAdd = e => {
  17747. this.scene.add(e.volume);
  17748. };
  17749. for (var volume of viewer.scene.volumes) {
  17750. this.onAdd({
  17751. volume: volume
  17752. });
  17753. }
  17754. this.viewer.inputHandler.addEventListener('delete', e => {
  17755. var volumes = e.selection.filter(e => e instanceof Volume);
  17756. volumes.forEach(e => this.viewer.scene.removeVolume(e));
  17757. });
  17758. viewer.addEventListener("update", this.update.bind(this));
  17759. viewer.addEventListener("render.pass.scene", e => this.render(e));
  17760. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  17761. viewer.scene.addEventListener('volume_added', this.onAdd);
  17762. viewer.scene.addEventListener('volume_removed', this.onRemove);
  17763. }
  17764. onSceneChange(e) {
  17765. if (e.oldScene) {
  17766. e.oldScene.removeEventListeners('volume_added', this.onAdd);
  17767. e.oldScene.removeEventListeners('volume_removed', this.onRemove);
  17768. }
  17769. e.scene.addEventListener('volume_added', this.onAdd);
  17770. e.scene.addEventListener('volume_removed', this.onRemove);
  17771. }
  17772. startInsertion() {
  17773. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  17774. var volume;
  17775. if (args.type) {
  17776. volume = new args.type();
  17777. } else {
  17778. volume = new BoxVolume();
  17779. }
  17780. volume.clip = args.clip || false;
  17781. volume.name = args.name || 'Volume';
  17782. this.dispatchEvent({
  17783. type: 'start_inserting_volume',
  17784. volume: volume
  17785. });
  17786. this.viewer.scene.addVolume(volume);
  17787. this.scene.add(volume);
  17788. var cancel = {
  17789. callback: null
  17790. };
  17791. var drag = e => {
  17792. var camera = this.viewer.scene.getActiveCamera();
  17793. var I = Utils.getMousePointCloudIntersection(e.drag.end, this.viewer.scene.getActiveCamera(), this.viewer, this.viewer.scene.pointclouds, {
  17794. pickClipped: false
  17795. });
  17796. if (I) {
  17797. volume.position.copy(I.location);
  17798. var wp = volume.getWorldPosition(new Vector3()).applyMatrix4(camera.matrixWorldInverse);
  17799. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  17800. var w = Math.abs(wp.z / 5);
  17801. volume.scale.set(w, w, w);
  17802. }
  17803. };
  17804. var drop = e => {
  17805. volume.removeEventListener('drag', drag);
  17806. volume.removeEventListener('drop', drop);
  17807. cancel.callback();
  17808. };
  17809. cancel.callback = e => {
  17810. volume.removeEventListener('drag', drag);
  17811. volume.removeEventListener('drop', drop);
  17812. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  17813. };
  17814. volume.addEventListener('drag', drag);
  17815. volume.addEventListener('drop', drop);
  17816. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  17817. this.viewer.inputHandler.startDragging(volume);
  17818. return volume;
  17819. }
  17820. update() {
  17821. if (!this.viewer.scene) {
  17822. return;
  17823. }
  17824. var camera = this.viewer.scene.getActiveCamera();
  17825. var renderAreaSize = this.viewer.renderer.getSize(new Vector2());
  17826. var clientWidth = renderAreaSize.width;
  17827. var clientHeight = renderAreaSize.height;
  17828. var volumes = this.viewer.scene.volumes;
  17829. for (var volume of volumes) {
  17830. var label = volume.label;
  17831. {
  17832. var distance = label.position.distanceTo(camera.position);
  17833. var pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  17834. var scale = 70 / pr;
  17835. label.scale.set(scale, scale, scale);
  17836. }
  17837. var calculatedVolume = volume.getVolume();
  17838. calculatedVolume = calculatedVolume / Math.pow(this.viewer.lengthUnit.unitspermeter, 3) * Math.pow(this.viewer.lengthUnitDisplay.unitspermeter, 3); //convert to cubic meters then to the cubic display unit
  17839. var text = Utils.addCommas(calculatedVolume.toFixed(3)) + ' ' + this.viewer.lengthUnitDisplay.code + '\u00B3';
  17840. label.setText(text);
  17841. }
  17842. }
  17843. render(params) {
  17844. var renderer = this.viewer.renderer;
  17845. var oldTarget = renderer.getRenderTarget();
  17846. if (params.renderTarget) {
  17847. renderer.setRenderTarget(params.renderTarget);
  17848. }
  17849. renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  17850. renderer.setRenderTarget(oldTarget);
  17851. }
  17852. }
  17853. /**
  17854. *
  17855. * code adapted from three.js BoxHelper.js
  17856. * https://github.com/mrdoob/three.js/blob/dev/src/helpers/BoxHelper.js
  17857. *
  17858. * @author mrdoob / http://mrdoob.com/
  17859. * @author Mugen87 / http://github.com/Mugen87
  17860. * @author mschuetz / http://potree.org
  17861. */
  17862. class Box3Helper$1 extends LineSegments {
  17863. constructor(box, color) {
  17864. var depthTest = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  17865. if (color === undefined) color = 0xffff00;
  17866. var indices = new Uint16Array([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7]);
  17867. var positions = new Float32Array([box.min.x, box.min.y, box.min.z, box.max.x, box.min.y, box.min.z, box.max.x, box.min.y, box.max.z, box.min.x, box.min.y, box.max.z, box.min.x, box.max.y, box.min.z, box.max.x, box.max.y, box.min.z, box.max.x, box.max.y, box.max.z, box.min.x, box.max.y, box.max.z]);
  17868. var geometry = new BufferGeometry();
  17869. geometry.setIndex(new BufferAttribute(indices, 1));
  17870. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  17871. var material = new LineBasicMaterial({
  17872. color: color,
  17873. depthTest
  17874. });
  17875. super(geometry, material);
  17876. }
  17877. }
  17878. var KeyCodes = {
  17879. LEFT: 37,
  17880. UP: 38,
  17881. RIGHT: 39,
  17882. BOTTOM: 40,
  17883. DELETE: 46,
  17884. A: 'A'.charCodeAt(0),
  17885. S: 'S'.charCodeAt(0),
  17886. D: 'D'.charCodeAt(0),
  17887. W: 'W'.charCodeAt(0),
  17888. Q: 'Q'.charCodeAt(0),
  17889. E: 'E'.charCodeAt(0),
  17890. R: 'R'.charCodeAt(0),
  17891. F: 'F'.charCodeAt(0)
  17892. };
  17893. class NormalizationMaterial extends RawShaderMaterial {
  17894. constructor() {
  17895. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  17896. super();
  17897. var uniforms = {
  17898. uDepthMap: {
  17899. type: 't',
  17900. value: null
  17901. },
  17902. uWeightMap: {
  17903. type: 't',
  17904. value: null
  17905. }
  17906. };
  17907. this.setValues({
  17908. uniforms: uniforms,
  17909. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  17910. fragmentShader: this.getDefines() + Shaders['normalize.fs']
  17911. });
  17912. }
  17913. getDefines() {
  17914. var defines = '';
  17915. return defines;
  17916. }
  17917. updateShaderSource() {
  17918. var vs = this.getDefines() + Shaders['normalize.vs'];
  17919. var fs = this.getDefines() + Shaders['normalize.fs'];
  17920. this.setValues({
  17921. vertexShader: vs,
  17922. fragmentShader: fs
  17923. });
  17924. this.needsUpdate = true;
  17925. }
  17926. }
  17927. class NormalizationEDLMaterial extends RawShaderMaterial {
  17928. constructor() {
  17929. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  17930. super();
  17931. var uniforms = {
  17932. screenWidth: {
  17933. type: 'f',
  17934. value: 0
  17935. },
  17936. screenHeight: {
  17937. type: 'f',
  17938. value: 0
  17939. },
  17940. edlStrength: {
  17941. type: 'f',
  17942. value: 1.0
  17943. },
  17944. radius: {
  17945. type: 'f',
  17946. value: 1.0
  17947. },
  17948. neighbours: {
  17949. type: '2fv',
  17950. value: []
  17951. },
  17952. uEDLMap: {
  17953. type: 't',
  17954. value: null
  17955. },
  17956. uDepthMap: {
  17957. type: 't',
  17958. value: null
  17959. },
  17960. uWeightMap: {
  17961. type: 't',
  17962. value: null
  17963. }
  17964. };
  17965. this.setValues({
  17966. uniforms: uniforms,
  17967. vertexShader: this.getDefines() + Shaders['normalize.vs'],
  17968. fragmentShader: this.getDefines() + Shaders['normalize_and_edl.fs']
  17969. });
  17970. this.neighbourCount = 8;
  17971. }
  17972. getDefines() {
  17973. var defines = '';
  17974. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  17975. return defines;
  17976. }
  17977. updateShaderSource() {
  17978. var vs = this.getDefines() + Shaders['normalize.vs'];
  17979. var fs = this.getDefines() + Shaders['normalize_and_edl.fs'];
  17980. this.setValues({
  17981. vertexShader: vs,
  17982. fragmentShader: fs
  17983. });
  17984. this.uniforms.neighbours.value = this.neighbours;
  17985. this.needsUpdate = true;
  17986. }
  17987. get neighbourCount() {
  17988. return this._neighbourCount;
  17989. }
  17990. set neighbourCount(value) {
  17991. if (this._neighbourCount !== value) {
  17992. this._neighbourCount = value;
  17993. this.neighbours = new Float32Array(this._neighbourCount * 2);
  17994. for (var c = 0; c < this._neighbourCount; c++) {
  17995. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  17996. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  17997. }
  17998. this.updateShaderSource();
  17999. }
  18000. }
  18001. }
  18002. //在potree.shim中修改。 。official中用不到且有bug
  18003. class HQSplatRenderer {
  18004. constructor(viewer) {
  18005. this.viewer = viewer;
  18006. this.depthMaterials = new Map();
  18007. this.attributeMaterials = new Map();
  18008. this.normalizationMaterial = null;
  18009. this.rtDepth = null;
  18010. this.rtAttribute = null;
  18011. this.gl = viewer.renderer.getContext();
  18012. this.initialized = false;
  18013. }
  18014. init() {
  18015. if (this.initialized) {
  18016. return;
  18017. }
  18018. this.normalizationMaterial = new NormalizationMaterial();
  18019. this.normalizationMaterial.depthTest = true;
  18020. this.normalizationMaterial.depthWrite = true;
  18021. this.normalizationMaterial.transparent = true;
  18022. this.normalizationEDLMaterial = new NormalizationEDLMaterial();
  18023. this.normalizationEDLMaterial.depthTest = true;
  18024. this.normalizationEDLMaterial.depthWrite = true;
  18025. this.normalizationEDLMaterial.transparent = true;
  18026. this.rtDepth = new WebGLRenderTarget(1024, 1024, {
  18027. minFilter: NearestFilter,
  18028. magFilter: NearestFilter,
  18029. format: RGBAFormat,
  18030. type: FloatType,
  18031. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  18032. });
  18033. this.rtAttribute = new WebGLRenderTarget(1024, 1024, {
  18034. minFilter: NearestFilter,
  18035. magFilter: NearestFilter,
  18036. format: RGBAFormat,
  18037. type: FloatType,
  18038. depthTexture: this.rtDepth.depthTexture
  18039. });
  18040. this.initialized = true;
  18041. }
  18042. resize(width, height) {
  18043. this.rtDepth.setSize(width, height);
  18044. this.rtAttribute.setSize(width, height);
  18045. }
  18046. clearTargets() {
  18047. var viewer = this.viewer;
  18048. var {
  18049. renderer
  18050. } = viewer;
  18051. var oldTarget = renderer.getRenderTarget();
  18052. renderer.setClearColor(0x000000, 0);
  18053. renderer.setRenderTarget(this.rtDepth);
  18054. renderer.clear(true, true, true);
  18055. renderer.setRenderTarget(this.rtAttribute);
  18056. renderer.clear(true, true, true);
  18057. renderer.setRenderTarget(oldTarget);
  18058. }
  18059. clear() {
  18060. this.init();
  18061. var {
  18062. renderer,
  18063. background
  18064. } = this.viewer;
  18065. if (background === "skybox") {
  18066. renderer.setClearColor(0x000000, 0);
  18067. } else if (background === 'gradient') {
  18068. renderer.setClearColor(0x000000, 0);
  18069. } else if (background === 'black') {
  18070. renderer.setClearColor(0x000000, 1);
  18071. } else if (background === 'white') {
  18072. renderer.setClearColor(0xFFFFFF, 1);
  18073. } else {
  18074. renderer.setClearColor(0x000000, 0);
  18075. }
  18076. renderer.clear();
  18077. this.clearTargets();
  18078. }
  18079. render(params) {
  18080. this.init();
  18081. var viewer = this.viewer;
  18082. var camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  18083. var {
  18084. width,
  18085. height
  18086. } = this.viewer.renderer.getSize(new Vector2());
  18087. viewer.dispatchEvent({
  18088. type: "render.pass.begin",
  18089. viewer: viewer
  18090. });
  18091. this.resize(width, height);
  18092. var visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  18093. var originalMaterials = new Map();
  18094. for (var pointcloud of visiblePointClouds) {
  18095. originalMaterials.set(pointcloud, pointcloud.material);
  18096. if (!this.attributeMaterials.has(pointcloud)) {
  18097. var attributeMaterial = new PointCloudMaterial$1();
  18098. this.attributeMaterials.set(pointcloud, attributeMaterial);
  18099. }
  18100. if (!this.depthMaterials.has(pointcloud)) {
  18101. var depthMaterial = new PointCloudMaterial$1();
  18102. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  18103. depthMaterial.setDefine("use_edl", "#define use_edl");
  18104. this.depthMaterials.set(pointcloud, depthMaterial);
  18105. }
  18106. }
  18107. {
  18108. // DEPTH PASS
  18109. for (var _pointcloud of visiblePointClouds) {
  18110. var octreeSize = _pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  18111. var material = originalMaterials.get(_pointcloud);
  18112. var _depthMaterial = this.depthMaterials.get(_pointcloud);
  18113. _depthMaterial.size = material.size;
  18114. _depthMaterial.minSize = material.minSize;
  18115. _depthMaterial.maxSize = material.maxSize;
  18116. _depthMaterial.pointSizeType = material.pointSizeType;
  18117. _depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  18118. _depthMaterial.weighted = false;
  18119. _depthMaterial.screenWidth = width;
  18120. _depthMaterial.shape = PointShape$1.CIRCLE;
  18121. _depthMaterial.screenHeight = height;
  18122. _depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  18123. _depthMaterial.uniforms.octreeSize.value = octreeSize;
  18124. _depthMaterial.spacing = _pointcloud.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  18125. _depthMaterial.classification = material.classification;
  18126. _depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  18127. _depthMaterial.classificationTexture.needsUpdate = true;
  18128. _depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  18129. _depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  18130. _depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  18131. _depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  18132. _depthMaterial.clipTask = material.clipTask;
  18133. _depthMaterial.clipMethod = material.clipMethod;
  18134. _depthMaterial.setClipBoxes(material.clipBoxes);
  18135. _depthMaterial.setClipPolygons(material.clipPolygons);
  18136. _pointcloud.material = _depthMaterial;
  18137. }
  18138. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtDepth, {
  18139. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1)
  18140. });
  18141. }
  18142. {
  18143. // ATTRIBUTE PASS
  18144. for (var _pointcloud2 of visiblePointClouds) {
  18145. var _octreeSize = _pointcloud2.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  18146. var _material = originalMaterials.get(_pointcloud2);
  18147. var _attributeMaterial = this.attributeMaterials.get(_pointcloud2);
  18148. _attributeMaterial.size = _material.size;
  18149. _attributeMaterial.minSize = _material.minSize;
  18150. _attributeMaterial.maxSize = _material.maxSize;
  18151. _attributeMaterial.pointSizeType = _material.pointSizeType;
  18152. _attributeMaterial.activeAttributeName = _material.activeAttributeName;
  18153. _attributeMaterial.visibleNodesTexture = _material.visibleNodesTexture;
  18154. _attributeMaterial.weighted = true;
  18155. _attributeMaterial.screenWidth = width;
  18156. _attributeMaterial.screenHeight = height;
  18157. _attributeMaterial.shape = PointShape$1.CIRCLE;
  18158. _attributeMaterial.uniforms.visibleNodes.value = _material.visibleNodesTexture;
  18159. _attributeMaterial.uniforms.octreeSize.value = _octreeSize;
  18160. _attributeMaterial.spacing = _pointcloud2.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  18161. _attributeMaterial.classification = _material.classification;
  18162. _attributeMaterial.uniforms.classificationLUT.value.image.data = _material.uniforms.classificationLUT.value.image.data;
  18163. _attributeMaterial.classificationTexture.needsUpdate = true;
  18164. _attributeMaterial.uniforms.uFilterReturnNumberRange.value = _material.uniforms.uFilterReturnNumberRange.value;
  18165. _attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = _material.uniforms.uFilterNumberOfReturnsRange.value;
  18166. _attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = _material.uniforms.uFilterGPSTimeClipRange.value;
  18167. _attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = _material.uniforms.uFilterPointSourceIDClipRange.value;
  18168. _attributeMaterial.elevationGradientRepeat = _material.elevationGradientRepeat;
  18169. _attributeMaterial.elevationRange = _material.elevationRange;
  18170. _attributeMaterial.gradient = _material.gradient;
  18171. _attributeMaterial.matcap = _material.matcap;
  18172. _attributeMaterial.intensityRange = _material.intensityRange;
  18173. _attributeMaterial.intensityGamma = _material.intensityGamma;
  18174. _attributeMaterial.intensityContrast = _material.intensityContrast;
  18175. _attributeMaterial.intensityBrightness = _material.intensityBrightness;
  18176. _attributeMaterial.rgbGamma = _material.rgbGamma;
  18177. _attributeMaterial.rgbContrast = _material.rgbContrast;
  18178. _attributeMaterial.rgbBrightness = _material.rgbBrightness;
  18179. _attributeMaterial.weightRGB = _material.weightRGB;
  18180. _attributeMaterial.weightIntensity = _material.weightIntensity;
  18181. _attributeMaterial.weightElevation = _material.weightElevation;
  18182. _attributeMaterial.weightRGB = _material.weightRGB;
  18183. _attributeMaterial.weightClassification = _material.weightClassification;
  18184. _attributeMaterial.weightReturnNumber = _material.weightReturnNumber;
  18185. _attributeMaterial.weightSourceID = _material.weightSourceID;
  18186. _attributeMaterial.color = _material.color;
  18187. _attributeMaterial.clipTask = _material.clipTask;
  18188. _attributeMaterial.clipMethod = _material.clipMethod;
  18189. _attributeMaterial.setClipBoxes(_material.clipBoxes);
  18190. _attributeMaterial.setClipPolygons(_material.clipPolygons);
  18191. _pointcloud2.material = _attributeMaterial;
  18192. }
  18193. var gl = this.gl;
  18194. viewer.renderer.setRenderTarget(null);
  18195. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  18196. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1),
  18197. //material: this.attributeMaterial,
  18198. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  18199. //depthTest: false,
  18200. depthWrite: false
  18201. });
  18202. }
  18203. for (var [_pointcloud3, _material2] of originalMaterials) {
  18204. _pointcloud3.material = _material2;
  18205. }
  18206. viewer.renderer.setRenderTarget(null);
  18207. if (viewer.background === "skybox") {
  18208. viewer.renderer.setClearColor(0x000000, 0);
  18209. viewer.renderer.clear();
  18210. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  18211. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  18212. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  18213. viewer.skybox.parent.rotation.x = 0;
  18214. viewer.skybox.parent.updateMatrixWorld();
  18215. viewer.skybox.camera.updateProjectionMatrix();
  18216. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  18217. } else if (viewer.background === 'gradient') {
  18218. viewer.renderer.setClearColor(0x000000, 0);
  18219. viewer.renderer.clear();
  18220. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  18221. } else if (viewer.background === 'black') {
  18222. viewer.renderer.setClearColor(0x000000, 1);
  18223. viewer.renderer.clear();
  18224. } else if (viewer.background === 'white') {
  18225. viewer.renderer.setClearColor(0xFFFFFF, 1);
  18226. viewer.renderer.clear();
  18227. } else {
  18228. viewer.renderer.setClearColor(0x000000, 0);
  18229. viewer.renderer.clear();
  18230. }
  18231. {
  18232. // NORMALIZATION PASS
  18233. var normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  18234. if (this.useEDL) {
  18235. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  18236. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  18237. normalizationMaterial.uniforms.screenWidth.value = width;
  18238. normalizationMaterial.uniforms.screenHeight.value = height;
  18239. normalizationMaterial.uniforms.uEDLMap.value = this.rtDepth.texture;
  18240. }
  18241. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  18242. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  18243. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  18244. }
  18245. viewer.renderer.render(viewer.scene.scene, camera);
  18246. viewer.dispatchEvent({
  18247. type: "render.pass.scene",
  18248. viewer: viewer
  18249. });
  18250. viewer.renderer.clearDepth();
  18251. viewer.transformationTool.update();
  18252. viewer.dispatchEvent({
  18253. type: "render.pass.perspective_overlay",
  18254. viewer: viewer
  18255. });
  18256. viewer.renderer.render(viewer.controls.sceneControls, camera);
  18257. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  18258. viewer.renderer.render(viewer.transformationTool.scene, camera);
  18259. viewer.renderer.setViewport(width - viewer.navigationCube.width, height - viewer.navigationCube.width, viewer.navigationCube.width, viewer.navigationCube.width);
  18260. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  18261. viewer.renderer.setViewport(0, 0, width, height);
  18262. viewer.dispatchEvent({
  18263. type: "render.pass.end",
  18264. viewer: viewer
  18265. });
  18266. }
  18267. }
  18268. class LRUItem {
  18269. constructor(node) {
  18270. this.previous = null;
  18271. this.next = null;
  18272. this.node = node;
  18273. }
  18274. }
  18275. /**
  18276. *
  18277. * @class A doubly-linked-list of the least recently used elements.
  18278. */
  18279. class LRU {
  18280. constructor() {
  18281. //类似链表存储
  18282. // the least recently used item
  18283. this.first = null;
  18284. // the most recently used item
  18285. this.last = null;
  18286. // a list of all items in the lru list
  18287. this.items = {}; //按node的id存储。(id为0的就是root,name='r')
  18288. this.elements = 0;
  18289. this.numPoints = 0;
  18290. }
  18291. size() {
  18292. return this.elements;
  18293. }
  18294. contains(node) {
  18295. return this.items[node.id] == null;
  18296. }
  18297. touch(node) {
  18298. //链接node,并且永远放在最后. (每次updatePointClouds都要刷新一次链表)
  18299. if (!node.loaded) {
  18300. return;
  18301. }
  18302. var item;
  18303. if (this.items[node.id] == null) {
  18304. // add to list
  18305. item = new LRUItem(node);
  18306. item.previous = this.last;
  18307. this.last = item;
  18308. if (item.previous !== null) {
  18309. item.previous.next = item;
  18310. }
  18311. this.items[node.id] = item;
  18312. this.elements++;
  18313. if (this.first === null) {
  18314. this.first = item;
  18315. }
  18316. this.numPoints += node.numPoints;
  18317. } else {
  18318. // update in list
  18319. item = this.items[node.id];
  18320. if (item.previous === null) {
  18321. // handle touch on first element
  18322. if (item.next !== null) {
  18323. this.first = item.next;
  18324. this.first.previous = null;
  18325. item.previous = this.last;
  18326. item.next = null;
  18327. this.last = item;
  18328. item.previous.next = item;
  18329. }
  18330. } else if (item.next === null) {
  18331. // handle touch on last element
  18332. } else {
  18333. //从原来的位置挑出放最后
  18334. // handle touch on any other element
  18335. item.previous.next = item.next;
  18336. item.next.previous = item.previous;
  18337. item.previous = this.last;
  18338. item.next = null;
  18339. this.last = item;
  18340. item.previous.next = item;
  18341. }
  18342. }
  18343. }
  18344. //因为需要显示的都放末尾,所以不显示的部分都在前面,删除时从头删除。(但并不代表开头的一定是不显示的,所以如果第一个仍是显示的,它很可能是root,也就是name='r'的nodeGeo,删除它也就会删除全部)
  18345. remove(node) {
  18346. var lruItem = this.items[node.id];
  18347. if (lruItem) {
  18348. if (this.elements === 1) {
  18349. this.first = null;
  18350. this.last = null;
  18351. } else {
  18352. if (!lruItem.previous) {
  18353. this.first = lruItem.next;
  18354. this.first.previous = null;
  18355. }
  18356. if (!lruItem.next) {
  18357. this.last = lruItem.previous;
  18358. this.last.next = null;
  18359. }
  18360. if (lruItem.previous && lruItem.next) {
  18361. lruItem.previous.next = lruItem.next;
  18362. lruItem.next.previous = lruItem.previous;
  18363. }
  18364. }
  18365. delete this.items[node.id];
  18366. this.elements--;
  18367. this.numPoints -= node.numPoints;
  18368. }
  18369. }
  18370. getLRUItem() {
  18371. if (this.first === null) {
  18372. return null;
  18373. }
  18374. var lru = this.first;
  18375. return lru.node;
  18376. }
  18377. toString() {
  18378. var string = '{ ';
  18379. var curr = this.first;
  18380. while (curr !== null) {
  18381. string += curr.node.id;
  18382. if (curr.next !== null) {
  18383. string += ', ';
  18384. }
  18385. curr = curr.next;
  18386. }
  18387. string += '}';
  18388. string += '(' + this.size() + ')';
  18389. return string;
  18390. }
  18391. freeMemory() {
  18392. if (this.elements <= 1) {
  18393. return;
  18394. }
  18395. while (this.numPoints > Potree.pointLoadLimit) {
  18396. var element = this.first;
  18397. var node = element.node;
  18398. this.disposeDescendants(node);
  18399. }
  18400. }
  18401. disposeDescendants(node) {
  18402. var stack = [];
  18403. stack.push(node);
  18404. while (stack.length > 0) {
  18405. var current = stack.pop();
  18406. // console.log(current);
  18407. current.dispose(); //真正删除geometry等
  18408. this.remove(current);
  18409. for (var key in current.children) {
  18410. if (current.children.hasOwnProperty(key)) {
  18411. var child = current.children[key];
  18412. if (child.loaded) {
  18413. stack.push(current.children[key]);
  18414. }
  18415. }
  18416. }
  18417. }
  18418. }
  18419. }
  18420. //
  18421. // how to calculate the radius of a projected sphere in screen space
  18422. // http://stackoverflow.com/questions/21648630/radius-of-projected-sphere-in-screen-space
  18423. // http://stackoverflow.com/questions/3717226/radius-of-projected-sphere
  18424. //
  18425. class ExtendPointCloudMaterial extends PointCloudMaterial$1 {
  18426. constructor() {
  18427. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  18428. super(parameters);
  18429. var getValid = (a, b) => {
  18430. if (a !== undefined) {
  18431. return a;
  18432. } else {
  18433. return b;
  18434. }
  18435. };
  18436. var maxSize = getValid(parameters.maxSize, 200.0);
  18437. var orthoMaxSize = getValid(parameters.orthoMaxSize, 3.0);
  18438. this._gradient = Gradients.RAINBOW; //Gradients.SPECTRAL;//海拔贴图种类
  18439. this.gradientTexture = ExtendPointCloudMaterial.generateGradientTexture(this._gradient);
  18440. //this.matcapTexture = ExtendPointCloudMaterial.generateMatcapTexture(this._matcap);
  18441. delete this.uniforms.screenWidth;
  18442. delete this.uniforms.screenHeight;
  18443. delete this.uniforms.clipBoxes;
  18444. delete this.uniforms.clipPolygons;
  18445. delete this.uniforms.clipPolygonVCount;
  18446. delete this.uniforms.clipPolygonVP;
  18447. delete this.uniforms.clipBoxCount;
  18448. //注意:这里修改了uniforms后,还需要在PotreeRender中手动传递到shader, like: gl.uniformMatrix4fv(....
  18449. Object.assign(this.uniforms, {
  18450. resolution: {
  18451. type: 'v2',
  18452. value: new Vector2()
  18453. },
  18454. maxSize: {
  18455. type: "f",
  18456. value: maxSize
  18457. },
  18458. orthoMaxSize: {
  18459. type: "f",
  18460. value: orthoMaxSize
  18461. },
  18462. gradient: {
  18463. type: "t",
  18464. value: this.gradientTexture
  18465. },
  18466. clipBoxes_in: {
  18467. type: "Matrix4fv",
  18468. value: []
  18469. },
  18470. clipBoxes_out: {
  18471. type: "Matrix4fv",
  18472. value: []
  18473. },
  18474. clipBoxBig_in: {
  18475. type: "Matrix4fv",
  18476. value: []
  18477. },
  18478. boxes_highlight: {
  18479. type: "Matrix4fv",
  18480. value: []
  18481. },
  18482. progress: {
  18483. type: "f",
  18484. value: 0
  18485. },
  18486. easeInOutRatio: {
  18487. type: "f",
  18488. value: 0.3
  18489. },
  18490. pano0Map: {
  18491. type: "t",
  18492. value: null
  18493. },
  18494. pano0Position: {
  18495. type: "v3",
  18496. value: new Vector3()
  18497. },
  18498. pano0Matrix: {
  18499. type: "m4",
  18500. value: new Matrix4()
  18501. },
  18502. pano1Map: {
  18503. type: "t",
  18504. value: null
  18505. },
  18506. pano1Position: {
  18507. type: "v3",
  18508. value: new Vector3()
  18509. },
  18510. pano1Matrix: {
  18511. type: "m4",
  18512. value: new Matrix4()
  18513. },
  18514. prismList: {
  18515. type: "Matrix3fv",
  18516. value: null
  18517. },
  18518. prismPoints: {
  18519. type: "vec2fv",
  18520. value: null
  18521. },
  18522. baseHeightAreaMap: {
  18523. type: 't',
  18524. value: null
  18525. },
  18526. baseHeightBoundZ: {
  18527. type: 'vec2',
  18528. value: new Vector2()
  18529. },
  18530. baseHeightBoundXY: {
  18531. type: 'vec4',
  18532. value: new Vector4()
  18533. }
  18534. });
  18535. delete this.clipBoxes;
  18536. this.clipBoxes_in = [];
  18537. this.clipBoxes_out = [];
  18538. this.highlightBoxes = [];
  18539. this.prisms = [];
  18540. var {
  18541. vs,
  18542. fs
  18543. } = Common.changeShaderToWebgl2(Shaders['pointcloud_new.vs'], Shaders['pointcloud_new.fs'], 'selfBuild');
  18544. Shaders['pointcloud_new.vs'] = vs;
  18545. Shaders['pointcloud_new.fs'] = fs;
  18546. this.updateShaderSource();
  18547. }
  18548. updateShaderSource() {
  18549. var vs = Shaders['pointcloud_new.vs']; //改
  18550. var fs = Shaders['pointcloud_new.fs']; //改
  18551. var definesString = this.getDefines();
  18552. var vsVersionIndex = vs.indexOf("#version ");
  18553. var fsVersionIndex = fs.indexOf("#version ");
  18554. if (vsVersionIndex >= 0) {
  18555. vs = vs.replace(/(#version .*)/, "$1\n".concat(definesString));
  18556. } else {
  18557. vs = "".concat(definesString, "\n").concat(vs);
  18558. }
  18559. if (fsVersionIndex >= 0) {
  18560. fs = fs.replace(/(#version .*)/, "$1\n".concat(definesString));
  18561. } else {
  18562. fs = "".concat(definesString, "\n").concat(fs);
  18563. }
  18564. this.vertexShader = vs;
  18565. this.fragmentShader = fs;
  18566. if (this.opacity === 1.0 && !this.useFilterByNormal) {
  18567. //add useFilterByNormal
  18568. this.blending = NoBlending;
  18569. this.transparent = false;
  18570. this.depthTest = true;
  18571. this.depthWrite = true;
  18572. this.depthFunc = LessEqualDepth;
  18573. } else if ((this.opacity < 1.0 || this.useFilterByNormal) && !this.useEDL) {
  18574. //add useFilterByNormal
  18575. this.blending = AdditiveBlending;
  18576. this.transparent = true;
  18577. this.depthTest = false;
  18578. this.depthWrite = true;
  18579. this.depthFunc = AlwaysDepth;
  18580. }
  18581. if (this.weighted) {
  18582. this.blending = AdditiveBlending;
  18583. this.transparent = true;
  18584. this.depthTest = true;
  18585. this.depthWrite = false;
  18586. }
  18587. this.shaderNeedsUpdate = true;
  18588. }
  18589. getDefines() {
  18590. var defines = [];
  18591. if (this.pointSizeType === PointSizeType.FIXED) {
  18592. defines.push('#define fixed_point_size');
  18593. } else if (this.pointSizeType === PointSizeType.ATTENUATED) {
  18594. defines.push('#define attenuated_point_size');
  18595. } else if (this.pointSizeType === PointSizeType.ADAPTIVE) {
  18596. defines.push('#define adaptive_point_size');
  18597. }
  18598. if (!Features.EXT_DEPTH.isSupported(viewer.renderer.getContext()) && this.shape === PointShape$1.PARABOLOID) {
  18599. this.shape = PointShape$1.SQUARE; //强行替换
  18600. }
  18601. if (this.shape === PointShape$1.SQUARE) {
  18602. defines.push('#define square_point_shape');
  18603. } else if (this.shape === PointShape$1.CIRCLE) {
  18604. defines.push('#define circle_point_shape');
  18605. } else if (this.shape === PointShape$1.PARABOLOID) {
  18606. defines.push('#define paraboloid_point_shape');
  18607. }
  18608. //console.log('this.shape PARABOLOID', this.shape, this.shape === PointShape.PARABOLOID)
  18609. if (this._useEDL || this.fakeEDL) {
  18610. defines.push('#define use_edl');
  18611. }
  18612. if (this.activeAttributeName) {
  18613. var attributeName = this.activeAttributeName.replace(/[^a-zA-Z0-9]/g, '_');
  18614. defines.push("#define color_type_".concat(attributeName));
  18615. }
  18616. if (this._treeType === TreeType.OCTREE) {
  18617. defines.push('#define tree_type_octree');
  18618. } else if (this._treeType === TreeType.KDTREE) {
  18619. defines.push('#define tree_type_kdtree');
  18620. }
  18621. if (this.weighted) {
  18622. defines.push('#define weighted_splats');
  18623. }
  18624. for (var [key, value] of this.defines) {
  18625. defines.push(value);
  18626. }
  18627. return defines.join("\n");
  18628. }
  18629. get pointSizeType() {
  18630. return this._pointSizeType;
  18631. }
  18632. set pointSizeType(value) {
  18633. if (typeof value == 'string') value = PointSizeType[value];
  18634. super.pointSizeType = value;
  18635. /* if (this._pointSizeType !== value) {
  18636. this._pointSizeType = value;
  18637. this.updateShaderSource(); //这句表明这个属性频繁更改会卡顿
  18638. this.dispatchEvent({
  18639. type: 'point_size_type_changed',
  18640. target: this
  18641. });
  18642. this.dispatchEvent({
  18643. type: 'material_property_changed',
  18644. target: this
  18645. });
  18646. } */
  18647. }
  18648. get color() {
  18649. return this.uniforms.uColor.value;
  18650. }
  18651. set color(value) {
  18652. //改
  18653. if (value == this.color_) return;
  18654. var color = value;
  18655. //if (!this.uniforms.uColor.value.equals(value)) {
  18656. if (typeof value == 'string') {
  18657. var colorArr = Potree.config.colors[value];
  18658. if (!colorArr) {
  18659. //console.warn('没找到该颜色值'+ value)
  18660. } else {
  18661. color = new Color().fromArray(colorArr).multiplyScalar(1 / 255);
  18662. }
  18663. }
  18664. this.uniforms.uColor.value.set(color);
  18665. //this.uniforms.uColor.value.copy(value);
  18666. this.dispatchEvent({
  18667. type: 'color_changed',
  18668. target: this
  18669. });
  18670. this.dispatchEvent({
  18671. type: 'material_property_changed',
  18672. target: this
  18673. });
  18674. //}
  18675. this.color_ = value; //记录下str
  18676. }
  18677. ////////////////////////add
  18678. setProjectedPanos(pano0, pano1, progressValue, easeInOutRatio) {
  18679. //this.uniforms.usePanoMap.value = 1
  18680. this.usePanoMap = true;
  18681. progressValue != void 0 && (this.uniforms.progress.value = progressValue);
  18682. //pano0.ensureSkyboxReadyForRender();
  18683. this.uniforms.pano0Map.value = pano0.getSkyboxTexture();
  18684. this.uniforms.pano0Position.value.copy(pano0.position);
  18685. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix);
  18686. //pano1.ensureSkyboxReadyForRender();
  18687. this.uniforms.easeInOutRatio.value = easeInOutRatio || 0; //之前做点云和全景混合时加的,为了让点云颜色柔和切换到全景颜色。如不混合就0
  18688. this.uniforms.pano1Map.value = pano1.getSkyboxTexture();
  18689. this.uniforms.pano1Position.value.copy(pano1.position);
  18690. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix);
  18691. //this.updateShaderSource()
  18692. //this.needsUpdate = true;
  18693. }
  18694. stopProjectedPanos() {
  18695. //this.uniforms.usePanoMap.value = 0
  18696. this.usePanoMap = false;
  18697. }
  18698. setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, highlightBoxes) {
  18699. var prismPolygons = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  18700. if (!clipBoxes_in || !clipBoxes_out) {
  18701. return;
  18702. }
  18703. this.uniforms.clipBoxBig_in.value = bigClipInBox && bigClipInBox.inverse;
  18704. this.uniforms.clipBoxes_in.value = new Float32Array(clipBoxes_in.length * 16);
  18705. this.uniforms.clipBoxes_out.value = new Float32Array(clipBoxes_out.length * 16);
  18706. this.uniforms.boxes_highlight.value = new Float32Array(highlightBoxes.length * 16);
  18707. for (var i = 0; i < clipBoxes_in.length; i++) {
  18708. var box = clipBoxes_in[i];
  18709. this.uniforms.clipBoxes_in.value.set(box.inverse.elements, 16 * i);
  18710. }
  18711. for (var _i = 0; _i < clipBoxes_out.length; _i++) {
  18712. var _box = clipBoxes_out[_i];
  18713. this.uniforms.clipBoxes_out.value.set(_box.inverse.elements, 16 * _i);
  18714. }
  18715. for (var _i2 = 0; _i2 < highlightBoxes.length; _i2++) {
  18716. var _box2 = highlightBoxes[_i2];
  18717. this.uniforms.boxes_highlight.value.set(_box2.inverse.elements, 16 * _i2);
  18718. }
  18719. /* for (let i = 0; i < this.uniforms.clipBoxes.value.length; i++) {??
  18720. if (Number.isNaN(this.uniforms.clipBoxes.value[i])) {
  18721. this.uniforms.clipBoxes.value[i] = Infinity;
  18722. }
  18723. } */
  18724. if (prismPolygons.length) {
  18725. var pointsCount = prismPolygons.pointsCount = prismPolygons.reduce((w, c) => {
  18726. return w + c.points.length;
  18727. }, 0);
  18728. this.uniforms.prismList.value = new Float32Array(9 * prismPolygons.length);
  18729. this.uniforms.prismPoints.value = new Float32Array(2 * pointsCount);
  18730. prismPolygons.maxPointsCount = 0; //单个prism最大点个数
  18731. var pointIndex = 0;
  18732. for (var _i3 = 0; _i3 < prismPolygons.length; _i3++) {
  18733. var bound = prismPolygons[_i3].prismBound;
  18734. var z = prismPolygons[_i3].horizonZ;
  18735. //z = Potree.browser.urlHasValue('zmin',true) || zs[0]
  18736. this.uniforms.prismList.value.set([bound.min.z, z, bound.max.z, bound.min.x, bound.max.x, bound.min.y, bound.max.y, prismPolygons[_i3].points.length], 9 * _i3);
  18737. for (var j = 0; j < prismPolygons[_i3].points.length; j++) {
  18738. this.uniforms.prismPoints.value.set([prismPolygons[_i3].points[j].x, prismPolygons[_i3].points[j].y], 2 * j + pointIndex);
  18739. }
  18740. pointIndex += 2 * prismPolygons[_i3].points.length;
  18741. prismPolygons.maxPointsCount = Math.max(prismPolygons.maxPointsCount, prismPolygons[_i3].points.length);
  18742. }
  18743. }
  18744. var doUpdate = this.clipBoxes_in.length !== clipBoxes_in.length || this.clipBoxes_out.length != clipBoxes_out.length || this.highlightBoxes.length !== highlightBoxes.length || !this.bigClipInBox != !bigClipInBox || this.prisms.length != prismPolygons.length || this.prisms.maxPointsCount != prismPolygons.maxPointsCount;
  18745. //this.clipBoxes = clipBoxes;
  18746. if (doUpdate) {
  18747. this.shaderNeedsUpdate = true;
  18748. viewer.dispatchEvent('content_changed');
  18749. }
  18750. this.bigClipInBox = bigClipInBox;
  18751. this.clipBoxes_in = clipBoxes_in;
  18752. this.clipBoxes_out = clipBoxes_out;
  18753. this.highlightBoxes = highlightBoxes;
  18754. this.prisms = prismPolygons;
  18755. }
  18756. }
  18757. var defaultColor = new Color(1, 1, 1); //config.applicationName == "zhiHouse" ? Colors.zhiBlue : Colors.lightGreen;
  18758. function dealPosArr(points) {
  18759. //识别是否每个点都不一样,把连续点变为不连续的片段连接
  18760. var add = points => {
  18761. var points2 = [],
  18762. len = points.length;
  18763. for (var i = 0; i < len - 1; i++) {
  18764. points2.push(points[i], points[i + 1]);
  18765. }
  18766. return points2;
  18767. };
  18768. if (points[0] && points[0] instanceof Array) {
  18769. //多组,每组间连续,但组之间不连续
  18770. var points2 = [];
  18771. points.forEach(ps => points2.push(...add(ps)));
  18772. return points2;
  18773. } else if (points.length > 2 && !points[2].equals(points[1])) {
  18774. return add(points);
  18775. } else return points;
  18776. }
  18777. var LineDraw = {
  18778. createLine: function createLine(posArr) {
  18779. var o = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  18780. //多段普通线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  18781. var mat;
  18782. if (o.mat) {
  18783. mat = o.mat;
  18784. } else {
  18785. var prop = Object.assign({
  18786. lineWidth: o.lineWidth || 1,
  18787. //windows无效。 似乎mac/ios上粗细有效 ?
  18788. color: o.color || defaultColor
  18789. }, o);
  18790. if (o.deshed) {
  18791. prop.dashSize = o.dashSize || 0.1, prop.gapSize = o.gapSize || 0.1;
  18792. }
  18793. mat = new THREE$1[o.deshed ? "LineDashedMaterial" : "LineBasicMaterial"](prop);
  18794. }
  18795. var line = new LineSegments(new BufferGeometry(), mat);
  18796. line.renderOrder = o.renderOrder || Potree.config.renderOrders.lines;
  18797. this.moveLine(line, posArr);
  18798. return line;
  18799. },
  18800. moveLine: function moveLine(line, posArr) {
  18801. //if(posArr.length == 0)return
  18802. if (!line.uncontinuous || posArr[0] && posArr[0] instanceof Array) posArr = dealPosArr(posArr);
  18803. var position = [];
  18804. posArr.forEach(e => position.push(e.x, e.y, e.z));
  18805. line.geometry.setAttribute('position', new Float32BufferAttribute( /* new Float32Array( */position /* ) */, 3));
  18806. line.geometry.attributes.position.needsUpdate = true;
  18807. line.geometry.computeBoundingSphere();
  18808. if (line.material instanceof LineDashedMaterial) {
  18809. line.computeLineDistances();
  18810. //line.geometry.attributes.lineDistance.needsUpdate = true;
  18811. line.geometry.verticesNeedUpdate = true; //没用
  18812. }
  18813. },
  18814. createFatLineMat: function createFatLineMat(o) {
  18815. var supportExtDepth = !!Features.EXT_DEPTH.isSupported();
  18816. var params = $.extend({}, {
  18817. //默认
  18818. lineWidth: 5,
  18819. color: 0xffffff,
  18820. transparent: true,
  18821. depthWrite: false,
  18822. depthTest: false,
  18823. dashSize: 0.1,
  18824. gapSize: 0.1
  18825. }, o, {
  18826. //修正覆盖:
  18827. dashed: o.dashWithDepth ? supportExtDepth && !!o.dashed : !!o.dashed,
  18828. dashWithDepth: !!o.dashWithDepth,
  18829. //只在被遮住的部分显示虚线
  18830. useDepth: !!o.useDepth,
  18831. supportExtDepth
  18832. });
  18833. var mat = new LineMaterial(params);
  18834. //if(o.dashed)(mat.defines.USE_DASH = "")
  18835. return mat;
  18836. },
  18837. /*
  18838. 创建可以改变粗细的线。
  18839. */
  18840. createFatLine: function createFatLine(posArr, o) {
  18841. var geometry = new LineGeometry();
  18842. geometry.setColors(o.color || [1, 1, 1]);
  18843. var matLine = o.mat || this.createFatLineMat(o);
  18844. var line = new Line2(geometry, matLine);
  18845. //line.computeLineDistances();
  18846. line.uncontinuous = o.uncontinuous; //线不连续,由线段组成
  18847. line.scale.set(1, 1, 1);
  18848. line.renderOrder = Potree.config.renderOrders.lines;
  18849. this.moveFatLine(line, posArr);
  18850. return line;
  18851. },
  18852. moveFatLine: function moveFatLine(line, posArr) {
  18853. var geometry = line.geometry;
  18854. var positions = [];
  18855. if (!line.uncontinuous || posArr[0] && posArr[0] instanceof Array) posArr = dealPosArr(posArr);
  18856. posArr.forEach(e => {
  18857. positions.push(...e.toArray());
  18858. });
  18859. if (!geometry) {
  18860. geometry = line.geometry = new LineGeometry();
  18861. }
  18862. if (geometry.attributes.instanceEnd && geometry.attributes.instanceEnd.data.array.length != positions.length) {
  18863. //positions个数改变会有部分显示不出来,所以重建
  18864. geometry.dispose();
  18865. geometry = new LineGeometry();
  18866. line.geometry = geometry;
  18867. }
  18868. geometry.setPositions(positions);
  18869. if (line.material.defines.USE_DASH != void 0) {
  18870. //line.geometry.verticesNeedUpdate = true; //没用
  18871. line.geometry.computeBoundingSphere(); //for raycaster
  18872. line.computeLineDistances();
  18873. }
  18874. },
  18875. updateLine: function updateLine(line, posArr) {
  18876. if (line instanceof Line2) {
  18877. LineDraw.moveFatLine(line, posArr);
  18878. } else {
  18879. LineDraw.moveLine(line, posArr);
  18880. }
  18881. },
  18882. /*
  18883. 为line创建用于检测鼠标的透明mesh,实际是个1-2段圆台。
  18884. 由于近大远小的原因,假设没有透视畸变、创建的是等粗的圆柱的话, 所看到的线上每个位置的粗细应该和距离成反比。所以将圆柱改为根据距离线性渐变其截面半径的圆台,在最近点(相机到线的垂足)最细。如果最近点在线段上,则分成两段圆台,否则一段。
  18885. */
  18886. createBoldLine: function createBoldLine(points, o) {
  18887. o = o || {};
  18888. var cylinder = o && o.cylinder;
  18889. var CD = points[1].clone().sub(points[0]);
  18890. var rotate = function rotate() {
  18891. //根据端点旋转好模型
  18892. cylinder.lastVector = CD; //记录本次的端点向量
  18893. var AB = new Vector3(0, -1, 0);
  18894. var axisVec = AB.clone().cross(CD).normalize(); //得到垂直于它们的向量,也就是旋转轴
  18895. var rotationAngle = AB.angleTo(CD);
  18896. cylinder.quaternion.setFromAxisAngle(axisVec, rotationAngle);
  18897. };
  18898. if (o && o.type == "init") {
  18899. cylinder = new Mesh();
  18900. cylinder.material = o.mat;
  18901. if (CD.length() == 0) return cylinder;
  18902. rotate();
  18903. }
  18904. if (CD.length() == 0) return cylinder;
  18905. if (o.type != "update") {
  18906. var CDcenter = points[0].clone().add(points[1]).multiplyScalar(.5);
  18907. cylinder.position.copy(CDcenter);
  18908. if (!cylinder.lastVector || o.type == "moveAndRotate") rotate();else if (cylinder.lastVector && CD.angleTo(cylinder.lastVector) > 0) rotate(); //线方向改了or线反向了 重新旋转一下模型
  18909. if (config.isEdit && !objects.mainDesign.editing) return cylinder; //节省初始加载时间?
  18910. }
  18911. //为了保证线段任何地方的可检测点击范围看起来一样大,更新圆台的结构(但是在镜头边缘会比中心看起来大)
  18912. var height = points[0].distanceTo(points[1]);
  18913. var standPos = o && o.standPos || objects.player.position;
  18914. var k = config.isMobile ? 20 : 40;
  18915. var dis1 = points[0].distanceTo(standPos);
  18916. var dis2 = points[1].distanceTo(standPos);
  18917. var foot = math.getFootPoint(standPos, points[0], points[1]); //垂足
  18918. if (o.constantBold || objects.player.mode != "panorama") {
  18919. var width = 0.1; //0.08;
  18920. var pts = [new Vector2(width, height / 2), new Vector2(width, -height / 2)];
  18921. } else if (foot.clone().sub(points[0]).dot(foot.clone().sub(points[1])) > 0) {
  18922. //foot不在线段上
  18923. var pts = [new Vector2(dis1 / k, height / 2), new Vector2(dis2 / k, -height / 2)];
  18924. } else {
  18925. //在线段上的话,要在垂足这加一个节点,因它距离站位最近,而两端较远
  18926. var dis3 = foot.distanceTo(standPos);
  18927. var len = foot.distanceTo(points[0]);
  18928. var pts = [new Vector2(dis1 / k, height / 2), new Vector2(dis3 / k, height / 2 - len), new Vector2(dis2 / k, -height / 2)];
  18929. }
  18930. cylinder.geometry && cylinder.geometry.dispose(); //若不删除会占用内存
  18931. cylinder.geometry = new LatheBufferGeometry(pts, 4 /* Math.min(dis1,dis2)<10?4:3 */);
  18932. cylinder.renderOrder = 2;
  18933. return cylinder;
  18934. },
  18935. updateBoldLine: function updateBoldLine(cylinder, points, type, standPos, constantBold) {
  18936. this.createBoldLine(points, {
  18937. type: type,
  18938. cylinder: cylinder,
  18939. standPos: standPos,
  18940. constantBold
  18941. }); //type:move:平移 会改长短 , type:update根据距离和角度更新 不改长短
  18942. }
  18943. };
  18944. var MeshDraw = {
  18945. getShape: function getShape(shapes, holes) {
  18946. //不一定闭合 暂时所有shapes共享holes。如果要单独的话, shapes改为[{shape:[],holes:[]},{}]的形式
  18947. if (shapes[0] && !(shapes[0] instanceof Array)) {
  18948. //仅是一个shape的点
  18949. shapes = [shapes];
  18950. }
  18951. var holesArr = [];
  18952. if (holes) {
  18953. //挖空
  18954. holes.forEach(points => {
  18955. var holePath = new Path();
  18956. holePath.moveTo(points[0].x, points[0].y);
  18957. for (var i = 1, len = points.length; i < len; i++) {
  18958. holePath.lineTo(points[i].x, points[i].y);
  18959. }
  18960. holesArr.push(holePath);
  18961. });
  18962. }
  18963. var shapesArr = shapes.map(points => {
  18964. var shape = new Shape();
  18965. shape.moveTo(points[0].x, points[0].y);
  18966. for (var i = 1, len = points.length; i < len; i++) {
  18967. shape.lineTo(points[i].x, points[i].y);
  18968. }
  18969. shape.holes.push(...holesArr);
  18970. shape.dontClose = points.dontClose; //add 有的shape不需要闭合
  18971. return shape;
  18972. });
  18973. return shapesArr;
  18974. },
  18975. /* getShape:function(shapes, holes){
  18976. var shape = new THREE.Shape();
  18977. if(shapes[0] && !(shapes[0] instanceof Array) ){//仅是一个shape的点
  18978. shapes = [shapes]
  18979. }
  18980. shapes.forEach((points)=>{
  18981. shape.moveTo( points[0].x, points[0].y );
  18982. for(var i=1,len=points.length; i<len; i++){
  18983. shape.lineTo(points[i].x, points[i].y )
  18984. }
  18985. })
  18986. //多个points的数组绘制在一个shape中,缺点是这些数组之间可能绘制出来会连在一起。
  18987. if(holes){//挖空
  18988. holes.forEach((points)=>{
  18989. var holePath = new THREE.Path()
  18990. holePath.moveTo( points[0].x, points[0].y )
  18991. for(var i=1,len=points.length; i<len; i++){
  18992. holePath.lineTo(points[i].x, points[i].y )
  18993. }
  18994. shape.holes.push( holePath );
  18995. })
  18996. }
  18997. return shape
  18998. }, */
  18999. getShapeGeo: function getShapeGeo(shapes, holes) {
  19000. //获取任意形状(多边形或弧形)的形状面 //quadraticCurveTo() 这是弧形的含函数
  19001. var geometry = new ShapeBufferGeometry(this.getShape(shapes, holes)); //ShapeGeometry
  19002. /* var matrix = new THREE.Matrix4();//将竖直的面变为水平
  19003. matrix.set(//z = y
  19004. 1, 0, 0, 0,
  19005. 0, 0, 0, 0,
  19006. 0, 1, 0, 0,
  19007. 0, 0, 0, 1
  19008. )
  19009. geometry.applyMatrix(matrix) */
  19010. //geometry.computeVertexNormals();//对于光照需要的是点法线
  19011. return geometry;
  19012. },
  19013. getExtrudeGeo: function getExtrudeGeo(shapes, holes) {
  19014. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {
  19015. openEnded: false,
  19016. shapeDontClose: false
  19017. };
  19018. //获得挤出棱柱,可以选择传递height,或者extrudePath
  19019. var shape = this.getShape(shapes, holes); //points是横截面 [vector2,...]
  19020. if (options.extrudePath) {
  19021. // 路径 :[vector3,...]
  19022. var length = options.extrudePath.reduce((total, currentValue, currentIndex, arr) => {
  19023. if (currentIndex == 0) return 0;
  19024. return total + currentValue.distanceTo(arr[currentIndex - 1]);
  19025. }, 0);
  19026. //options.extrudePath = new THREE.CatmullRomCurve3(options.extrudePath)
  19027. if (options.extrudePath.length == 2) {
  19028. options.tension = 0; //否则一端扭曲
  19029. options.steps = 1;
  19030. }
  19031. {
  19032. //去掉重复的点
  19033. var path = [];
  19034. var minDis = options.dontSmooth ? 0 : 0.2; //CatmullRomCurve3 经常扭曲,如果两个点靠得很近可能会扭曲,这里去除靠的太近的点。但去除后依旧会出现一定扭曲.
  19035. options.extrudePath.forEach((p, i) => {
  19036. if (i == 0 || i == options.extrudePath.length - 1) return path.push(p); //首尾直接加入
  19037. var last = path[path.length - 1]; //和上一个比
  19038. var dis = last.distanceTo(p);
  19039. if (dis <= minDis) {
  19040. console.log("\u7B2C".concat(i, "\u4E2A\u70B9(").concat(p.toArray(), ")\u56E0\u4E3A\u548C\u4E0A\u4E00\u4E2A\u6570\u636E(").concat(last.toArray(), ")\u592A\u63A5\u8FD1(dis:").concat(dis, ")\u6240\u4EE5\u5220\u9664"));
  19041. } else if (i == options.extrudePath.length - 2) {
  19042. //因为最后一个必定加入,所以倒数第二个还也不能太靠近最后一个
  19043. last = options.extrudePath[options.extrudePath.length - 1]; //和下一个(最后一个比)
  19044. if (dis <= minDis) {
  19045. console.log("\u7B2C".concat(i, "\u4E2A\u70B9(").concat(p.toArray(), ")\u56E0\u4E3A\u548C\u4E0B\u4E00\u4E2A\u6570\u636E(").concat(last.toArray(), ")\u592A\u63A5\u8FD1(dis:").concat(dis, ")\u6240\u4EE5\u5220\u9664"));
  19046. } else {
  19047. path.push(p);
  19048. }
  19049. } else {
  19050. path.push(p);
  19051. }
  19052. });
  19053. options.extrudePath = path;
  19054. }
  19055. if (options.dontSmooth) {
  19056. var curvePath = new CurvePath(); //通用的曲线路径对象,它可以包含直线段和曲线段。在这里只做折线
  19057. for (var i = 0; i < options.extrudePath.length - 1; i++) {
  19058. var curve3 = new LineCurve3(options.extrudePath[i], options.extrudePath[i + 1]); //添加线段
  19059. curvePath.add(curve3);
  19060. }
  19061. options.extrudePath = curvePath;
  19062. } else {
  19063. //平滑连续的曲线(但经常会有扭曲的问题,tension:0能缓解, 另外shape和path都最好在原点附近,也就是点需减去bound.min )
  19064. options.extrudePath = new CatmullRomCurve3(options.extrudePath, options.closed, 'catmullrom' /* 'centripetal' */, options.tension); //tension:拐弯剧烈程度,但随着长度增长,该值需要减小,否则会扭曲
  19065. }
  19066. }
  19067. var extrudeSettings = $.extend(options, {
  19068. steps: options.steps != void 0 ? options.steps : options.extrudePath ? Math.round(length / (options.spaceDis || 0.3)) : 1,
  19069. //分成几段 spaceDis每段长度
  19070. bevelEnabled: false //不加的话,height为0时会有圆弧高度
  19071. //openEnded默认false
  19072. });
  19073. var geometry = new ExtrudeBufferGeometry(shape, extrudeSettings); //修改了three.js文件, buildLidFaces处,创建顶底面加了选项,可以选择开口。
  19074. return geometry;
  19075. },
  19076. getUnPosPlaneGeo: function () {
  19077. //获取还没有赋值位置的plane geometry
  19078. var e = new Uint16Array([0, 1, 2, 0, 2, 3])
  19079. // , t = new Float32Array([-.5, -.5, 0, .5, -.5, 0, .5, .5, 0, -.5, .5, 0])
  19080. ,
  19081. i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
  19082. g = new BufferGeometry();
  19083. g.setIndex(new BufferAttribute(e, 1)),
  19084. //g.addAttribute("position", new n.BufferAttribute(t, 3)),
  19085. g.setAttribute("uv", new BufferAttribute(i, 2));
  19086. return function () {
  19087. return g;
  19088. };
  19089. }(),
  19090. getPlaneGeo: function getPlaneGeo(A, B, C, D) {
  19091. var geo = this.getUnPosPlaneGeo().clone();
  19092. var pos = [A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z, D.x, D.y, D.z];
  19093. //geo.addAttribute("position", new THREE.BufferAttribute(pos, 3))
  19094. geo.setAttribute('position', new Float32BufferAttribute(pos, 3));
  19095. geo.computeVertexNormals();
  19096. geo.computeBoundingSphere(); //for raycaster
  19097. return geo;
  19098. },
  19099. drawPlane: function drawPlane(A, B, C, D, material) {
  19100. var wall = new Mesh(this.getPlaneGeo(A, B, C, D), material);
  19101. return wall;
  19102. },
  19103. movePlane: function movePlane(mesh, A, B, C, D) {
  19104. var pos = new Float32Array([A.x, A.y, A.z, B.x, B.y, B.z, C.x, C.y, C.z, D.x, D.y, D.z]);
  19105. mesh.geometry.addAttribute("position", new BufferAttribute(pos, 3));
  19106. mesh.geometry.computeBoundingSphere(); //for checkIntersect
  19107. },
  19108. createGeometry: function createGeometry(posArr, faceArr, uvArr, normalArr) {
  19109. //创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  19110. var geo = new BufferGeometry();
  19111. var positions = [];
  19112. posArr.forEach(p => positions.push(p.x, p.y, p.z));
  19113. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  19114. if (faceArr) {
  19115. var indice = [];
  19116. faceArr.forEach(f => indice.push(...f));
  19117. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  19118. }
  19119. if (uvArr) {
  19120. var uvs = [];
  19121. uvArr.forEach(uv => uvs.push(uv.x, uv.y));
  19122. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  19123. }
  19124. if (normalArr) {
  19125. var normals = [];
  19126. normalArr.forEach(n => normals.push(n.x, n.y, n.z));
  19127. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  19128. }
  19129. /*
  19130. geo.computeVertexNormals()
  19131. geo.computeBoundingSphere() //for raycaster
  19132. */
  19133. return geo;
  19134. },
  19135. updateGeometry: function updateGeometry(geo, posArr, faceArr, uvArr, normalArr) {
  19136. //创建复杂mesh. faceArr:[[0,1,2],[0,2,3]]
  19137. var positions = [];
  19138. posArr.forEach(p => positions.push(p.x, p.y, p.z));
  19139. geo.setAttribute('position', new Float32BufferAttribute(positions, 3));
  19140. geo.attributes.position.needsUpdate = true;
  19141. if (faceArr) {
  19142. var indice = [];
  19143. faceArr.forEach(f => indice.push(...f));
  19144. geo.setIndex(indice); // auto set Uint16BufferAttribute or Uint32BufferAttribute
  19145. }
  19146. if (uvArr) {
  19147. var uvs = [];
  19148. uvArr.forEach(uv => uvs.push(uv.x, uv.y));
  19149. geo.setAttribute("uv", new Float32BufferAttribute(uvs, 2));
  19150. }
  19151. if (normalArr) {
  19152. var normals = [];
  19153. normalArr.forEach(n => normals.push(n.x, n.y, n.z));
  19154. geo.setAttribute("normal", new Float32BufferAttribute(normals, 3));
  19155. }
  19156. /*
  19157. geo.computeVertexNormals()
  19158. */
  19159. geo.computeBoundingSphere(); //for raycaster and visi
  19160. return geo;
  19161. }
  19162. };
  19163. class DepthBasicMaterial extends ShaderMaterial {
  19164. constructor() {
  19165. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  19166. var {
  19167. width,
  19168. height
  19169. } = viewer.renderer.getSize(new Vector2());
  19170. var uniforms = {
  19171. resolution: {
  19172. type: 'v2',
  19173. value: new Vector2(width, height)
  19174. },
  19175. viewportOffset: {
  19176. type: 'v2',
  19177. value: new Vector2(0, 0)
  19178. },
  19179. //left, top
  19180. //uUseOrthographicCamera:{ type: "b", value: false },
  19181. nearPlane: {
  19182. type: 'f',
  19183. value: 0.1
  19184. },
  19185. farPlane: {
  19186. type: 'f',
  19187. value: 10000
  19188. },
  19189. depthTexture: {
  19190. type: 't',
  19191. value: null
  19192. },
  19193. opacity: {
  19194. type: 'f',
  19195. value: 1
  19196. },
  19197. map: {
  19198. type: 't',
  19199. value: o.map
  19200. },
  19201. baseColor: {
  19202. type: 'v3',
  19203. value: o.color ? new Color(o.color) : new Color("#ffffff")
  19204. },
  19205. backColor: {
  19206. type: 'v3',
  19207. value: o.backColor ? new Color(o.backColor) : new Color("#ddd")
  19208. },
  19209. clipDistance: {
  19210. type: 'f',
  19211. value: o.clipDistance || 4
  19212. },
  19213. //消失距离
  19214. occlusionDistance: {
  19215. type: 'f',
  19216. value: o.occlusionDistance || 1
  19217. },
  19218. //变为backColor距离
  19219. maxClipFactor: {
  19220. type: 'f',
  19221. value: o.maxClipFactor || 1
  19222. },
  19223. //0-1
  19224. maxOcclusionFactor: {
  19225. type: 'f',
  19226. value: o.maxOcclusionFactor || 1
  19227. },
  19228. //0-1
  19229. mapScale: {
  19230. type: 'f',
  19231. value: o.mapScale || 1
  19232. } //0-1
  19233. };
  19234. var {
  19235. vs,
  19236. fs
  19237. } = Common.changeShaderToWebgl2(Shaders['depthBasic.vs'], Shaders['depthBasic.fs'], 'ShaderMaterial');
  19238. super({
  19239. uniforms,
  19240. vertexShader: vs,
  19241. fragmentShader: fs,
  19242. depthWrite: false,
  19243. depthTest: false,
  19244. transparent: o.transparent == void 0 ? true : o.transparent,
  19245. side: o.side || 0 /* THREE.DoubleSide */
  19246. });
  19247. this.events = {
  19248. setSize: e => {
  19249. //如果出现横条状的异常,往往是viewportOffset出错 //地图不需要
  19250. if (!this.realUseDepth || !e.viewport) return;
  19251. var viewport = e.viewport;
  19252. var viewportOffset = viewport.offset || new Vector2();
  19253. this.uniforms.resolution.value.copy(viewport.resolution2); //2023.6.12突然发现ratio>1的用resolution不对,得用2才对。但是之前明明记得不是这样
  19254. this.uniforms.viewportOffset.value.copy(viewportOffset);
  19255. },
  19256. render: e => {
  19257. //before render 如果有大于两个viewport的话,不同viewport用不同的depthTex
  19258. this.updateDepthParams(e);
  19259. }
  19260. /* cameraChange:(e)=>{
  19261. if(e.changeInfo.projectionChanged){//resize时也会触发。虽然保守起见的话加上resize比较好//所以当时为何不用resize
  19262. //console.log('projectionChanged')
  19263. this.events.setSize(e)
  19264. }
  19265. } */
  19266. };
  19267. //-----其他----
  19268. this.autoDepthTest = o.autoDepthTest;
  19269. if (o.opacity != void 0) {
  19270. this.opacity = o.opacity;
  19271. }
  19272. this.useDepth = o.useDepth;
  19273. this.map = o.map;
  19274. }
  19275. get useDepth() {
  19276. return this.useDepth_;
  19277. }
  19278. set useDepth(value) {
  19279. value = value && Features.EXT_DEPTH.isSupported(); //如果不支持 EXT_DEPTH 的话会失效
  19280. if (this.useDepth_ != value) {
  19281. this.setRealDepth(value);
  19282. this.useDepth_ = value;
  19283. if (value) {
  19284. viewer.addEventListener("render.begin", this.events.render);
  19285. //viewer.addEventListener('camera_changed', this.events.cameraChange)
  19286. viewer.addEventListener('resize', this.events.setSize);
  19287. this.updateDepthParams();
  19288. } else {
  19289. viewer.removeEventListener("render.begin", this.events.render);
  19290. viewer.removeEventListener('resize', this.events.setSize);
  19291. }
  19292. }
  19293. }
  19294. setRealDepth(useDepth, viewport) {
  19295. //确实使用到depthTex
  19296. if (this.realUseDepth != useDepth) {
  19297. if (useDepth) {
  19298. this.defines.useDepth = '';
  19299. } else {
  19300. delete this.defines.useDepth;
  19301. }
  19302. this.realUseDepth = useDepth;
  19303. if (this.autoDepthTest) this.depthWrite = this.depthTest = !useDepth; //如果useDepth = false,使用原始的depthTest
  19304. this.needsUpdate = true;
  19305. if (!viewport) viewport = viewer.mainViewport; //暂时这么设置
  19306. useDepth && this.events.setSize({
  19307. viewport
  19308. });
  19309. }
  19310. }
  19311. get map() {
  19312. return this.uniforms.map.value;
  19313. }
  19314. set map(map) {
  19315. this.uniforms.map.value = map;
  19316. if (map) {
  19317. this.defines.use_map = '';
  19318. } else {
  19319. delete this.defines.use_map;
  19320. }
  19321. }
  19322. get opacity() {
  19323. return this.uniforms.opacity.value;
  19324. }
  19325. set opacity(o) {
  19326. this.uniforms && (this.uniforms.opacity.value = o);
  19327. }
  19328. get color() {
  19329. return this.uniforms.baseColor.value;
  19330. }
  19331. set color(c) {
  19332. this.uniforms && this.uniforms.baseColor.value.set(c);
  19333. }
  19334. /* dispose(){
  19335. super.dispose()
  19336. viewer.depthBasic
  19337. } */
  19338. copy(source) {
  19339. super.copy(source);
  19340. this.useDepth = source.useDepth;
  19341. this.map = source.map;
  19342. return this;
  19343. }
  19344. updateDepthParams() {
  19345. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  19346. //主要用于点云遮住mesh
  19347. var viewport = e.viewport || viewer.mainViewport;
  19348. var camera = viewport.camera;
  19349. var hasDepth = this.useDepth && camera.isPerspectiveCamera && (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL);
  19350. this.setRealDepth(hasDepth, viewport);
  19351. if (hasDepth) {
  19352. this.uniforms.depthTexture.value = viewer.getPRenderer().getRtEDL(viewport).depthTexture; //其实只赋值一次就行
  19353. this.uniforms.nearPlane.value = camera.near;
  19354. this.uniforms.farPlane.value = camera.far;
  19355. }
  19356. //this.uniforms.uUseOrthographicCamera.value = !camera.isPerspectiveCamera
  19357. }
  19358. }
  19359. var geo = new PlaneBufferGeometry(1, 1);
  19360. class Sprite$2 extends Mesh {
  19361. constructor() {
  19362. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  19363. super(geo, options.mat || new DepthBasicMaterial(options)); /* ({map:options.map, useDepth:options.useDepth})) */
  19364. this.root = options.root || this;
  19365. this.renderOrder = options.renderOrder != void 0 ? options.renderOrder : 4;
  19366. this.pickOrder = options.pickOrder || 0;
  19367. this.sizeInfo = options.sizeInfo;
  19368. this.dontFixOrient = options.dontFixOrient;
  19369. this.options = options;
  19370. this.position.y = options.disToLine || 0; //离线距离
  19371. this.matrixAutoUpdate = false;
  19372. this.matrixMap = new Map();
  19373. if (this.root != this) {
  19374. this.matrixMapRoot = new Map();
  19375. this.root.matrixAutoUpdate = false;
  19376. }
  19377. this.visiMap = new Map();
  19378. this.name = options.name || 'sprite';
  19379. this.useViewport = null;
  19380. this.viewports = options.viewports; //指定更新的viewports
  19381. this.visible_ = true;
  19382. var clear = e => {
  19383. this.matrixMap.clear(); //清空后在所有viewport上都必须更新才能渲染 //this.needsUpdate = true
  19384. };
  19385. viewer.mapViewer && viewer.mapViewer.addEventListener("camera_changed", clear);
  19386. viewer.addEventListener("camera_changed", clear);
  19387. /* if(viewer.viewports.length == 1){//直接更新。如果有多个不在这更新,在"render.begin"
  19388. this.update(e)
  19389. } */
  19390. var applyMatrix = e => {
  19391. this.applyMatrix(e);
  19392. };
  19393. viewer.addEventListener("raycaster", applyMatrix); //before render
  19394. viewer.addEventListener("render.begin", applyMatrix); //before render
  19395. viewer.addEventListener("render.begin2", applyMatrix);
  19396. viewer.addEventListener("cameraSetLayers", applyMatrix);
  19397. this.addEventListener('dispose', () => {
  19398. viewer.mapViewer && viewer.mapViewer.removeEventListener("camera_changed", clear);
  19399. viewer.removeEventListener("camera_changed", clear);
  19400. viewer.removeEventListener("raycaster", applyMatrix); //before render
  19401. viewer.removeEventListener("render.begin", applyMatrix);
  19402. viewer.removeEventListener("render.begin2", applyMatrix);
  19403. });
  19404. }
  19405. set visible(v) {
  19406. var oldV = this.visible_;
  19407. this.visible_ = v;
  19408. if (v && !oldV) {
  19409. this.matrixMap && this.matrixMap.clear(); //this.update() //update内有unableCompute会无限回调
  19410. }
  19411. }
  19412. get visible() {
  19413. return this.visible_;
  19414. }
  19415. realVisible(viewport, interactables /* , raycaster */) {
  19416. if (interactables) {
  19417. if (!interactables.some(object => {
  19418. //interactables中是否能找到this
  19419. var finded;
  19420. object.traverse(object => {
  19421. if (object == this) {
  19422. finded = true;
  19423. return {
  19424. stopContinue: true
  19425. };
  19426. }
  19427. });
  19428. return finded;
  19429. })) return;
  19430. }
  19431. /* if(interactables && viewport.name == 'mapViewport'){
  19432. console.log(this)
  19433. } */
  19434. if (!( /* raycaster || */viewport.camera).layers.test(this.layers)) {
  19435. //如地图上一般不可见测量线
  19436. return false;
  19437. }
  19438. if (!this.visible && this.unvisibleReasons && this.unvisibleReasons.some(e => e.reason != 'unableCompute')) {
  19439. return false;
  19440. }
  19441. var v = true;
  19442. var parent = this.parent;
  19443. var lastParent = this;
  19444. while (parent) {
  19445. if (parent.visible === false) {
  19446. v = false;
  19447. break;
  19448. }
  19449. lastParent = parent;
  19450. parent = parent.parent;
  19451. }
  19452. if (v && !(lastParent instanceof Scene)) {
  19453. //已被删除
  19454. v = false;
  19455. }
  19456. /* if(!this.latestRealVisi && v){//变为可见后先update
  19457. this.latestRealVisi = true
  19458. setTimeout(()=>{
  19459. this.update()
  19460. },1)//延迟 防止无限调用
  19461. return false
  19462. }
  19463. this.latestRealVisi = v */
  19464. return v;
  19465. }
  19466. waitUpdate() {
  19467. this.matrixMap.clear(); //清空后在所有viewport上都必须更新才能渲染
  19468. //viewer.dispatchEvent('content_changed')
  19469. }
  19470. update() {
  19471. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  19472. if (!e.viewport) {
  19473. var viewports = this.viewports || viewer.viewports;
  19474. if (!viewports) return;
  19475. viewports.forEach(view => {
  19476. this.update({
  19477. viewport: view
  19478. });
  19479. });
  19480. return;
  19481. }
  19482. if (!this.root || !this.realVisible(e.viewport, e.interactables) /* this.visible */) return;
  19483. if (this.viewports && !this.viewports.includes(e.viewport)) return;
  19484. if (e.viewport.name == 'magnifier') return;
  19485. var camera = e.viewport.camera;
  19486. //rotation
  19487. if (!this.dontFixOrient) {
  19488. //orthoCamera一般要加dontFixOrient
  19489. var orient2dAngle;
  19490. if (this.root.lineDir) {
  19491. this.root.updateMatrix(); //先更新,getWorldPosition才能得到正确的
  19492. this.root.updateMatrixWorld(true);
  19493. var center = this.root.getWorldPosition(new Vector3());
  19494. //由于两个端点容易在屏幕外,所以使用center和center加dir
  19495. var setVisi = state => {
  19496. this.visiMap.set(e.viewport, state);
  19497. Potree.Utils.updateVisible(this, 'unableCompute', !!state);
  19498. };
  19499. var renderer = e.viewer ? e.viewer.renderer : e.renderer;
  19500. var r1 = Potree.Utils.getPos2d(center, e.viewport, renderer.domElement.parentElement, renderer);
  19501. //let r1 = Potree.Utils.getPos2d(center, e.viewport, viewer.renderArea, viewer.renderer);
  19502. if (!r1.trueSide) return setVisi(false); // 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了
  19503. var r2, point2;
  19504. var p2State = '',
  19505. len = 1,
  19506. p2StateHistory = [];
  19507. while (p2State != 'got' && p2StateHistory.length < 10) {
  19508. point2 = center.clone().add(this.root.lineDir.clone().multiplyScalar(len));
  19509. r2 = Potree.Utils.getPos2d(point2, e.viewport, renderer.domElement.parentElement, renderer);
  19510. if (!r2.trueSide) {
  19511. //很少遇到点2在背面的
  19512. if (!p2StateHistory.includes('tooLong-reverse')) {
  19513. p2State = 'tooLong-reverse'; //先尝试反向
  19514. len = -len;
  19515. } else {
  19516. p2State = 'tooLong';
  19517. len = len / 2;
  19518. }
  19519. } else {
  19520. var _dis = r2.pos.distanceTo(r1.pos);
  19521. if (math.closeTo(_dis, 0)) {
  19522. //console.log('dis == 0')
  19523. setVisi(false);
  19524. return;
  19525. break;
  19526. }
  19527. if (_dis < 10 && !p2StateHistory.includes('tooLong')) {
  19528. //和r1的屏幕距离太近,要加长,否则精度过低
  19529. p2State = 'tooShort';
  19530. len = 100 / _dis * len;
  19531. } else {
  19532. p2State = 'got';
  19533. break;
  19534. }
  19535. }
  19536. p2StateHistory.push(p2State);
  19537. }
  19538. //console.log(p2StateHistory,len)
  19539. if (!r2.trueSide) {
  19540. return setVisi(false); //, console.log(' !r2.trueSide', )
  19541. }
  19542. var p1 = r1.pos,
  19543. p2 = r2.pos;
  19544. if (p2StateHistory.filter(e => e == 'tooLong-reverse').length % 2 == 1) {
  19545. //反,for marker
  19546. p2 = r1.pos, p1 = r2.pos;
  19547. }
  19548. var vec = new Vector2().subVectors(p1, p2);
  19549. orient2dAngle = -vec.angle(); //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。
  19550. var y = Math.abs(this.position.y);
  19551. var facePlane = this.root.measure && this.root.measure.facePlane;
  19552. var eyeDir = new Vector3().subVectors(center, camera.position);
  19553. var clockWise = facePlane && facePlane.normal.dot(eyeDir /* e.viewport.view.direction */) < 0;
  19554. if (p1.x < p2.x) {
  19555. orient2dAngle += Math.PI; //避免字是倒着的情况。(使字一直在线的下方)
  19556. clockWise != void 0 && (this.position.y = clockWise ? y : -y);
  19557. } else {
  19558. clockWise != void 0 && (this.position.y = clockWise ? -y : y); //使area类型的edgeLabel都在外侧
  19559. }
  19560. //this.parent.text && console.log(this.parent.text, clockWise, this.position.y, e.viewport.name /* THREE.Math.radToDeg(angle), p1.x < p2.x */ )
  19561. setVisi(true);
  19562. }
  19563. var parentQua = this.root.parent.getWorldQuaternion(new Quaternion());
  19564. this.root.quaternion.multiplyQuaternions(parentQua.invert(), camera.quaternion); //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion
  19565. if (orient2dAngle) {
  19566. var qua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), orient2dAngle);
  19567. this.root.quaternion.multiply(qua);
  19568. }
  19569. }
  19570. //scale
  19571. var info = this.sizeInfo;
  19572. if (info) {
  19573. this.root.updateMatrix(); //先更新,getWorldPosition才能得到正确的
  19574. this.root.updateMatrixWorld(true);
  19575. var scale;
  19576. if (info.nearBound == void 0 && info.farBound != void 0 || info.nearBound != void 0 && info.farBound == void 0) {
  19577. //仅限制最大或最小的话,不判断像素大小,直接限制mesh的scale
  19578. //这个判断也可以写到getScaleForConstantSize里,可以更严谨控制像素宽度,这里只简单计算大小
  19579. var dis = camera.position.distanceTo(this.root.getWorldPosition(new Vector3()));
  19580. if (info.farBound == void 0 && dis < info.nearBound) {
  19581. scale = info.scale * dis / info.nearBound;
  19582. } else if (info.nearBound == void 0 && dis > info.farBound) {
  19583. scale = info.scale * dis / info.farBound;
  19584. } else {
  19585. scale = info.scale;
  19586. }
  19587. } else {
  19588. scale = math.getScaleForConstantSize($.extend(info, {
  19589. //规定下最小最大像素
  19590. camera,
  19591. position: this.root.getWorldPosition(new Vector3()),
  19592. resolution: e.viewport.resolution //2
  19593. }));
  19594. }
  19595. if (!isNaN(scale)) {
  19596. this.root.scale.set(scale, scale, scale);
  19597. }
  19598. }
  19599. this.updateMatrix();
  19600. //this.root.updateMatrixWorld(true)
  19601. //console.log(this.root.text, this.root.matrix.elements)
  19602. this.matrixMap.set(e.viewport, this.matrix.clone());
  19603. if (this.root != this) {
  19604. this.root.updateMatrix(); //因this.position可能在两个viewport不同
  19605. this.matrixMapRoot.set(e.viewport, this.root.matrix.clone());
  19606. }
  19607. this.needsUpdate = false;
  19608. this.useViewport = e.viewport;
  19609. }
  19610. applyMatrix(e) {
  19611. if (!e) e = {
  19612. viewport: viewer.mainViewport
  19613. }; //随便写一个viewport
  19614. var visi = this.visiMap.get(e.viewport); //还原可见性
  19615. Potree.Utils.updateVisible(this, 'unableCompute', visi == false ? false : true);
  19616. /* if(e.viewport.name == 'mapViewport' && visi && this.visiMap.get(viewer.mainViewport) == false){
  19617. console.log(1)
  19618. } */
  19619. if (e.viewport.name == 'magnifier') return;
  19620. if (this.viewports && !this.viewports.includes(e.viewport)) return;
  19621. if (!this.root || !this.realVisible(e.viewport, e.interactables)) return;
  19622. var matrix = this.matrixMap.get(e.viewport);
  19623. if (!matrix) {
  19624. this.update(e);
  19625. matrix = this.matrixMap.get(e.viewport);
  19626. if (!matrix) return;
  19627. }
  19628. if (e.viewport == this.useViewport) {
  19629. return;
  19630. }
  19631. this.useViewport = e.viewport;
  19632. this.matrix.copy(matrix);
  19633. if (this.root != this) {
  19634. var matrix2 = this.matrixMapRoot.get(e.viewport);
  19635. this.root.matrix.copy(matrix2);
  19636. }
  19637. e.raycaster && this.root.updateMatrixWorld(true); //渲染前会自动updateMatrixWorld,但raycaster不会
  19638. //console.log(this.root.name + e.viewport.name + " : "+this.root.matrixWorld.elements)
  19639. }
  19640. setUniforms(name, value) {
  19641. this.material.setUniforms(name, value);
  19642. }
  19643. dispose() {
  19644. this.removeAllListeners();
  19645. this.parent && this.parent.remove(this);
  19646. this.dispatchEvent('dispose');
  19647. }
  19648. }
  19649. /*
  19650. let orient2d
  19651. if(this.lineDir){
  19652. this.root.updateMatrix();//先更新,getWorldPosition才能得到正确的
  19653. this.root.updateMatrixWorld(true)
  19654. let center = this.root.getWorldPosition(new THREE.Vector3())
  19655. //由于两个端点容易在屏幕外,所以使用center和center加dir
  19656. let lineDir = this.lineDir.clone();
  19657. let r1 = Potree.Utils.getPos2d(center, camera, viewer.renderArea, e.viewport);
  19658. if(!r1.trueSide)return Potree.Utils.updateVisible(this, 'unableCompute', false);// 但这句会使realVisible为false从而无法更新//console.error('!r1.trueSide') //中心点如果在背面直接不渲染了
  19659. let r2, point2
  19660. let p2State = '', len=1, p2StateHistory = []
  19661. while(p2State != 'got' && p2StateHistory.length<10){
  19662. point2 = center.clone().add(lineDir.multiplyScalar(len));
  19663. r2 = Potree.Utils.getPos2d(point2, camera, viewer.renderArea, e.viewport);
  19664. if(!r2.trueSide){ //很少遇到点2在背面的
  19665. if(!p2StateHistory.includes('tooLong-reverse')){
  19666. p2State = 'tooLong-reverse' //先尝试反向
  19667. len = -len
  19668. }else{
  19669. p2State = 'tooLong'
  19670. len = len / 2
  19671. }
  19672. }else{
  19673. let dis = r2.pos.distanceTo(r1.pos)
  19674. if(dis == 0){
  19675. //console.log('dis == 0')
  19676. Potree.Utils.updateVisible(this, 'unableCompute', false)
  19677. return
  19678. break
  19679. }
  19680. if(dis<10 && !p2StateHistory.includes('tooLong')){//和r1的屏幕距离太近,要加长,否则精度过低
  19681. p2State = 'tooShort'
  19682. len = 100/dis * len
  19683. }else{
  19684. p2State = 'got'; break;
  19685. }
  19686. }
  19687. p2StateHistory.push(p2State)
  19688. }
  19689. //console.log(p2StateHistory,len)
  19690. if(!r2.trueSide){
  19691. return Potree.Utils.updateVisible(this, 'unableCompute', false)//, console.log(' !r2.trueSide', )
  19692. }
  19693. Potree.Utils.updateVisible(this, 'unableCompute', true)
  19694. let p1 = r1.pos, p2 = r2.pos
  19695. let vec = new THREE.Vector2().subVectors(p1,p2);
  19696. let angle = -vec.angle() //根据测量线在屏幕上的角度在旋转label,使之和屏幕上的二维线平行。
  19697. if(p1.x < p2.x) angle += Math.PI //避免字是倒着的情况
  19698. orient2d = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), angle)
  19699. //console.log(this.parent.text, THREE.Math.radToDeg(angle), p1.x < p2.x )
  19700. }
  19701. let parentQua = this.root.parent.getWorldQuaternion(new THREE.Quaternion)
  19702. this.root.quaternion.multiplyQuaternions(parentQua.invert(),camera.quaternion) //乘上parentQua.invert()是为了中和掉父结点的qua,使只剩下camera.quaternion
  19703. if(this.lineDir){
  19704. this.root.quaternion.multiply(orient2d)
  19705. }
  19706. */
  19707. // /**
  19708. //可能还是要用html写,因为要加按钮和图片
  19709. class TextSprite$2 extends Object3D {
  19710. //注:为了分两层控制scale,不直接extend Sprite
  19711. constructor() {
  19712. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  19713. super();
  19714. var map = new Texture();
  19715. map.minFilter = LinearFilter;
  19716. map.magFilter = LinearFilter;
  19717. this.sprite = new Sprite$2(Object.assign({
  19718. root: this
  19719. }, options, {
  19720. map
  19721. }));
  19722. this.add(this.sprite);
  19723. this.fontWeight = options.fontWeight == void 0 ? 'Bold' : options.fontWeight;
  19724. this.rectBorderThick = options.rectBorderThick || 0;
  19725. this.textBorderThick = options.textBorderThick || 0;
  19726. this.fontface = 'Arial';
  19727. this.fontsize = options.fontsize || 16;
  19728. this.textBorderColor = options.textBorderColor ? Common.CloneObject(options.textBorderColor) : {
  19729. r: 0,
  19730. g: 0,
  19731. b: 0,
  19732. a: 0.0
  19733. };
  19734. this.backgroundColor = options.backgroundColor ? Common.CloneObject(options.backgroundColor) : {
  19735. r: 255,
  19736. g: 255,
  19737. b: 255,
  19738. a: 1.0
  19739. };
  19740. this.textColor = options.textColor ? Common.CloneObject(options.textColor) : {
  19741. r: 0,
  19742. g: 0,
  19743. b: 0,
  19744. a: 1.0
  19745. };
  19746. this.borderColor = options.borderColor ? Common.CloneObject(options.borderColor) : {
  19747. r: 0,
  19748. g: 0,
  19749. b: 0,
  19750. a: 0.0
  19751. };
  19752. this.borderRadius = options.borderRadius || 6;
  19753. this.margin = options.margin;
  19754. this.setText(options.text);
  19755. this.name = options.name;
  19756. //this.setText(text);
  19757. }
  19758. setText(text) {
  19759. if (text == void 0) text = '';
  19760. if (this.text !== text) {
  19761. if (!(text instanceof Array)) {
  19762. this.text = [text + ''];
  19763. } else this.text = text;
  19764. this.updateTexture();
  19765. this.sprite.waitUpdate(); //重新计算各个viewport的matrix
  19766. }
  19767. }
  19768. setTextColor(color) {
  19769. this.textColor = Common.CloneObject(color);
  19770. this.updateTexture();
  19771. }
  19772. setBorderColor(color) {
  19773. this.borderColor = Common.CloneObject(color);
  19774. this.updateTexture();
  19775. }
  19776. setBackgroundColor(color) {
  19777. this.backgroundColor = Common.CloneObject(color);
  19778. this.updateTexture();
  19779. }
  19780. setPos(pos) {
  19781. this.position.copy(pos);
  19782. this.sprite.waitUpdate();
  19783. }
  19784. update() {
  19785. this.sprite.waitUpdate();
  19786. }
  19787. /* setVisible(v){
  19788. Potree.Utils.updateVisible(this, 'setVisible', v)
  19789. } */
  19790. setUniforms(name, value) {
  19791. this.sprite.setUniforms(name, value);
  19792. }
  19793. updateTexture1() {
  19794. var canvas = document.createElement('canvas');
  19795. var context = canvas.getContext('2d');
  19796. var r = window.devicePixelRatio;
  19797. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  19798. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  19799. //this.text = '啊啊啊啊啊啊fag'
  19800. var metrics = context.measureText(this.text);
  19801. var textWidth = metrics.width;
  19802. var margin = (this.margin ? new Vector2().copy(this.margin) : new Vector2(this.fontsize, Math.max(this.fontsize * 0.4, 10))).clone().multiplyScalar(r);
  19803. var spriteWidth = 2 * margin.x + textWidth + 2 * this.rectBorderThick * r;
  19804. var spriteHeight = 2 * margin.y + this.fontsize * r + 2 * this.rectBorderThick * r;
  19805. context.canvas.width = spriteWidth;
  19806. context.canvas.height = spriteHeight;
  19807. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  19808. /* let diff = 2//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  19809. context.textBaseline = "middle"
  19810. */
  19811. var expand = Math.max(1, Math.pow(this.fontsize / 16, 1.3)) * r; // 针对英文大部分在baseLine之上所以降低一点,或者可以识别当不包含jgqp时才加这个值
  19812. //canvas原点在左上角
  19813. context.textBaseline = 'alphabetic'; // "middle" //设置文字基线。当起点y设置为0时,只有该线以下的部分被绘制出来。middle时文字显示一半(但是对该字体所有字的一半,有的字是不一定显示一半的,尤其汉字),alphabetic时是英文字母的那条基线。
  19814. //let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; // 当前文本字符串在这个字体下用的实际高度
  19815. //文字y向距离从textBaseline向上算
  19816. var actualBoundingBoxAscent = metrics.actualBoundingBoxAscent == void 0 ? this.fontsize * r * 0.8 : metrics.actualBoundingBoxAscent; //有的流览器没有。只能大概给一个
  19817. var y = actualBoundingBoxAscent + margin.y + expand;
  19818. //console.log(this.text, 'y' , y, 'actualBoundingBoxAscent', metrics.actualBoundingBoxAscent,'expand',expand )
  19819. // border color
  19820. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')';
  19821. var rectBorderThick = this.rectBorderThick * r;
  19822. context.lineWidth = rectBorderThick;
  19823. // background color
  19824. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  19825. this.roundRect(context, rectBorderThick / 2, rectBorderThick / 2, spriteWidth - rectBorderThick, spriteHeight - rectBorderThick, this.borderRadius * r);
  19826. // text color
  19827. if (this.textBorderThick) {
  19828. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' + this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  19829. context.lineWidth = this.textBorderThick * r;
  19830. context.strokeText(this.text, rectBorderThick + margin.x, y /* spriteHeight/2 + diff */);
  19831. }
  19832. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')';
  19833. context.fillText(this.text, rectBorderThick + margin.x, y /* spriteHeight/2 + diff */); //x,y
  19834. var texture = new Texture(canvas);
  19835. texture.minFilter = LinearFilter;
  19836. texture.magFilter = LinearFilter;
  19837. texture.needsUpdate = true;
  19838. //this.material.needsUpdate = true;
  19839. if (this.sprite.material.map) {
  19840. this.sprite.material.map.dispose();
  19841. }
  19842. this.sprite.material.map = texture;
  19843. this.sprite.scale.set(spriteWidth * 0.01 / r, spriteHeight * 0.01 / r, 1.0);
  19844. }
  19845. updateTexture() {
  19846. var canvas = document.createElement('canvas');
  19847. var context = canvas.getContext('2d');
  19848. var r = window.devicePixelRatio;
  19849. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  19850. //context["font-weight"] = 100; //语法与 CSS font 属性相同。
  19851. //this.text = '啊啊啊啊啊啊fag'
  19852. var textMaxWidth = 0,
  19853. infos = [];
  19854. for (var text of this.text) {
  19855. var metrics = context.measureText(text);
  19856. var textWidth = metrics.width;
  19857. infos.push(metrics);
  19858. textMaxWidth = Math.max(textMaxWidth, textWidth);
  19859. }
  19860. var margin = (this.margin ? new Vector2().copy(this.margin) : new Vector2(this.fontsize, Math.max(this.fontsize * 0.4, 10))).clone().multiplyScalar(r);
  19861. var lineSpace = (this.fontsize + margin.y) * 0.5;
  19862. var spriteWidth = 2 * margin.x + textMaxWidth + 2 * (this.rectBorderThick + this.textBorderThick) * r; //还要考虑this.textshadowColor,太麻烦了不写了
  19863. var spriteHeight = 2 * margin.y + (this.fontsize + this.textBorderThick * 2) * r * this.text.length + 2 * this.rectBorderThick * r + lineSpace * (this.text.length - 1);
  19864. context.canvas.width = spriteWidth;
  19865. context.canvas.height = spriteHeight;
  19866. context.font = this.fontWeight + ' ' + this.fontsize * r + 'px ' + this.fontface;
  19867. if (spriteWidth > 4000) {
  19868. console.error('spriteWidth', spriteWidth, 'spriteHeight', spriteHeight, this.fontsize, r, this.text, margin);
  19869. }
  19870. /* let diff = 2//针对英文大部分在baseLine之上所以降低一点(metrics.fontBoundingBoxAscent - metrics.fontBoundingBoxDescent) / 2
  19871. context.textBaseline = "middle"
  19872. */
  19873. var expand = Math.max(1, Math.pow(this.fontsize / 16, 1.3)) * r; // 针对英文大部分在baseLine之上所以降低一点,或者可以识别当不包含jgqp时才加这个值
  19874. //canvas原点在左上角
  19875. context.textBaseline = 'alphabetic'; // "middle" //设置文字基线。当起点y设置为0时,只有该线以下的部分被绘制出来。middle时文字显示一半(但是对该字体所有字的一半,有的字是不一定显示一半的,尤其汉字),alphabetic时是英文字母的那条基线。
  19876. // border color
  19877. context.strokeStyle = 'rgba(' + this.borderColor.r + ',' + this.borderColor.g + ',' + this.borderColor.b + ',' + this.borderColor.a + ')';
  19878. var rectBorderThick = this.rectBorderThick * r;
  19879. context.lineWidth = rectBorderThick;
  19880. // background color
  19881. context.fillStyle = 'rgba(' + this.backgroundColor.r + ',' + this.backgroundColor.g + ',' + this.backgroundColor.b + ',' + this.backgroundColor.a + ')';
  19882. this.roundRect(context, rectBorderThick / 2, rectBorderThick / 2, spriteWidth - rectBorderThick, spriteHeight - rectBorderThick, this.borderRadius * r);
  19883. context.fillStyle = 'rgba(' + this.textColor.r + ',' + this.textColor.g + ',' + this.textColor.b + ',' + this.textColor.a + ')';
  19884. var y = margin.y;
  19885. for (var i = 0; i < this.text.length; i++) {
  19886. //let actualHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent // 当前文本字符串在这个字体下用的实际高度
  19887. //文字y向距离从textBaseline向上算
  19888. var actualBoundingBoxAscent = infos[i].actualBoundingBoxAscent == void 0 ? this.fontsize * r * 0.8 : infos[i].actualBoundingBoxAscent; //有的流览器没有。只能大概给一个
  19889. y += actualBoundingBoxAscent + expand + this.textBorderThick;
  19890. //console.log(actualBoundingBoxAscent)
  19891. //console.log(this.text, 'y' , y, 'actualBoundingBoxAscent', metrics.actualBoundingBoxAscent,'expand',expand )
  19892. var textLeftSpace = (textMaxWidth - infos[i].width) / 2;
  19893. var x = this.rectBorderThick + margin.x + textLeftSpace;
  19894. // text color
  19895. if (this.textBorderThick) {
  19896. context.strokeStyle = 'rgba(' + this.textBorderColor.r + ',' + this.textBorderColor.g + ',' + this.textBorderColor.b + ',' + this.textBorderColor.a + ')';
  19897. context.lineWidth = this.textBorderThick * r;
  19898. context.strokeText(this.text[i], x, y);
  19899. }
  19900. if (this.textshadowColor) {
  19901. context.shadowOffsetX = 0;
  19902. context.shadowOffsetY = 0;
  19903. context.shadowColor = this.textshadowColor;
  19904. context.shadowBlur = 12 * r;
  19905. }
  19906. context.fillText(this.text[i], x, y);
  19907. y += lineSpace;
  19908. }
  19909. var texture = new Texture(canvas);
  19910. texture.minFilter = LinearFilter;
  19911. texture.magFilter = LinearFilter;
  19912. texture.needsUpdate = true;
  19913. //this.material.needsUpdate = true;
  19914. if (this.sprite.material.map) {
  19915. this.sprite.material.map.dispose();
  19916. }
  19917. this.sprite.material.map = texture;
  19918. this.sprite.scale.set(spriteWidth * 0.01 / r, spriteHeight * 0.01 / r, 1.0);
  19919. }
  19920. roundRect(ctx, x, y, w, h, r) {
  19921. ctx.beginPath();
  19922. ctx.moveTo(x + r, y);
  19923. ctx.lineTo(x + w - r, y);
  19924. ctx.arcTo(x + w, y, x + w, y + r, r); //圆弧。前四个参数同quadraticCurveTo
  19925. //ctx.quadraticCurveTo(x + w, y, x + w, y + r); //二次贝塞尔曲线需要两个点。第一个点是用于二次贝塞尔计算中的控制点,第二个点是曲线的结束点。
  19926. ctx.lineTo(x + w, y + h - r);
  19927. ctx.arcTo(x + w, y + h, x + w - r, y + h, r);
  19928. ctx.lineTo(x + r, y + h);
  19929. ctx.arcTo(x, y + h, x, y + h - r, r);
  19930. ctx.lineTo(x, y + r);
  19931. ctx.arcTo(x, y, x + r, y, r);
  19932. ctx.closePath();
  19933. ctx.fill();
  19934. ctx.stroke();
  19935. }
  19936. dispose() {
  19937. this.sprite.material.uniforms.map.value.dispose();
  19938. this.parent && this.parent.remove(this);
  19939. this.sprite.dispose();
  19940. this.removeAllListeners();
  19941. this.dispatchEvent('dispose');
  19942. }
  19943. }
  19944. /*
  19945. z
  19946. |
  19947. |
  19948. |
  19949. |
  19950. x <-------| 中心为点云position加boudingbox中心
  19951. /
  19952. /
  19953. y
  19954. */
  19955. var lineLen$1 = 2,
  19956. stemLen = 4,
  19957. arrowLen = 2,
  19958. lineDisToStem = 5;
  19959. var opacity = 0.5;
  19960. class Axis extends Object3D {
  19961. // 坐标轴
  19962. constructor() {
  19963. super();
  19964. this.getArrow();
  19965. this.createArrows();
  19966. //this.position.copy(position) 点云的中心点就是在(0,0,0)
  19967. //this.scale.set(2,2,2)
  19968. /* viewer.addEventListener('camera_changed', e => {
  19969. if(e.viewport.name != 'MainView')return //只调整mainView,否则需要每次渲染前调整。缺点:地图上的大小变来变去
  19970. let s = Potree.math.getScaleForConstantSize( {//规定下最小最大像素
  19971. width2d:50, camera:e.camera , position:this.position,
  19972. resolution: e.viewport.resolution//2
  19973. })
  19974. this.scale.set(s,s,s)
  19975. }) */
  19976. }
  19977. getArrow() {
  19978. var arrowGroup = new Object3D();
  19979. var line = LineDraw.createLine([new Vector3(), new Vector3(0, 0, lineLen$1)]);
  19980. var stem = new Mesh(new BoxGeometry(0.3, 0.3, stemLen));
  19981. stem.position.set(0, 0, lineLen$1 + lineDisToStem + stemLen / 2);
  19982. var arrow = new Mesh(new CylinderBufferGeometry(0, 0.6, arrowLen, 12, 1, false)); //radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2
  19983. arrow.position.set(0, 0, lineLen$1 + lineDisToStem + stemLen + arrowLen / 2);
  19984. arrow.rotation.set(Math.PI / 2, 0, 0);
  19985. arrowGroup.add(stem);
  19986. arrowGroup.add(line);
  19987. arrowGroup.add(arrow);
  19988. this.arrowGroup = arrowGroup;
  19989. }
  19990. createArrows() {
  19991. var material = new MeshBasicMaterial({
  19992. color: "#00d7df",
  19993. side: 2,
  19994. transparent: true,
  19995. opacity: 0.8,
  19996. depthWrite: false
  19997. });
  19998. ['x', 'y', 'z'].forEach(axisText => {
  19999. var color = new Color().set(Potree.config.axis[axisText].color);
  20000. var group = this.arrowGroup.clone();
  20001. group.children.forEach(e => {
  20002. e.material = e.material.clone();
  20003. /* e.material.opacity = opacity
  20004. e.material.transparent = true */
  20005. e.material.color.copy(color);
  20006. });
  20007. var label = this.createLabel(axisText, color);
  20008. label.position.set(0, 0, lineLen$1 + stemLen + arrowLen + lineDisToStem + 3);
  20009. group.add(label);
  20010. if (axisText == 'y') {
  20011. group.rotation.x = -Math.PI / 2;
  20012. } else if (axisText == 'x') {
  20013. group.rotation.y = Math.PI / 2;
  20014. }
  20015. this.add(group);
  20016. });
  20017. }
  20018. createLabel(text, color) {
  20019. var label = new TextSprite$2({
  20020. //无法解决 因其祖先有设定quaternion, 无法对着镜头
  20021. backgroundColor: {
  20022. r: 0,
  20023. g: 0,
  20024. b: 0,
  20025. a: 0
  20026. },
  20027. textColor: {
  20028. r: color.r * 255,
  20029. g: color.g * 255,
  20030. b: color.b * 255,
  20031. a: 1
  20032. },
  20033. fontsize: 120,
  20034. //useDepth : true ,
  20035. renderOrder: 5,
  20036. // pickOrder:5,
  20037. text,
  20038. name: 'axis'
  20039. });
  20040. label.scale.set(3, 3, 3);
  20041. return label;
  20042. }
  20043. /* createLabel(text,color){
  20044. var canvas = document.createElement("canvas")
  20045. var context = canvas.getContext("2d");
  20046. canvas.width = 256,
  20047. canvas.height = 256;
  20048. var fontSize = 120
  20049. context.fillStyle = color //"#00ffee";
  20050. context.font = "normal " + fontSize + "px 微软雅黑"
  20051. var textWidth = context.measureText(text).width;
  20052. context.clearRect(0,0,canvas.width,canvas.height);
  20053. context.fillText(text, (canvas.width - textWidth) / 2 , (canvas.height + fontSize) / 2);
  20054. var tex = new THREE.Texture(canvas);
  20055. tex.needsUpdate = true
  20056. tex.minFilter = THREE.NearestFilter//防止边缘发黑
  20057. tex.magFilter = THREE.NearestFilter//防止边缘发黑
  20058. var sprite = new THREE.Sprite(new THREE.SpriteMaterial({
  20059. map: tex , // depthWrite:false,
  20060. }))
  20061. sprite.renderOrder = 1//防止在透明后还是出现白矩形挡住其他mesh
  20062. sprite.scale.set(3,3,3)
  20063. return sprite
  20064. } */
  20065. }
  20066. class Action extends EventDispatcher$1 {
  20067. constructor() {
  20068. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  20069. super();
  20070. this.icon = args.icon || '';
  20071. this.tooltip = args.tooltip;
  20072. if (args.onclick !== undefined) {
  20073. this.onclick = args.onclick;
  20074. }
  20075. }
  20076. onclick(event) {}
  20077. pairWith(object) {}
  20078. setIcon(newIcon) {
  20079. var oldIcon = this.icon;
  20080. if (newIcon === oldIcon) {
  20081. return;
  20082. }
  20083. this.icon = newIcon;
  20084. this.dispatchEvent({
  20085. type: 'icon_changed',
  20086. action: this,
  20087. icon: newIcon,
  20088. oldIcon: oldIcon
  20089. });
  20090. }
  20091. }
  20092. ;
  20093. //Potree.Actions = {};
  20094. //
  20095. //Potree.Actions.ToggleAnnotationVisibility = class ToggleAnnotationVisibility extends Potree.Action {
  20096. // constructor (args = {}) {
  20097. // super(args);
  20098. //
  20099. // this.icon = Potree.resourcePath + '/icons/eye.svg';
  20100. // this.showIn = 'sidebar';
  20101. // this.tooltip = 'toggle visibility';
  20102. // }
  20103. //
  20104. // pairWith (annotation) {
  20105. // if (annotation.visible) {
  20106. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  20107. // } else {
  20108. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  20109. // }
  20110. //
  20111. // annotation.addEventListener('visibility_changed', e => {
  20112. // let annotation = e.annotation;
  20113. //
  20114. // if (annotation.visible) {
  20115. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  20116. // } else {
  20117. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  20118. // }
  20119. // });
  20120. // }
  20121. //
  20122. // onclick (event) {
  20123. // let annotation = event.annotation;
  20124. //
  20125. // annotation.visible = !annotation.visible;
  20126. //
  20127. // if (annotation.visible) {
  20128. // this.setIcon(Potree.resourcePath + '/icons/eye.svg');
  20129. // } else {
  20130. // this.setIcon(Potree.resourcePath + '/icons/eye_crossed.svg');
  20131. // }
  20132. // }
  20133. //};
  20134. class Annotation extends EventDispatcher$1 {
  20135. constructor() {
  20136. var _this;
  20137. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  20138. super();
  20139. _this = this;
  20140. this.scene = null;
  20141. this._title = args.title || 'No Title';
  20142. this._description = args.description || '';
  20143. this.offset = new Vector3();
  20144. this.uuid = MathUtils.generateUUID();
  20145. if (!args.position) {
  20146. this.position = null;
  20147. } else if (args.position.x != null) {
  20148. this.position = args.position;
  20149. } else {
  20150. this.position = new Vector3(...args.position);
  20151. }
  20152. this.cameraPosition = args.cameraPosition instanceof Array ? new Vector3().fromArray(args.cameraPosition) : args.cameraPosition;
  20153. this.cameraTarget = args.cameraTarget instanceof Array ? new Vector3().fromArray(args.cameraTarget) : args.cameraTarget;
  20154. this.radius = args.radius;
  20155. this.view = args.view || null;
  20156. this.keepOpen = false;
  20157. this.descriptionVisible = false;
  20158. this.showDescription = true;
  20159. this.actions = args.actions || [];
  20160. this.isHighlighted = false;
  20161. this._visible = true;
  20162. this.__visible = true;
  20163. this._display = true;
  20164. this._expand = false;
  20165. this.collapseThreshold = [args.collapseThreshold, 100].find(e => e !== undefined);
  20166. this.children = [];
  20167. this.parent = null;
  20168. this.boundingBox = new Box3();
  20169. var iconClose = exports.resourcePath + '/icons/close.svg';
  20170. this.domElement = $("\n\t\t\t<div class=\"annotation\" oncontextmenu=\"return false;\">\n\t\t\t\t<div class=\"annotation-titlebar\">\n\t\t\t\t\t<span class=\"annotation-label\"></span>\n\t\t\t\t</div>\n\t\t\t\t<div class=\"annotation-description\">\n\t\t\t\t\t<span class=\"annotation-description-close\">\n\t\t\t\t\t\t<img src=\"".concat(iconClose, "\" width=\"16px\">\n\t\t\t\t\t</span>\n\t\t\t\t\t<span class=\"annotation-description-content\">").concat(this._description, "</span>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  20171. this.elTitlebar = this.domElement.find('.annotation-titlebar');
  20172. this.elTitle = this.elTitlebar.find('.annotation-label');
  20173. this.elTitle.append(this._title);
  20174. this.elDescription = this.domElement.find('.annotation-description');
  20175. this.elDescriptionClose = this.elDescription.find('.annotation-description-close');
  20176. // this.elDescriptionContent = this.elDescription.find(".annotation-description-content");
  20177. this.clickTitle = () => {
  20178. if (this.hasView()) {
  20179. this.moveHere(this.scene.getActiveCamera());
  20180. }
  20181. this.dispatchEvent({
  20182. type: 'click',
  20183. target: this
  20184. });
  20185. };
  20186. this.elTitle.click(this.clickTitle);
  20187. this.actions = this.actions.map(a => {
  20188. if (a instanceof Action) {
  20189. return a;
  20190. } else {
  20191. return new Action(a);
  20192. }
  20193. });
  20194. for (var action of this.actions) {
  20195. action.pairWith(this);
  20196. }
  20197. var actions = this.actions.filter(a => a.showIn === undefined || a.showIn.includes('scene'));
  20198. var _loop = function _loop(_action) {
  20199. var elButton = $("<img src=\"".concat(_action.icon, "\" class=\"annotation-action-icon\">"));
  20200. _this.elTitlebar.append(elButton);
  20201. elButton.click(() => _action.onclick({
  20202. annotation: _this
  20203. }));
  20204. };
  20205. for (var _action of actions) {
  20206. _loop(_action);
  20207. }
  20208. this.elDescriptionClose.hover(e => this.elDescriptionClose.css('opacity', '1'), e => this.elDescriptionClose.css('opacity', '0.5'));
  20209. this.elDescriptionClose.click(e => this.setHighlighted(false));
  20210. // this.elDescriptionContent.html(this._description);
  20211. this.domElement.mouseenter(e => this.setHighlighted(true));
  20212. this.domElement.mouseleave(e => this.setHighlighted(false));
  20213. this.domElement.on('touchstart', e => {
  20214. this.setHighlighted(!this.isHighlighted);
  20215. });
  20216. this.display = false;
  20217. //this.display = true;
  20218. }
  20219. installHandles(viewer) {
  20220. if (this.handles !== undefined) {
  20221. return;
  20222. }
  20223. var domElement = $("\n\t\t\t<div style=\"position: absolute; left: 300; top: 200; pointer-events: none\">\n\t\t\t\t<svg width=\"300\" height=\"600\">\n\t\t\t\t\t<line x1=\"0\" y1=\"0\" x2=\"1200\" y2=\"200\" style=\"stroke: black; stroke-width:2\" />\n\t\t\t\t\t<circle cx=\"50\" cy=\"50\" r=\"4\" stroke=\"black\" stroke-width=\"2\" fill=\"gray\" />\n\t\t\t\t\t<circle cx=\"150\" cy=\"50\" r=\"4\" stroke=\"black\" stroke-width=\"2\" fill=\"gray\" />\n\t\t\t\t</svg>\n\t\t\t</div>\n\t\t");
  20224. var svg = domElement.find("svg")[0];
  20225. var elLine = domElement.find("line")[0];
  20226. var elStart = domElement.find("circle")[0];
  20227. var elEnd = domElement.find("circle")[1];
  20228. var setCoordinates = (start, end) => {
  20229. elStart.setAttribute("cx", "".concat(start.x));
  20230. elStart.setAttribute("cy", "".concat(start.y));
  20231. elEnd.setAttribute("cx", "".concat(end.x));
  20232. elEnd.setAttribute("cy", "".concat(end.y));
  20233. elLine.setAttribute("x1", start.x);
  20234. elLine.setAttribute("y1", start.y);
  20235. elLine.setAttribute("x2", end.x);
  20236. elLine.setAttribute("y2", end.y);
  20237. var box = svg.getBBox();
  20238. svg.setAttribute("width", "".concat(box.width));
  20239. svg.setAttribute("height", "".concat(box.height));
  20240. svg.setAttribute("viewBox", "".concat(box.x, " ").concat(box.y, " ").concat(box.width, " ").concat(box.height));
  20241. var ya = start.y - end.y;
  20242. var xa = start.x - end.x;
  20243. if (ya > 0) {
  20244. start.y = start.y - ya;
  20245. }
  20246. if (xa > 0) {
  20247. start.x = start.x - xa;
  20248. }
  20249. domElement.css("left", "".concat(start.x, "px"));
  20250. domElement.css("top", "".concat(start.y, "px"));
  20251. };
  20252. $(viewer.renderArea).append(domElement);
  20253. var annotationStartPos = this.position.clone();
  20254. var annotationStartOffset = this.offset.clone();
  20255. $(this.domElement).draggable({
  20256. start: (event, ui) => {
  20257. annotationStartPos = this.position.clone();
  20258. annotationStartOffset = this.offset.clone();
  20259. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "none");
  20260. console.log($(this.domElement).find(".annotation-titlebar"));
  20261. },
  20262. stop: () => {
  20263. $(this.domElement).find(".annotation-titlebar").css("pointer-events", "");
  20264. },
  20265. drag: (event, ui) => {
  20266. var renderAreaWidth = viewer.renderer.getSize(new Vector2()).width;
  20267. //let renderAreaHeight = viewer.renderer.getSize().height;
  20268. var diff = {
  20269. x: ui.originalPosition.left - ui.position.left,
  20270. y: ui.originalPosition.top - ui.position.top
  20271. };
  20272. var nDiff = {
  20273. x: -(diff.x / renderAreaWidth) * 2,
  20274. y: diff.y / renderAreaWidth * 2
  20275. };
  20276. var camera = viewer.scene.getActiveCamera();
  20277. var oldScreenPos = new Vector3().addVectors(annotationStartPos, annotationStartOffset).project(camera);
  20278. var newScreenPos = oldScreenPos.clone();
  20279. newScreenPos.x += nDiff.x;
  20280. newScreenPos.y += nDiff.y;
  20281. var newPos = newScreenPos.clone();
  20282. newPos.unproject(camera);
  20283. var newOffset = new Vector3().subVectors(newPos, this.position);
  20284. this.offset.copy(newOffset);
  20285. }
  20286. });
  20287. var updateCallback = () => {
  20288. var position = this.position;
  20289. var scene = viewer.scene;
  20290. var renderAreaSize = viewer.renderer.getSize(new Vector2());
  20291. var renderAreaWidth = renderAreaSize.width;
  20292. var renderAreaHeight = renderAreaSize.height;
  20293. var start = this.position.clone();
  20294. var end = new Vector3().addVectors(this.position, this.offset);
  20295. var toScreen = position => {
  20296. var camera = scene.getActiveCamera();
  20297. var screenPos = new Vector3();
  20298. var worldView = new Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  20299. var ndc = new Vector4(position.x, position.y, position.z, 1.0).applyMatrix4(worldView);
  20300. // limit w to small positive value, in case position is behind the camera
  20301. ndc.w = Math.max(ndc.w, 0.1);
  20302. ndc.divideScalar(ndc.w);
  20303. screenPos.copy(ndc);
  20304. screenPos.x = renderAreaWidth * (screenPos.x + 1) / 2;
  20305. screenPos.y = renderAreaHeight * (1 - (screenPos.y + 1) / 2);
  20306. return screenPos;
  20307. };
  20308. start = toScreen(start);
  20309. end = toScreen(end);
  20310. setCoordinates(start, end);
  20311. };
  20312. viewer.addEventListener("update", updateCallback);
  20313. this.handles = {
  20314. domElement: domElement,
  20315. setCoordinates: setCoordinates,
  20316. updateCallback: updateCallback
  20317. };
  20318. }
  20319. removeHandles(viewer) {
  20320. if (this.handles === undefined) {
  20321. return;
  20322. }
  20323. //$(viewer.renderArea).remove(this.handles.domElement);
  20324. this.handles.domElement.remove();
  20325. viewer.removeEventListener("update", this.handles.updateCallback);
  20326. delete this.handles;
  20327. }
  20328. get visible() {
  20329. return this._visible;
  20330. }
  20331. set visible(value) {
  20332. if (this._visible === value) {
  20333. return;
  20334. }
  20335. this._visible = value;
  20336. //this.traverse(node => {
  20337. // node.display = value;
  20338. //});
  20339. this.dispatchEvent({
  20340. type: 'visibility_changed',
  20341. annotation: this
  20342. });
  20343. }
  20344. get display() {
  20345. return this._display;
  20346. }
  20347. set display(display) {
  20348. if (this._display === display) {
  20349. return;
  20350. }
  20351. this._display = display;
  20352. if (display) {
  20353. // this.domElement.fadeIn(200);
  20354. this.domElement.show();
  20355. } else {
  20356. // this.domElement.fadeOut(200);
  20357. this.domElement.hide();
  20358. }
  20359. }
  20360. get expand() {
  20361. return this._expand;
  20362. }
  20363. set expand(expand) {
  20364. if (this._expand === expand) {
  20365. return;
  20366. }
  20367. if (expand) {
  20368. this.display = false;
  20369. } else {
  20370. this.display = true;
  20371. this.traverseDescendants(node => {
  20372. node.display = false;
  20373. });
  20374. }
  20375. this._expand = expand;
  20376. }
  20377. get title() {
  20378. return this._title;
  20379. }
  20380. set title(title) {
  20381. if (this._title === title) {
  20382. return;
  20383. }
  20384. this._title = title;
  20385. this.elTitle.empty();
  20386. this.elTitle.append(this._title);
  20387. this.dispatchEvent({
  20388. type: "annotation_changed",
  20389. annotation: this
  20390. });
  20391. }
  20392. get description() {
  20393. return this._description;
  20394. }
  20395. set description(description) {
  20396. if (this._description === description) {
  20397. return;
  20398. }
  20399. this._description = description;
  20400. var elDescriptionContent = this.elDescription.find(".annotation-description-content");
  20401. elDescriptionContent.empty();
  20402. elDescriptionContent.append(this._description);
  20403. this.dispatchEvent({
  20404. type: "annotation_changed",
  20405. annotation: this
  20406. });
  20407. }
  20408. add(annotation) {
  20409. if (!this.children.includes(annotation)) {
  20410. this.children.push(annotation);
  20411. annotation.parent = this;
  20412. var descendants = [];
  20413. annotation.traverse(a => {
  20414. descendants.push(a);
  20415. });
  20416. for (var descendant of descendants) {
  20417. var c = this;
  20418. while (c !== null) {
  20419. c.dispatchEvent({
  20420. 'type': 'annotation_added',
  20421. 'annotation': descendant
  20422. });
  20423. c = c.parent;
  20424. }
  20425. }
  20426. }
  20427. }
  20428. level() {
  20429. if (this.parent === null) {
  20430. return 0;
  20431. } else {
  20432. return this.parent.level() + 1;
  20433. }
  20434. }
  20435. hasChild(annotation) {
  20436. return this.children.includes(annotation);
  20437. }
  20438. remove(annotation) {
  20439. if (this.hasChild(annotation)) {
  20440. annotation.removeAllChildren();
  20441. annotation.dispose();
  20442. this.children = this.children.filter(e => e !== annotation);
  20443. annotation.parent = null;
  20444. }
  20445. }
  20446. removeAllChildren() {
  20447. this.children.forEach(child => {
  20448. if (child.children.length > 0) {
  20449. child.removeAllChildren();
  20450. }
  20451. this.remove(child);
  20452. });
  20453. }
  20454. updateBounds() {
  20455. var box = new Box3();
  20456. if (this.position) {
  20457. box.expandByPoint(this.position);
  20458. }
  20459. for (var child of this.children) {
  20460. child.updateBounds();
  20461. box.union(child.boundingBox);
  20462. }
  20463. this.boundingBox.copy(box);
  20464. }
  20465. traverse(handler) {
  20466. var expand = handler(this);
  20467. if (expand === undefined || expand === true) {
  20468. for (var child of this.children) {
  20469. child.traverse(handler);
  20470. }
  20471. }
  20472. }
  20473. traverseDescendants(handler) {
  20474. for (var child of this.children) {
  20475. child.traverse(handler);
  20476. }
  20477. }
  20478. flatten() {
  20479. var annotations = [];
  20480. this.traverse(annotation => {
  20481. annotations.push(annotation);
  20482. });
  20483. return annotations;
  20484. }
  20485. descendants() {
  20486. var annotations = [];
  20487. this.traverse(annotation => {
  20488. if (annotation !== this) {
  20489. annotations.push(annotation);
  20490. }
  20491. });
  20492. return annotations;
  20493. }
  20494. setHighlighted(highlighted) {
  20495. if (highlighted) {
  20496. this.domElement.css('opacity', '0.8');
  20497. this.elTitlebar.css('box-shadow', '0 0 5px #fff');
  20498. this.domElement.css('z-index', '1000');
  20499. if (this._description) {
  20500. this.descriptionVisible = true;
  20501. this.elDescription.fadeIn(200);
  20502. this.elDescription.css('position', 'relative');
  20503. }
  20504. } else {
  20505. this.domElement.css('opacity', '0.5');
  20506. this.elTitlebar.css('box-shadow', '');
  20507. this.domElement.css('z-index', '100');
  20508. this.descriptionVisible = false;
  20509. this.elDescription.css('display', 'none');
  20510. }
  20511. this.isHighlighted = highlighted;
  20512. }
  20513. hasView() {
  20514. var hasPosTargetView = this.cameraTarget.x != null;
  20515. hasPosTargetView = hasPosTargetView && this.cameraPosition.x != null;
  20516. var hasRadiusView = this.radius !== undefined;
  20517. var hasView = hasPosTargetView || hasRadiusView;
  20518. return hasView;
  20519. }
  20520. moveHere(camera) {
  20521. if (!this.hasView()) {
  20522. return;
  20523. }
  20524. var view = this.scene.view;
  20525. var animationDuration = 500;
  20526. var easing = TWEEN.Easing.Quartic.Out;
  20527. var endTarget;
  20528. if (this.cameraTarget) {
  20529. endTarget = this.cameraTarget;
  20530. } else if (this.position) {
  20531. endTarget = this.position;
  20532. } else {
  20533. endTarget = this.boundingBox.getCenter(new Vector3());
  20534. }
  20535. if (this.cameraPosition) {
  20536. var endPosition = this.cameraPosition;
  20537. Utils.moveTo(this.scene, endPosition, endTarget);
  20538. } else if (this.radius) {
  20539. var direction = view.direction;
  20540. var _endPosition = endTarget.clone().add(direction.multiplyScalar(-this.radius));
  20541. var startRadius = view.radius;
  20542. var endRadius = this.radius;
  20543. {
  20544. // animate camera position
  20545. var tween = new TWEEN.Tween(view.position).to(_endPosition, animationDuration);
  20546. tween.easing(easing);
  20547. tween.start();
  20548. }
  20549. {
  20550. // animate radius
  20551. var t = {
  20552. x: 0
  20553. };
  20554. var _tween = new TWEEN.Tween(t).to({
  20555. x: 1
  20556. }, animationDuration).onUpdate(function () {
  20557. view.radius = this.x * endRadius + (1 - this.x) * startRadius;
  20558. });
  20559. _tween.easing(easing);
  20560. _tween.start();
  20561. }
  20562. }
  20563. }
  20564. dispose() {
  20565. if (this.domElement.parentElement) {
  20566. this.domElement.parentElement.removeChild(this.domElement);
  20567. }
  20568. }
  20569. toString() {
  20570. return 'Annotation: ' + this._title;
  20571. }
  20572. }
  20573. ;
  20574. class Scene$1 extends EventDispatcher$1 {
  20575. //base
  20576. constructor() {
  20577. super();
  20578. this.annotations = new Annotation();
  20579. this.scene = new Scene();
  20580. this.sceneBG = new Scene();
  20581. this.scenePointCloud = new Scene();
  20582. this.cameraP = new PerspectiveCamera(this.fov, 1, 0.1, 1000 * 1000);
  20583. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, 0.1, 1000 * 1000);
  20584. this.cameraVR = new PerspectiveCamera();
  20585. this.cameraBG = new Camera();
  20586. this.cameraScreenSpace = new OrthographicCamera(-1, 1, 1, -1, 0.1, 10);
  20587. this.cameraMode = CameraMode.PERSPECTIVE;
  20588. this.overrideCamera = null;
  20589. this.pointclouds = [];
  20590. this.measurements = [];
  20591. this.profiles = [];
  20592. this.volumes = [];
  20593. this.polygonClipVolumes = [];
  20594. this.cameraAnimations = [];
  20595. this.orientedImages = [];
  20596. this.images360 = [];
  20597. this.geopackages = [];
  20598. this.fpControls = null;
  20599. this.orbitControls = null;
  20600. this.earthControls = null;
  20601. this.geoControls = null;
  20602. this.deviceControls = null;
  20603. this.inputHandler = null;
  20604. this.view = new ExtendView();
  20605. this.directionalLight = null;
  20606. this.initialize();
  20607. }
  20608. estimateHeightAt(position) {
  20609. var height = null;
  20610. var fromSpacing = Infinity;
  20611. for (var pointcloud of this.pointclouds) {
  20612. if (pointcloud.root.geometryNode === undefined) {
  20613. continue;
  20614. }
  20615. var pHeight = null;
  20616. var pFromSpacing = Infinity;
  20617. var lpos = position.clone().sub(pointcloud.position);
  20618. lpos.z = 0;
  20619. var ray = new Ray(lpos, new Vector3(0, 0, 1));
  20620. var stack = [pointcloud.root];
  20621. while (stack.length > 0) {
  20622. var node = stack.pop();
  20623. var box = node.getBoundingBox();
  20624. var inside = ray.intersectBox(box);
  20625. if (!inside) {
  20626. continue;
  20627. }
  20628. var h = node.geometryNode.mean.z + pointcloud.position.z + node.geometryNode.boundingBox.min.z;
  20629. if (node.geometryNode.spacing <= pFromSpacing) {
  20630. pHeight = h;
  20631. pFromSpacing = node.geometryNode.spacing;
  20632. }
  20633. for (var index of Object.keys(node.children)) {
  20634. var child = node.children[index];
  20635. if (child.geometryNode) {
  20636. stack.push(node.children[index]);
  20637. }
  20638. }
  20639. }
  20640. if (height === null || pFromSpacing < fromSpacing) {
  20641. height = pHeight;
  20642. fromSpacing = pFromSpacing;
  20643. }
  20644. }
  20645. return height;
  20646. }
  20647. getBoundingBox() {
  20648. var pointclouds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.pointclouds;
  20649. var box = new Box3();
  20650. this.scenePointCloud.updateMatrixWorld(true);
  20651. this.referenceFrame.updateMatrixWorld(true);
  20652. for (var pointcloud of pointclouds) {
  20653. pointcloud.updateMatrixWorld(true);
  20654. var pointcloudBox = pointcloud.pcoGeometry.tightBoundingBox ? pointcloud.pcoGeometry.tightBoundingBox : pointcloud.boundingBox;
  20655. var boxWorld = Utils.computeTransformedBoundingBox(pointcloudBox, pointcloud.matrixWorld);
  20656. box.union(boxWorld);
  20657. }
  20658. return box;
  20659. }
  20660. addPointCloud(pointcloud) {
  20661. this.pointclouds.push(pointcloud);
  20662. this.scenePointCloud.add(pointcloud);
  20663. this.dispatchEvent({
  20664. type: 'pointcloud_added',
  20665. pointcloud: pointcloud
  20666. });
  20667. }
  20668. addVolume(volume) {
  20669. this.volumes.push(volume);
  20670. this.dispatchEvent({
  20671. 'type': 'volume_added',
  20672. 'scene': this,
  20673. 'volume': volume
  20674. });
  20675. viewer.dispatchEvent('content_changed');
  20676. }
  20677. addOrientedImages(images) {
  20678. this.orientedImages.push(images);
  20679. this.scene.add(images.node);
  20680. this.dispatchEvent({
  20681. 'type': 'oriented_images_added',
  20682. 'scene': this,
  20683. 'images': images
  20684. });
  20685. }
  20686. removeOrientedImages(images) {
  20687. var index = this.orientedImages.indexOf(images);
  20688. if (index > -1) {
  20689. this.orientedImages.splice(index, 1);
  20690. this.dispatchEvent({
  20691. 'type': 'oriented_images_removed',
  20692. 'scene': this,
  20693. 'images': images
  20694. });
  20695. }
  20696. }
  20697. add360Images(images) {
  20698. this.images360.push(images);
  20699. this.scene.add(images.node);
  20700. this.dispatchEvent({
  20701. 'type': '360_images_added',
  20702. 'scene': this,
  20703. 'images': images
  20704. });
  20705. }
  20706. remove360Images(images) {
  20707. var index = this.images360.indexOf(images);
  20708. if (index > -1) {
  20709. this.images360.splice(index, 1);
  20710. this.dispatchEvent({
  20711. 'type': '360_images_removed',
  20712. 'scene': this,
  20713. 'images': images
  20714. });
  20715. }
  20716. }
  20717. addGeopackage(geopackage) {
  20718. this.geopackages.push(geopackage);
  20719. this.scene.add(geopackage.node);
  20720. this.dispatchEvent({
  20721. 'type': 'geopackage_added',
  20722. 'scene': this,
  20723. 'geopackage': geopackage
  20724. });
  20725. }
  20726. removeGeopackage(geopackage) {
  20727. var index = this.geopackages.indexOf(geopackage);
  20728. if (index > -1) {
  20729. this.geopackages.splice(index, 1);
  20730. this.dispatchEvent({
  20731. 'type': 'geopackage_removed',
  20732. 'scene': this,
  20733. 'geopackage': geopackage
  20734. });
  20735. }
  20736. }
  20737. removeVolume(volume) {
  20738. var index = this.volumes.indexOf(volume);
  20739. if (index > -1) {
  20740. this.volumes.splice(index, 1);
  20741. this.dispatchEvent({
  20742. 'type': 'volume_removed',
  20743. 'scene': this,
  20744. 'volume': volume
  20745. });
  20746. }
  20747. viewer.dispatchEvent('content_changed');
  20748. }
  20749. addCameraAnimation(animation) {
  20750. this.cameraAnimations.push(animation);
  20751. this.dispatchEvent({
  20752. 'type': 'camera_animation_added',
  20753. 'scene': this,
  20754. 'animation': animation
  20755. });
  20756. }
  20757. removeCameraAnimation(animation) {
  20758. var index = this.cameraAnimations.indexOf(volume);
  20759. if (index > -1) {
  20760. this.cameraAnimations.splice(index, 1);
  20761. this.dispatchEvent({
  20762. 'type': 'camera_animation_removed',
  20763. 'scene': this,
  20764. 'animation': animation
  20765. });
  20766. }
  20767. }
  20768. addPolygonClipVolume(volume) {
  20769. this.polygonClipVolumes.push(volume);
  20770. this.dispatchEvent({
  20771. "type": "polygon_clip_volume_added",
  20772. "scene": this,
  20773. "volume": volume
  20774. });
  20775. }
  20776. removePolygonClipVolume(volume) {
  20777. var index = this.polygonClipVolumes.indexOf(volume);
  20778. if (index > -1) {
  20779. this.polygonClipVolumes.splice(index, 1);
  20780. this.dispatchEvent({
  20781. "type": "polygon_clip_volume_removed",
  20782. "scene": this,
  20783. "volume": volume
  20784. });
  20785. }
  20786. }
  20787. addMeasurement(measurement) {
  20788. measurement.lengthUnit = this.lengthUnit;
  20789. measurement.lengthUnitDisplay = this.lengthUnitDisplay;
  20790. this.measurements.push(measurement);
  20791. this.dispatchEvent({
  20792. 'type': 'measurement_added',
  20793. 'scene': this,
  20794. 'measurement': measurement
  20795. });
  20796. viewer.dispatchEvent('content_changed');
  20797. }
  20798. removeMeasurement(measurement) {
  20799. var index = this.measurements.indexOf(measurement);
  20800. if (index > -1) {
  20801. this.measurements.splice(index, 1);
  20802. this.dispatchEvent({
  20803. 'type': 'measurement_removed',
  20804. 'scene': this,
  20805. 'measurement': measurement
  20806. });
  20807. viewer.dispatchEvent('content_changed');
  20808. }
  20809. }
  20810. addProfile(profile) {
  20811. this.profiles.push(profile);
  20812. this.dispatchEvent({
  20813. 'type': 'profile_added',
  20814. 'scene': this,
  20815. 'profile': profile
  20816. });
  20817. }
  20818. removeProfile(profile) {
  20819. var index = this.profiles.indexOf(profile);
  20820. if (index > -1) {
  20821. this.profiles.splice(index, 1);
  20822. this.dispatchEvent({
  20823. 'type': 'profile_removed',
  20824. 'scene': this,
  20825. 'profile': profile
  20826. });
  20827. }
  20828. }
  20829. removeAllMeasurements() {
  20830. while (this.measurements.length > 0) {
  20831. this.removeMeasurement(this.measurements[0]);
  20832. }
  20833. while (this.profiles.length > 0) {
  20834. this.removeProfile(this.profiles[0]);
  20835. }
  20836. while (this.volumes.length > 0) {
  20837. this.removeVolume(this.volumes[0]);
  20838. }
  20839. }
  20840. removeAllClipVolumes() {
  20841. var clipVolumes = this.volumes.filter(volume => volume.clip === true);
  20842. for (var clipVolume of clipVolumes) {
  20843. this.removeVolume(clipVolume);
  20844. }
  20845. while (this.polygonClipVolumes.length > 0) {
  20846. this.removePolygonClipVolume(this.polygonClipVolumes[0]);
  20847. }
  20848. }
  20849. getActiveCamera() {
  20850. if (this.overrideCamera) {
  20851. return this.overrideCamera;
  20852. }
  20853. if (this.cameraMode === CameraMode.PERSPECTIVE) {
  20854. return this.cameraP;
  20855. } else if (this.cameraMode === CameraMode.ORTHOGRAPHIC) {
  20856. return this.cameraO;
  20857. } else if (this.cameraMode === CameraMode.VR) {
  20858. return this.cameraVR;
  20859. }
  20860. return null;
  20861. }
  20862. initialize() {
  20863. this.referenceFrame = new Object3D();
  20864. this.referenceFrame.matrixAutoUpdate = false;
  20865. this.scenePointCloud.add(this.referenceFrame);
  20866. this.cameraP.up.set(0, 0, 1);
  20867. this.cameraP.position.set(1000, 1000, 1000);
  20868. this.cameraO.up.set(0, 0, 1);
  20869. this.cameraO.position.set(1000, 1000, 1000);
  20870. //this.camera.rotation.y = -Math.PI / 4;
  20871. //this.camera.rotation.x = -Math.PI / 6;
  20872. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  20873. this.directionalLight = new DirectionalLight(0xffffff, 0.5);
  20874. this.directionalLight.position.set(10, 10, 10);
  20875. this.directionalLight.lookAt(new Vector3(0, 0, 0));
  20876. this.scenePointCloud.add(this.directionalLight);
  20877. var light = new AmbientLight(0x555555); // soft white light
  20878. this.scenePointCloud.add(light);
  20879. {
  20880. // background
  20881. var texture = Utils.createBackgroundTexture(512, 512);
  20882. texture.minFilter = texture.magFilter = NearestFilter;
  20883. texture.minFilter = texture.magFilter = LinearFilter;
  20884. var bg = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({
  20885. map: texture
  20886. }));
  20887. bg.material.depthTest = false;
  20888. bg.material.depthWrite = false;
  20889. this.sceneBG.add(bg);
  20890. }
  20891. // { // lights
  20892. // {
  20893. // let light = new THREE.DirectionalLight(0xffffff);
  20894. // light.position.set(10, 10, 1);
  20895. // light.target.position.set(0, 0, 0);
  20896. // this.scene.add(light);
  20897. // }
  20898. // {
  20899. // let light = new THREE.DirectionalLight(0xffffff);
  20900. // light.position.set(-10, 10, 1);
  20901. // light.target.position.set(0, 0, 0);
  20902. // this.scene.add(light);
  20903. // }
  20904. // {
  20905. // let light = new THREE.DirectionalLight(0xffffff);
  20906. // light.position.set(0, -10, 20);
  20907. // light.target.position.set(0, 0, 0);
  20908. // this.scene.add(light);
  20909. // }
  20910. // }
  20911. }
  20912. addAnnotation(position) {
  20913. var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  20914. if (position instanceof Array) {
  20915. args.position = new Vector3().fromArray(position);
  20916. } else if (position.x != null) {
  20917. args.position = position;
  20918. }
  20919. var annotation = new Annotation(args);
  20920. this.annotations.add(annotation);
  20921. return annotation;
  20922. }
  20923. getAnnotations() {
  20924. return this.annotations;
  20925. }
  20926. removeAnnotation(annotationToRemove) {
  20927. this.annotations.remove(annotationToRemove);
  20928. }
  20929. }
  20930. ;
  20931. class ExtendScene extends Scene$1 {
  20932. constructor() {
  20933. super();
  20934. delete this.sceneBG;
  20935. this.cameraP = new PerspectiveCamera(this.fov, 1, Potree.config.view.near, Potree.config.view.near);
  20936. this.cameraO = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  20937. this.cameraP.limitFar = true; //add
  20938. this.initializeExtend();
  20939. //-------------
  20940. this.axisArrow = new Axis();
  20941. this.scene.add(this.axisArrow);
  20942. if (!Potree.settings.isDebug && !Potree.settings.showAxis) this.axisArrow.visible = false;
  20943. Potree.Utils.setObjectLayers(this.axisArrow, 'bothMapAndScene');
  20944. this.tags = new Object3D();
  20945. this.scene.add(this.tags);
  20946. }
  20947. estimateHeightAt(position) {
  20948. var height = null;
  20949. var fromSpacing = Infinity;
  20950. for (var pointcloud of this.pointclouds) {
  20951. if (pointcloud.root.geometryNode === undefined) {
  20952. continue;
  20953. }
  20954. var pHeight = null;
  20955. var pFromSpacing = Infinity;
  20956. var lpos = position.clone().sub(pointcloud.position);
  20957. lpos.z = 0;
  20958. var ray = new Ray(lpos, new Vector3(0, 0, 1));
  20959. var stack = [pointcloud.root];
  20960. while (stack.length > 0) {
  20961. var node = stack.pop();
  20962. var box = node.getBoundingBox();
  20963. var inside = ray.intersectBox(box);
  20964. if (!inside) {
  20965. continue;
  20966. }
  20967. var h = node.geometryNode.mean.z + pointcloud.position.z + node.geometryNode.boundingBox.min.z;
  20968. if (node.geometryNode.spacing <= pFromSpacing) {
  20969. pHeight = h;
  20970. pFromSpacing = node.geometryNode.spacing;
  20971. }
  20972. for (var index of Object.keys(node.children)) {
  20973. var child = node.children[index];
  20974. if (child.geometryNode) {
  20975. stack.push(node.children[index]);
  20976. }
  20977. }
  20978. }
  20979. if (height === null || pFromSpacing < fromSpacing) {
  20980. height = pHeight;
  20981. fromSpacing = pFromSpacing;
  20982. }
  20983. }
  20984. return height;
  20985. }
  20986. //add:
  20987. removePointCloud(pointcloud) {
  20988. var index = this.pointclouds.indexOf(pointcloud);
  20989. if (index == -1) return;
  20990. this.pointclouds.splice(index, 1);
  20991. this.scenePointCloud.remove(pointcloud);
  20992. pointcloud.panos.forEach(pano => {
  20993. pano.dispose();
  20994. });
  20995. }
  20996. removeCameraAnimation(animation) {
  20997. var index = this.cameraAnimations.indexOf(animation);
  20998. if (index > -1) {
  20999. this.cameraAnimations.splice(index, 1);
  21000. this.dispatchEvent({
  21001. 'type': 'camera_animation_removed',
  21002. 'scene': this,
  21003. 'animation': animation
  21004. });
  21005. }
  21006. }
  21007. getActiveCamera() {
  21008. return viewer.mainViewport.camera;
  21009. }
  21010. initialize() {//不用旧的 因为还没创建完变量
  21011. }
  21012. initializeExtend() {
  21013. //add 新的initialize
  21014. this.referenceFrame = new Object3D();
  21015. this.referenceFrame.matrixAutoUpdate = false;
  21016. this.scenePointCloud.add(this.referenceFrame);
  21017. if (window.axisYup) {} else {
  21018. this.cameraP.up.set(0, 0, 1);
  21019. this.cameraO.up.set(0, 0, 1);
  21020. }
  21021. this.cameraP.position.set(1000, 1000, 1000);
  21022. this.cameraO.position.set(1000, 1000, 1000);
  21023. //this.camera.rotation.y = -Math.PI / 4;
  21024. //this.camera.rotation.x = -Math.PI / 6;
  21025. this.cameraScreenSpace.lookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 1, 0));
  21026. this.directionalLight = new DirectionalLight(0xffffff, 0.5);
  21027. this.directionalLight.position.set(10, 10, 10);
  21028. this.directionalLight.lookAt(new Vector3(0, 0, 0));
  21029. this.scenePointCloud.add(this.directionalLight);
  21030. var light = new AmbientLight(0x555555); // soft white light
  21031. this.scenePointCloud.add(light);
  21032. //add:------给空间模型的box 或其他obj------
  21033. var light2 = new AmbientLight(16777215, 0.5);
  21034. Potree.Utils.setObjectLayers(light2, 'light' /* 'bothMapAndScene' */);
  21035. this.scene.add(light2);
  21036. var light3 = new DirectionalLight(16777215, 0.7);
  21037. light3.position.set(10, 10, 10);
  21038. light3.lookAt(new Vector3(0, 0, 0));
  21039. Potree.Utils.setObjectLayers(light3, 'light');
  21040. this.scene.add(light3);
  21041. var light4 = new DirectionalLight(16777215, 0.3); //补光
  21042. light4.position.set(-10, -5, -7);
  21043. light4.lookAt(new Vector3(0, 0, 0));
  21044. Potree.Utils.setObjectLayers(light4, 'light');
  21045. this.scene.add(light4);
  21046. //--------------------------------------------
  21047. {
  21048. // background
  21049. var texture = Utils.createBackgroundTexture(512, 512);
  21050. texture.minFilter = texture.magFilter = NearestFilter;
  21051. texture.minFilter = texture.magFilter = LinearFilter;
  21052. var bg = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({
  21053. map: texture
  21054. }));
  21055. bg.material.depthTest = false;
  21056. bg.material.depthWrite = false;
  21057. bg.name = 'bg';
  21058. //this.sceneBG.add(bg);
  21059. this.scene.add(bg);
  21060. bg.layers.set(Potree.config.renderLayers.bg);
  21061. }
  21062. {
  21063. // background color
  21064. var bg2 = new Mesh(new PlaneBufferGeometry(2, 2, 1), new MeshBasicMaterial({
  21065. transparent: true
  21066. }));
  21067. bg2.material.depthTest = false;
  21068. bg2.material.depthWrite = false;
  21069. bg2.name = 'bg2';
  21070. this.scene.add(bg2);
  21071. bg2.layers.set(Potree.config.renderLayers.bg2);
  21072. this.bg2 = bg2;
  21073. }
  21074. // { // lights
  21075. // {
  21076. // let light = new THREE.DirectionalLight(0xffffff);
  21077. // light.position.set(10, 10, 1);
  21078. // light.target.position.set(0, 0, 0);
  21079. // this.scene.add(light);
  21080. // }
  21081. // {
  21082. // let light = new THREE.DirectionalLight(0xffffff);
  21083. // light.position.set(-10, 10, 1);
  21084. // light.target.position.set(0, 0, 0);
  21085. // this.scene.add(light);
  21086. // }
  21087. // {
  21088. // let light = new THREE.DirectionalLight(0xffffff);
  21089. // light.position.set(0, -10, 20);
  21090. // light.target.position.set(0, 0, 0);
  21091. // this.scene.add(light);
  21092. // }
  21093. // }
  21094. }
  21095. }
  21096. ;
  21097. KeyCodes.BACKSPACE = 8;
  21098. //注意,这时候Potree.js中export的内容还不在Potree变量中
  21099. var texLoader$1 = new TextureLoader();
  21100. texLoader$1.crossOrigin = "anonymous";
  21101. {
  21102. //defines:
  21103. Potree.defines = {};
  21104. Potree.defines.Buttons = {
  21105. // MouseEvent.buttons
  21106. //buttons,设置按下了鼠标哪些键,是一个3个比特位的二进制值,默认为0。1表示按下主键(通常是左键),2表示按下次要键(通常是右键),4表示按下辅助键(通常是中间的键)。
  21107. NONE: 0,
  21108. //add
  21109. LEFT: 0b0001,
  21110. RIGHT: 0b0010,
  21111. MIDDLE: 0b0100
  21112. };
  21113. /* 如果访问的是button, 用THREE.MOUSE来判断:
  21114. button,设置按下了哪一个鼠标按键,默认为0。-1表示没有按键,0表示按下主键(通常是左键),1表示按下辅助键(通常是中间的键),2表示按下次要键(通常是右键)
  21115. */
  21116. Potree.browser = browser;
  21117. /////////// add //////////////////////////////////
  21118. Potree.defines.GLCubeFaces = {
  21119. GL_TEXTURE_CUBE_MAP_POSITIVE_X: 0,
  21120. GL_TEXTURE_CUBE_MAP_NEGATIVE_X: 1,
  21121. GL_TEXTURE_CUBE_MAP_POSITIVE_Y: 2,
  21122. GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: 3,
  21123. GL_TEXTURE_CUBE_MAP_POSITIVE_Z: 4,
  21124. GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: 5
  21125. };
  21126. Potree.defines.PanoSizeClass = {
  21127. BASE: 1,
  21128. STANDARD: 2,
  21129. HIGH: 3,
  21130. ULTRAHIGH: 4
  21131. };
  21132. Potree.defines.PanoRendererEvents = {
  21133. PanoRenderComplete: "panorama.render.complete",
  21134. TileRenderFailure: "panorama.tile.render.failed",
  21135. TileRenderSuccess: "panorama.tile.render.success",
  21136. TileUploadAttempted: "panorama.tile.upload.attempted",
  21137. UploadAttemptedForAllTiles: "panorama.upload.attempted.all.tiles",
  21138. ZoomLevelRenderStarted: "panorama.zoom.render.started"
  21139. };
  21140. Potree.defines.SceneRendererEvents = {
  21141. ContextCreated: "scene-renderer-context-created",
  21142. AfterRender: "after-render",
  21143. MemoryUsageUpdated: "scene-renderer-memory-usage-updated"
  21144. };
  21145. Potree.defines.TileDownloaderEvents = {
  21146. TileDownloadSuccess: "tiledownloader.download.success",
  21147. TileDownloadFailure: "tiledownloader.download.failure",
  21148. PanoDownloadComplete: "tiledownloader.pano.download.complete"
  21149. };
  21150. Potree.defines.Vectors = {
  21151. UP: new Vector3(0, 1, 0),
  21152. DOWN: new Vector3(0, -1, 0),
  21153. LEFT: new Vector3(-1, 0, 0),
  21154. RIGHT: new Vector3(1, 0, 0),
  21155. FORWARD: new Vector3(0, 0, -1),
  21156. BACK: new Vector3(0, 0, 1)
  21157. };
  21158. /* var Vectors2 = {}
  21159. for(var i in Vectors){
  21160. Vectors2[i] = math.convertVector.YupToZup(Vectors[i])
  21161. }
  21162. */
  21163. Potree.defines.DownloadStatus = Object.freeze({
  21164. None: 0,
  21165. Queued: 1,
  21166. ForceQueued: 2,
  21167. Downloading: 3,
  21168. Downloaded: 4,
  21169. DownloadFailed: 5
  21170. });
  21171. Potree.defines.ModelManagerEvents = {
  21172. ModelAdded: "model-added",
  21173. ActiveModelChanged: "active-model-changed"
  21174. };
  21175. Potree.defines.PanoramaEvents = {
  21176. Enter: 'panorama.enter',
  21177. Exit: 'panorama.exit',
  21178. LoadComplete: "panorama.load.complete",
  21179. LoadFailed: "panorama.load.failed",
  21180. TileLoaded: "panorama.tile.loaded",
  21181. VideoRendered: "panorama.video.rendered"
  21182. };
  21183. ClipTask.SHOW_INSIDE_Big = 4;
  21184. }
  21185. {
  21186. //Features
  21187. var gl_;
  21188. Features.EXT_DEPTH = {
  21189. isSupported: function isSupported(gl) {
  21190. gl = gl || gl_;
  21191. gl_ = gl;
  21192. if (browser.detectIOS()) {
  21193. var {
  21194. major,
  21195. minor,
  21196. patch
  21197. } = browser.iosVersion();
  21198. //console.warn('iosVersion',major,minor,patch)
  21199. if (major == 15 && minor == 4 && patch == 1) {
  21200. console.warn('检测到是ios15.4.1, 关闭EXT_frag_depth'); //该版本ext_depth有问题,导致clear错乱。没有解决办法先关闭。
  21201. return false;
  21202. }
  21203. }
  21204. return typeof WebGL2RenderingContext != 'undefined' && gl instanceof WebGL2RenderingContext || gl.getExtension('EXT_frag_depth'); //shader中的GL_EXT_frag_depth需要判断一下detectIOS吗。。
  21205. }
  21206. };
  21207. }
  21208. Utils.loadSkybox = function (path, oldSky, callback) {
  21209. var camera, scene, parent, cameraOrtho;
  21210. if (!oldSky) {
  21211. parent = new Object3D("skybox_root");
  21212. camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 100000);
  21213. cameraOrtho = new OrthographicCamera(-1, 1, 1, -1, Potree.config.view.near, Potree.settings.cameraFar);
  21214. if (!window.axisYup) camera.up.set(0, 0, 1); //add
  21215. scene = new Scene();
  21216. var skyboxBgWidth = Potree.config.skyboxBgWidth;
  21217. var skyGeometry = new BoxBufferGeometry(skyboxBgWidth, skyboxBgWidth, skyboxBgWidth);
  21218. var skybox = new Mesh(skyGeometry, new ShaderMaterial({
  21219. vertexShader: Shaders['skybox.vs'],
  21220. fragmentShader: Shaders['skybox.fs'],
  21221. side: BackSide,
  21222. uniforms: {
  21223. tDiffuse: {
  21224. type: "t",
  21225. value: null
  21226. },
  21227. matrix: {
  21228. type: "m4",
  21229. value: new Matrix4()
  21230. }
  21231. },
  21232. depthTest: false,
  21233. depthWrite: false
  21234. }));
  21235. scene.add(skybox);
  21236. scene.traverse(n => n.frustumCulled = false);
  21237. // z up
  21238. //scene.rotation.x = Math.PI / 2;
  21239. parent.children.push(camera);
  21240. camera.parent = parent;
  21241. } else {
  21242. camera = oldSky.camera, scene = oldSky.scene;
  21243. parent = oldSky.parent;
  21244. cameraOrtho = oldSky.cameraOrtho;
  21245. }
  21246. var texture = texLoader$1.load(path, () => {
  21247. console.log('loadSkybox成功', path);
  21248. texture.wrapS = RepeatWrapping;
  21249. texture.flipY = false;
  21250. texture.magFilter = LinearFilter;
  21251. texture.minFilter = LinearFilter;
  21252. scene.children[0].material.uniforms.tDiffuse.value = texture;
  21253. callback && callback();
  21254. viewer.dispatchEvent('content_changed');
  21255. }, null, e => {
  21256. //error
  21257. console.error('loadSkybox失败', path);
  21258. });
  21259. return {
  21260. camera,
  21261. scene,
  21262. parent,
  21263. cameraOrtho
  21264. };
  21265. };
  21266. Utils.getMousePointCloudIntersection = function (viewport, mouse, pointer, camera, viewer, pointclouds) {
  21267. var pickParams = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {};
  21268. //getIntersectByDepthTex
  21269. /* let result = viewer.edlRenderer.depthTexSampler.sample(viewport, mouse)//add
  21270. if(result != 'unsupport')return result
  21271. */
  21272. if (!pointclouds || pointclouds.length == 0) return;
  21273. //console.log('getMousePointCloudIntersection')
  21274. var renderer = viewer.renderer;
  21275. if (viewport) {
  21276. //转换到类似整个画面时
  21277. /*let mouseInViewport = Utils.convertNDCToScreenPosition(pointer, null, viewport.resolution.x, viewport.resolution.y)
  21278. pickParams.x = mouseInViewport.x //mouse.x / viewport.width;
  21279. pickParams.y = mouseInViewport.y //renderer.domElement.clientHeight - mouse.y / viewport.height; */
  21280. pickParams.x = mouse.x;
  21281. pickParams.y = viewport.resolution.y - mouse.y;
  21282. } else {
  21283. pickParams.x = mouse.x;
  21284. pickParams.y = renderer.domElement.clientHeight - mouse.y;
  21285. }
  21286. //console.log('getMousePointCloudIntersection')
  21287. /* if(!raycaster){
  21288. raycaster = new THREE.Raycaster();
  21289. raycaster.setFromCamera(pointer, camera);
  21290. } */
  21291. var raycaster = new Raycaster();
  21292. raycaster.setFromCamera(pointer, camera);
  21293. var ray = raycaster.ray;
  21294. var selectedPointcloud = null;
  21295. var closestDistance = Infinity;
  21296. var closestIntersection = null;
  21297. var closestPoint = null;
  21298. //-----------add--------------------
  21299. var old_clipBoxes_in = new Map();
  21300. var old_clipBoxes_out = new Map();
  21301. var old_bigClipInBox = new Map();
  21302. var old_highlightBoxes = new Map();
  21303. var old_visibleNodes = new Map();
  21304. //bigClipInBox 最好也写下
  21305. var density;
  21306. var sizeType;
  21307. var size = new Map();
  21308. var visiMap = new Map();
  21309. var needsUpdate = false;
  21310. if (pickParams.measuring || Potree.settings.displayMode == 'showPanos') {
  21311. //测量或无深度图时的全景模式提高精准度. (全景模式有深度图时不会执行到这)
  21312. density = Potree.settings.pointDensity;
  21313. Potree.settings.pointDensity = 'magnifier'; //加载最高level
  21314. pointclouds.forEach(e => {
  21315. //因为全景模式的pointSizeType是fixed所以要还原下
  21316. visiMap.set(e, e.visible);
  21317. e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示
  21318. if (!e.visible) return;
  21319. size.set(e, e.temp.pointSize);
  21320. sizeType = e.material.pointSizeType;
  21321. e.material.pointSizeType = Potree.config.material.pointSizeType;
  21322. //e.changePointSize(Potree.config.material.realPointSize*2, true)//更改点云大小到能铺满为止,否则容易识别不到
  21323. });
  21324. needsUpdate = true;
  21325. } else {
  21326. if (viewer.viewports.filter(e => !e.noPointcloud && e.active).length > 1 || pickParams.cameraChanged) {
  21327. //在pick时相机和渲染时不一样的话
  21328. viewport.beforeRender && viewport.beforeRender();
  21329. needsUpdate = true; //不updatePointClouds的话hover久了会不准 因node是错的
  21330. //但依旧需要camera真的移动到那个位置才能加载出点云
  21331. }
  21332. }
  21333. if (!pickParams.pickClipped) {
  21334. // 无视clipBoxes
  21335. for (var pointcloud of pointclouds) {
  21336. old_clipBoxes_in.set(pointcloud, pointcloud.clipBoxes_in);
  21337. old_clipBoxes_out.set(pointcloud, pointcloud.clipBoxes_out);
  21338. old_bigClipInBox.set(pointcloud, pointcloud.bigClipInBox);
  21339. old_highlightBoxes.set(pointcloud, pointcloud.highlightBoxes);
  21340. pointcloud.material.setClipBoxes(null, [], [], []);
  21341. }
  21342. needsUpdate = true;
  21343. }
  21344. if (needsUpdate) {
  21345. for (var _pointcloud of pointclouds) {
  21346. old_visibleNodes.set(_pointcloud, _pointcloud.visibleNodes);
  21347. }
  21348. if (window.notViewOffset) {
  21349. Potree.updatePointClouds(pointclouds, camera, viewport.resolution);
  21350. } else {
  21351. //尽量减少点云加载的范围,集中在pick的空间(这部分以外还是会加载一些散点的)
  21352. var viewWidth = 80; //viewer.magnifier ? viewer.magnifier.viewport.resolution.x : 200
  21353. var camera_ = camera.clone();
  21354. camera_.setViewOffset(viewport.resolution.x, viewport.resolution.y, pickParams.x - viewWidth / 2, viewport.resolution.y - pickParams.y - viewWidth / 2, viewWidth, viewWidth); //注意offsetY是从上到下,和一般的不同
  21355. Potree.updatePointClouds(pointclouds, camera_, viewport.resolution);
  21356. }
  21357. }
  21358. //------------------------------------------------
  21359. var allPointclouds = [];
  21360. for (var _pointcloud2 of pointclouds) {
  21361. var point = _pointcloud2.pick(viewer, viewport, camera, ray, pickParams);
  21362. if (!point) {
  21363. continue;
  21364. }
  21365. allPointclouds.push(_pointcloud2);
  21366. var distance = camera.position.distanceTo(point.position);
  21367. if (distance < closestDistance) {
  21368. closestDistance = distance;
  21369. selectedPointcloud = _pointcloud2;
  21370. closestIntersection = point.position;
  21371. closestPoint = point;
  21372. }
  21373. }
  21374. //恢复
  21375. if (pickParams.measuring || Potree.settings.displayMode == 'showPanos') {
  21376. Potree.settings.pointDensity = density;
  21377. pointclouds.forEach(e => {
  21378. if (e.visible) {
  21379. e.material.pointSizeType = sizeType;
  21380. //e.changePointSize(size.get(e))
  21381. }
  21382. e.visible = visiMap.get(e);
  21383. });
  21384. } else {
  21385. /* if(viewer.viewports.filter(e=>!e.noPointcloud).length>1){
  21386. viewport.afterRender && viewport.afterRender()
  21387. } */
  21388. }
  21389. if (!pickParams.pickClipped) {
  21390. //add
  21391. for (var _pointcloud3 of pointclouds) {
  21392. _pointcloud3.material.setClipBoxes(old_bigClipInBox.get(_pointcloud3), old_clipBoxes_in.get(_pointcloud3), old_clipBoxes_out.get(_pointcloud3), old_highlightBoxes.get(_pointcloud3));
  21393. }
  21394. }
  21395. if (needsUpdate) {
  21396. for (var _pointcloud4 of pointclouds) {
  21397. //不恢复的话(尤其cameraChanged时),在下次render前,再次pick可能是错的。表现为多数据集刚开始reticule消失了,直到ifPointBlockedByIntersect停止
  21398. _pointcloud4.visibleNodes = old_visibleNodes.get(_pointcloud4);
  21399. }
  21400. }
  21401. if (selectedPointcloud) {
  21402. return {
  21403. location: closestIntersection,
  21404. distance: closestDistance,
  21405. pointcloud: selectedPointcloud,
  21406. point: closestPoint,
  21407. pointclouds: allPointclouds,
  21408. //add
  21409. normal: closestPoint.normal && new Vector3().fromArray(closestPoint.normal).applyMatrix4(selectedPointcloud.rotateMatrix) //add
  21410. };
  21411. } else {
  21412. return null;
  21413. }
  21414. };
  21415. Utils.pixelsArrayToDataUrl = function (pixels, width, height) {
  21416. var compressRatio = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.7;
  21417. var canvas = document.createElement('canvas');
  21418. canvas.width = width;
  21419. canvas.height = height;
  21420. var context = canvas.getContext('2d');
  21421. pixels = new pixels.constructor(pixels);
  21422. /* for (let i = 0; i < pixels.length; i++) {
  21423. pixels[i * 4 + 3] = 255;
  21424. } */
  21425. // flip vertically
  21426. var bytesPerLine = width * 4;
  21427. for (var i = 0; i < parseInt(height / 2); i++) {
  21428. var j = height - i - 1;
  21429. var lineI = pixels.slice(i * bytesPerLine, i * bytesPerLine + bytesPerLine);
  21430. var lineJ = pixels.slice(j * bytesPerLine, j * bytesPerLine + bytesPerLine);
  21431. pixels.set(lineJ, i * bytesPerLine);
  21432. pixels.set(lineI, j * bytesPerLine);
  21433. }
  21434. var imageData = context.createImageData(width, height);
  21435. imageData.data.set(pixels);
  21436. context.putImageData(imageData, 0, 0);
  21437. var dataURL = canvas.toDataURL(compressRatio);
  21438. return dataURL;
  21439. };
  21440. Utils.renderTargetToDataUrl = function (renderTarget, width, height, renderer) {
  21441. var compressRatio = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0.7;
  21442. var pixelCount = width * height;
  21443. var buffer = new Uint8Array(4 * pixelCount);
  21444. renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, buffer);
  21445. var dataUrl = Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio);
  21446. return dataUrl;
  21447. };
  21448. Utils.mouseToRay = function (pointer, camera) {
  21449. var vector = new Vector3(pointer.x, pointer.y, 1);
  21450. var origin = new Vector3(pointer.x, pointer.y, -1); //不能用camera.position,在orbitCamera时不准
  21451. vector.unproject(camera);
  21452. origin.unproject(camera);
  21453. var direction = new Vector3().subVectors(vector, origin).normalize();
  21454. var ray = new Ray(origin, direction);
  21455. return ray;
  21456. };
  21457. Utils.getPos2d = function (point, viewport, dom, renderer) {
  21458. //获取一个三维坐标对应屏幕中的二维坐标
  21459. var pos;
  21460. if (math.closeTo(viewport.camera.position, point, 1e-5)) {
  21461. //和相机位置重合时显示会四处飘,看是要改成一直显示中间还是隐藏?
  21462. pos = new Vector3(0, 0, 1.5); //1.5是为了不可见
  21463. } else {
  21464. pos = point.clone().project(viewport.camera); //比之前hotspot的计算方式写得简单 project用于3转2(求法同shader); unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera);
  21465. }
  21466. var size = renderer && renderer.getSize(new Vector2()); //如果是渲染到renderTarget上,resolution和dom的大小不一致。如果输出的结果给前端2d用,就使用clinetWidth,如果自己场景用,用renderer.size
  21467. var w = renderer ? size.x : dom.clientWidth;
  21468. var h = renderer ? size.y : dom.clientHeight;
  21469. var x, y, left, top;
  21470. x = (pos.x + 1) / 2 * w * viewport.width;
  21471. y = (1 - (pos.y + 1) / 2) * h * viewport.height;
  21472. left = viewport.left * w;
  21473. top = (1 - viewport.bottom - viewport.height) * h;
  21474. var inSight = pos.x <= 1 && pos.x >= -1 //是否在屏幕中
  21475. && pos.x <= 1 && pos.y >= -1;
  21476. return {
  21477. pos: new Vector2(left + x, top + y),
  21478. // 屏幕像素坐标
  21479. vector: pos,
  21480. //(范围 -1 ~ 1)
  21481. trueSide: pos.z < 1,
  21482. //trueSide为false时,即使在屏幕范围内可见,也是反方向的另一个不可以被渲染的点 参见Tag.update
  21483. inSight: inSight,
  21484. //在屏幕范围内可见,
  21485. posInViewport: new Vector2(x, y)
  21486. };
  21487. };
  21488. Utils.screenPass = new function () {
  21489. this.screenScene = new Scene();
  21490. this.screenQuad = new Mesh(new PlaneBufferGeometry(2, 2, 1));
  21491. this.screenQuad.material.depthTest = true;
  21492. this.screenQuad.material.depthWrite = true;
  21493. this.screenQuad.material.transparent = true;
  21494. this.screenScene.add(this.screenQuad);
  21495. this.camera = new Camera();
  21496. this.render = function (renderer, material, target, composer) {
  21497. this.screenQuad.material = material;
  21498. if (typeof target === 'undefined') {
  21499. (composer || renderer).render(this.screenScene, this.camera);
  21500. } else {
  21501. var oldTarget = renderer.getRenderTarget();
  21502. renderer.setRenderTarget(target);
  21503. //renderer.clear(); //有时候不能clear,如renderBG后再
  21504. (composer || renderer).render(this.screenScene, this.camera);
  21505. renderer.setRenderTarget(oldTarget);
  21506. }
  21507. };
  21508. }();
  21509. //add
  21510. Utils.computePointcloudsBound = function (pointclouds) {
  21511. var boundingBox = new Box3();
  21512. pointclouds.forEach(pointcloud => {
  21513. pointcloud.updateBound();
  21514. boundingBox.union(pointcloud.bound2);
  21515. });
  21516. var boundSize = boundingBox.getSize(new Vector3());
  21517. var center = boundingBox.getCenter(new Vector3());
  21518. return {
  21519. boundSize,
  21520. center,
  21521. boundingBox
  21522. };
  21523. };
  21524. Utils.convertScreenPositionToNDC = function (pointer, mouse, width, height) {
  21525. return pointer = pointer || new Vector2(), pointer.x = mouse.x / width * 2 - 1, pointer.y = 2 * -(mouse.y / height) + 1, pointer;
  21526. };
  21527. Utils.convertNDCToScreenPosition = function (pointer, mouse, width, height) {
  21528. return mouse = mouse || new Vector2(), mouse.x = Math.round((pointer.x + 1) / 2 * width), mouse.y = Math.round(-(pointer.y - 1) / 2 * height), mouse;
  21529. };
  21530. Utils.getOrthoCameraMoveVec = function (pointerDelta, camera) {
  21531. //获取当camera为Ortho型时 屏幕点1 到 屏幕点2 的三维距离
  21532. var cameraViewWidth = camera.right / camera.zoom;
  21533. var cameraViewHeight = camera.top / camera.zoom;
  21534. var moveVec = new Vector3();
  21535. moveVec.set(pointerDelta.x * cameraViewWidth, pointerDelta.y * cameraViewHeight, 0).applyQuaternion(camera.quaternion);
  21536. return moveVec;
  21537. };
  21538. Utils.VectorFactory = {
  21539. fromArray: function fromArray(t) {
  21540. if (t) {
  21541. if (t.length < 2 || t.length > 3) console.error("Wrong number of ordinates for a point!");
  21542. return 3 === t.length ? new Vector3().fromArray(t) : new Vector2().fromArray(t);
  21543. }
  21544. },
  21545. fromArray3: function fromArray3(t) {
  21546. if (t) {
  21547. if (3 !== t.length) console.error("Wrong number of ordinates for a point!");
  21548. return new Vector3().fromArray(t);
  21549. }
  21550. },
  21551. fromArray2: function fromArray2(t) {
  21552. if (t) {
  21553. if (2 !== t.length) console.error("Wrong number of ordinates for a point!");
  21554. return new Vector2().fromArray(t);
  21555. }
  21556. },
  21557. toString: function toString(t) {
  21558. return t.x.toFixed(8) + "," + t.y.toFixed(8) + "," + t.z.toFixed(3);
  21559. }
  21560. };
  21561. Utils.QuaternionFactory = {
  21562. rot90: new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), MathUtils.degToRad(-90)),
  21563. fromArray: function fromArray(t) {
  21564. if (t) {
  21565. if (4 !== t.length) console.error("Wrong number of ordinates for a quaternion!");
  21566. return new Quaternion(t[1], t[2], t[3], t[0]).multiply(this.rot90);
  21567. }
  21568. },
  21569. toArray: function toArray(t) {
  21570. if (t) {
  21571. var e = t.clone().multiply(a).toArray();
  21572. return [e[3], e[0], e[1], e[2]];
  21573. }
  21574. },
  21575. fromLonLat: function fromLonLat(t) {
  21576. if (t) return new Quaternion().setFromEuler(new Euler(t.lon, t.lat, 0));
  21577. },
  21578. toLonLat: function toLonLat(t) {
  21579. if (t) {
  21580. var e = new Euler().setFromQuaternion(t);
  21581. return {
  21582. lon: e.x,
  21583. lat: e.y
  21584. };
  21585. }
  21586. }
  21587. };
  21588. Utils.datasetPosTransform = function () {
  21589. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  21590. var pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e => e.dataset_id == o.datasetId);
  21591. var tranMatrix;
  21592. if (pointcloud) {
  21593. if (Potree.settings.editType == 'merge') {
  21594. tranMatrix = o.fromDataset ? pointcloud.matrixWorld : new Matrix4().copy(pointcloud.matrixWorld).invert();
  21595. } else {
  21596. tranMatrix = o.fromDataset ? pointcloud.transformMatrix : pointcloud.transformInvMatrix;
  21597. }
  21598. } else {
  21599. if (Potree.settings.intersectOnObjs) {
  21600. var object = o.object || viewer.objs.children.find(e => e.dataset_id == o.datasetId);
  21601. if (object) {
  21602. tranMatrix = o.fromDataset ? object.matrixWorld : new Matrix4().copy(object.matrixWorld).invert();
  21603. }
  21604. }
  21605. }
  21606. if (tranMatrix) {
  21607. return new Vector3().copy(o.position).applyMatrix4(tranMatrix);
  21608. } else {
  21609. if (o.datasetId != void 0) {
  21610. console.error("datasetPosTransform\u627E\u4E0D\u5230datasetId\u4E3A".concat(o.datasetId, "\u7684\u6570\u636E\u96C6\u6216\u6A21\u578B\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\uFF0C \u6A21\u578B\u672A\u521B\u5EFA\u6216\u5220\u9664"));
  21611. //很可能是旧的热点,需要删除
  21612. }
  21613. }
  21614. };
  21615. Utils.datasetRotTransform = function () {
  21616. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  21617. var pointcloud = o.pointcloud || viewer.scene.pointclouds.find(e => e.dataset_id == o.datasetId);
  21618. if (pointcloud) {
  21619. var matrix, newMatrix, result;
  21620. if (o.rotation) {
  21621. matrix = new Matrix4().makeRotationFromEuler(o.rotation);
  21622. } else if (o.quaternion) {
  21623. matrix = new Matrix4().makeRotationFromQuaternion(o.quaternion);
  21624. } else if (o.matrix) {
  21625. matrix = o.matrix.clone();
  21626. } else {
  21627. return;
  21628. }
  21629. var rotateMatrix = o.fromDataset ? pointcloud.rotateMatrix : pointcloud.rotateInvMatrix;
  21630. newMatrix = new Matrix4().multiplyMatrices(rotateMatrix, matrix);
  21631. if (o.getRotation) {
  21632. result = new Euler().setFromRotationMatrix(newMatrix);
  21633. } else if (o.getQuaternion) {
  21634. result = new Quaternion().setFromRotationMatrix(newMatrix);
  21635. } else if (o.getMatrix) {
  21636. result = newMatrix;
  21637. }
  21638. return result;
  21639. }
  21640. };
  21641. Utils.isInsideFrustum = function (bounding, camera) {
  21642. // bounding是否在视野范围内有可见部分(视野就是一个锥状box)
  21643. var frustumMatrix = new Matrix4();
  21644. frustumMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  21645. var frustum = new Frustum();
  21646. frustum.setFromProjectionMatrix(frustumMatrix);
  21647. if (bounding instanceof Sphere) {
  21648. return frustum.intersectsSphere(bounding);
  21649. } else {
  21650. return frustum.intersectsBox(bounding);
  21651. }
  21652. };
  21653. Utils.isIntersectBox = function (object, boxMatrix) {
  21654. //object是否有在box中的部分。 object可以是点或者bounding, box原为1*1*1,但可能形变
  21655. //let frustum = new THREE.Frustum();
  21656. //frustum.setFromProjectionMatrix(boxMatrixInverse) --错
  21657. var px = new Vector3(+0.5, 0, 0).applyMatrix4(boxMatrix);
  21658. var nx = new Vector3(-0.5, 0, 0).applyMatrix4(boxMatrix);
  21659. var py = new Vector3(0, +0.5, 0).applyMatrix4(boxMatrix);
  21660. var ny = new Vector3(0, -0.5, 0).applyMatrix4(boxMatrix);
  21661. var pz = new Vector3(0, 0, +0.5).applyMatrix4(boxMatrix);
  21662. var nz = new Vector3(0, 0, -0.5).applyMatrix4(boxMatrix);
  21663. var pxN = new Vector3().subVectors(nx, px).normalize();
  21664. var nxN = pxN.clone().multiplyScalar(-1);
  21665. var pyN = new Vector3().subVectors(ny, py).normalize();
  21666. var nyN = pyN.clone().multiplyScalar(-1);
  21667. var pzN = new Vector3().subVectors(nz, pz).normalize();
  21668. var nzN = pzN.clone().multiplyScalar(-1);
  21669. var pxPlane = new Plane().setFromNormalAndCoplanarPoint(pxN, px);
  21670. var nxPlane = new Plane().setFromNormalAndCoplanarPoint(nxN, nx);
  21671. var pyPlane = new Plane().setFromNormalAndCoplanarPoint(pyN, py);
  21672. var nyPlane = new Plane().setFromNormalAndCoplanarPoint(nyN, ny);
  21673. var pzPlane = new Plane().setFromNormalAndCoplanarPoint(pzN, pz);
  21674. var nzPlane = new Plane().setFromNormalAndCoplanarPoint(nzN, nz);
  21675. var frustum = new Frustum(pxPlane, nxPlane, pyPlane, nyPlane, pzPlane, nzPlane);
  21676. if (object instanceof Box3) {
  21677. var boxBound = new Box3(new Vector3(-0.5, -0.5, -0.5), new Vector3(0.5, 0.5, 0.5)).applyMatrix4(boxMatrix); //large boundingbox
  21678. if (!object.intersectsBox(boxBound)) return;
  21679. return frustum.intersectsBox(object); //根据该函数, 若存在某个plane在box上的对应点都在plane背面,则不相交. 可得知在box构成的frustum倾斜时不准确,不相交也判断为相交,甚至不如bound相交准确。所以前面加步骤排除下,但仍不完全准确。(可在裁剪中将box放置到数据集上方旋转下校验)
  21680. } else if (object instanceof Array) {
  21681. //点合集, 只能粗略计算下
  21682. var sphere = new Sphere();
  21683. sphere.setFromPoints(object);
  21684. return this.isIntersectBox(sphere, boxMatrix);
  21685. } else if (object instanceof Sphere) {
  21686. return frustum.intersectsSphere(object);
  21687. } else if (object instanceof Vector3) {
  21688. return frustum.containsPoint(object);
  21689. } else if (object instanceof Matrix4) {//第一个参数如果和第二个参数一样都是box的worldMatrix
  21690. }
  21691. /* containsPoint: ƒ containsPoint( point )
  21692. intersectsBox: ƒ intersectsBox( box )
  21693. intersectsObject: ƒ intersectsObject( object )//geo
  21694. intersectsSphere: ƒ intersectsSphere( sphere )
  21695. intersectsSprite: ƒ intersectsSprite( sprite )
  21696. */
  21697. };
  21698. Utils.getIntersect = function (camera, meshes, pointer, raycaster) {
  21699. //获取鼠标和meshes交点
  21700. if (!raycaster) {
  21701. //getMouseIntersect
  21702. camera.updateMatrixWorld();
  21703. raycaster = new Raycaster();
  21704. var origin = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  21705. end = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  21706. var dir = end.sub(origin).normalize();
  21707. raycaster.set(origin, dir);
  21708. }
  21709. meshes.forEach(e => {
  21710. raycaster.layers.enable(math.getBaseLog(2, e.layers.mask));
  21711. });
  21712. var n = raycaster.intersectObjects(meshes);
  21713. if (0 === n.length) return null;
  21714. return n[0];
  21715. };
  21716. Utils.addOrRemoveDefine = function (material, defineName, type) {
  21717. var value = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '';
  21718. var defines = material.defines;
  21719. if (type == 'add') {
  21720. if (defines[defineName] != void 0 && defines[defineName] == value) return;
  21721. defines[defineName] = value;
  21722. } else {
  21723. if (defines[defineName] != void 0) return;
  21724. delete defines[defineName];
  21725. }
  21726. material.needsUpdate = true;
  21727. };
  21728. Utils.makeTexDontResize = function (map) {
  21729. //避免贴图因非2的次方而缩小。小心使用
  21730. if (!map || !map.image) {
  21731. return console.log('!map || !map.image', map, map && map.image);
  21732. }
  21733. if (MathUtils.isPowerOfTwo(map.image.width) && MathUtils.isPowerOfTwo(map.image.height)) return;
  21734. map.wrapS = map.wrapT = ClampToEdgeWrapping; //原默认 RepeatWrapping
  21735. map.minFilter = LinearFilter; // or THREE.NearestFilter 原默认 LinearMipmapLinearFilter
  21736. map.generateMipmaps = false;
  21737. map.needsUpdate = true;
  21738. };
  21739. Utils.updateVisible = function (object, reason, ifShow) {
  21740. var level = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  21741. var type = arguments.length > 4 ? arguments[4] : undefined;
  21742. //当所有加入的条件都不为false时才显示. reason='force'一般是强制、临时的
  21743. if (!object.unvisibleReasons) object.unvisibleReasons = []; //如果length>0代表不可见
  21744. if (!object.visibleReasons) object.visibleReasons = []; //在同级时,优先可见
  21745. var update = function update() {
  21746. //先按从高到低的level排列
  21747. object.unvisibleReasons = object.unvisibleReasons.sort((a, b) => b.level - a.level);
  21748. object.visibleReasons = object.visibleReasons.sort((a, b) => b.level - a.level);
  21749. var maxVisiLevel = object.visibleReasons[0] ? object.visibleReasons[0].level : -1;
  21750. var maxunVisiLevel = object.unvisibleReasons[0] ? object.unvisibleReasons[0].level : -1;
  21751. var shouldVisi = maxVisiLevel >= maxunVisiLevel;
  21752. var visiBefore = object.visible;
  21753. if (visiBefore != shouldVisi) {
  21754. object.visible = shouldVisi;
  21755. object.dispatchEvent({
  21756. type: 'isVisible',
  21757. visible: shouldVisi,
  21758. reason
  21759. });
  21760. }
  21761. };
  21762. if (ifShow) {
  21763. var index = object.unvisibleReasons.findIndex(e => e.reason == reason);
  21764. if (index > -1) {
  21765. type = 'cancel';
  21766. object.unvisibleReasons.splice(index, 1);
  21767. }
  21768. if (type == 'add') {
  21769. if (!object.visibleReasons.some(e => e.reason == reason)) {
  21770. object.visibleReasons.push({
  21771. reason,
  21772. level
  21773. });
  21774. }
  21775. }
  21776. } else {
  21777. var index = object.visibleReasons.findIndex(e => e.reason == reason);
  21778. if (index > -1) {
  21779. type = 'cancel';
  21780. object.visibleReasons.splice(index, 1);
  21781. }
  21782. if (type != 'cancel') {
  21783. if (!object.unvisibleReasons.some(e => e.reason == reason)) {
  21784. object.unvisibleReasons.push({
  21785. reason,
  21786. level
  21787. });
  21788. }
  21789. }
  21790. }
  21791. update();
  21792. };
  21793. /*
  21794. 复杂案例: 如果物体默认隐藏, 当符合任何一个其他条件时可见,则可:
  21795. Potree.Utils.updateVisible(this, "default", false, 0 ) //默认隐藏
  21796. Potree.Utils.updateVisible(this, 条件名, ifShow, 1, ifShow?'add':'cancel' ) //其他的条件
  21797. */
  21798. Utils.getObjVisiByReason = function (object, reason) {
  21799. //获取在某条件下是否可见. 注: 用户在数据集选择可不可见为"datasetSelection"
  21800. if (object.visible) return true;else {
  21801. return !object.unvisibleReasons || !object.unvisibleReasons.some(e => e.reason == reason);
  21802. }
  21803. };
  21804. Utils.setCameraLayers = function (camera, enableLayers) {
  21805. var extraEnableLayers = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  21806. //add
  21807. camera.layers.disableAll();
  21808. enableLayers.concat(extraEnableLayers).forEach(e => {
  21809. var layer = Potree.config.renderLayers[e];
  21810. if (layer == void 0) {
  21811. console.error('setCameraLayer没找到layer!');
  21812. return;
  21813. }
  21814. camera.layers.enable(layer);
  21815. });
  21816. };
  21817. Utils.setObjectLayers = function (object, layerName) {
  21818. //add
  21819. var layer = Potree.config.renderLayers[layerName];
  21820. if (layer == void 0) {
  21821. console.error('setObjectLayers没找到layer!', layerName);
  21822. return;
  21823. }
  21824. object.traverse(e => {
  21825. e.layers.set(layer);
  21826. });
  21827. };
  21828. Utils.imgAddText = /*#__PURE__*/function () {
  21829. var _ref = _asyncToGenerator(function* (img, text, labelInfo) {
  21830. var label = new Potree.TextSprite(Object.assign({
  21831. //如果直接在canvas里写字,要另外写很多和canvas.drawText有关的,所以还是借助textSprite吧
  21832. backgroundColor: {
  21833. r: 0,
  21834. g: 0,
  21835. b: 0,
  21836. a: 0
  21837. },
  21838. textColor: {
  21839. r: 255,
  21840. g: 255,
  21841. b: 255,
  21842. a: 1
  21843. },
  21844. margin: {
  21845. x: 3,
  21846. y: 3
  21847. },
  21848. renderOrder: 50,
  21849. fontsize: 20,
  21850. text
  21851. }, labelInfo));
  21852. var labelImg = new Image();
  21853. labelImg.src = label.sprite.material.map.image.toDataURL('image/png');
  21854. return new Promise((resolve, reject) => {
  21855. labelImg.onload = () => {
  21856. if (labelInfo.horizonCenter) {
  21857. //水平居中(对img来说)
  21858. labelInfo.leftRatioToImg = 0.5 - labelImg.width / img.width / 2;
  21859. }
  21860. var result = Common.imgAddLabel(img, labelImg, labelInfo);
  21861. label.dispose();
  21862. resolve(result);
  21863. };
  21864. });
  21865. });
  21866. return function (_x, _x2, _x3) {
  21867. return _ref.apply(this, arguments);
  21868. };
  21869. }();
  21870. Utils.combineImgs = /*#__PURE__*/function () {
  21871. var _ref2 = _asyncToGenerator(function* (imgs, compressRatio, width, height) {
  21872. //拼合图片,顺序从上到下从左到右, 每张图大小不一定一致,但同列的宽一致,同行宽一致
  21873. return new Promise((resolve, reject) => {
  21874. var item = imgs[0][0];
  21875. var wc = imgs.length,
  21876. hc = imgs[0].length,
  21877. loadCount = 0,
  21878. amount = wc * hc;
  21879. width = width || imgs.reduce((w, c) => w + c[0].width, 0),
  21880. //相加得到的可能比想要得到的大几个像素,之后会重叠
  21881. height = height || imgs[0].reduce((w, c) => w + c.height, 0);
  21882. var canvas = document.createElement('canvas');
  21883. canvas.width = width;
  21884. canvas.height = height;
  21885. var context = canvas.getContext('2d');
  21886. for (var i = 0; i < wc; i++) {
  21887. var _loop = function _loop() {
  21888. var img = new Image();
  21889. img.src = imgs[i][j].dataUrl;
  21890. img.index = {
  21891. i,
  21892. j
  21893. };
  21894. img.onload = () => {
  21895. loadCount++;
  21896. context.drawImage(img, img.index.i * img.width, img.index.j * img.height, img.width, img.height);
  21897. if (loadCount == amount) {
  21898. var dataUrl = canvas.toDataURL('image/png', compressRatio);
  21899. context.clearRect(0, 0, width, height);
  21900. resolve(dataUrl);
  21901. }
  21902. };
  21903. };
  21904. for (var j = 0; j < hc; j++) {
  21905. _loop();
  21906. }
  21907. }
  21908. });
  21909. });
  21910. return function (_x4, _x5, _x6, _x7) {
  21911. return _ref2.apply(this, arguments);
  21912. };
  21913. }();
  21914. BinaryLoader.prototype.load = function (node, callback) {
  21915. //解析点云
  21916. if (node.loaded) {
  21917. return;
  21918. }
  21919. var url = node.getURL();
  21920. if (this.version.equalOrHigher('1.4')) {
  21921. url += '.bin';
  21922. }
  21923. url += '?m=' + node.pcoGeometry.timeStamp; //add
  21924. var xhr = XHRFactory.createXMLHttpRequest();
  21925. xhr.open('GET', url, true);
  21926. xhr.responseType = 'arraybuffer';
  21927. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  21928. xhr.onreadystatechange = () => {
  21929. if (xhr.readyState === 4) {
  21930. if ((xhr.status === 200 || xhr.status === 0) && xhr.response !== null) {
  21931. var buffer = xhr.response;
  21932. this.parse(node, buffer, callback);
  21933. } else {
  21934. node.loadFailed = 'status:' + xhr.status + ",url:" + url;
  21935. Potree.numNodesLoading--;
  21936. //console.error(`Failed to load file! HTTP status: ${xhr.status}, file: ${url}`);
  21937. throw new Error("Failed to load file! HTTP status: ".concat(xhr.status, ", file: ").concat(url));
  21938. }
  21939. }
  21940. };
  21941. try {
  21942. xhr.send(null);
  21943. } catch (e) {
  21944. node.loadFailed = 'catchError';
  21945. Potree.numNodesLoading--;
  21946. console.error('加载点云node出错 ', url, e);
  21947. }
  21948. };
  21949. PointAttribute.RGBA_PACKED = new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_INT8, 4);
  21950. PointAttribute.COLOR_PACKED = PointAttribute.RGBA_PACKED;
  21951. PointAttribute.INTENSITY = new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1);
  21952. PointAttribute.CLASSIFICATION = new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1);
  21953. PointAttribute.GPS_TIME = new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1);
  21954. ProfileWindow.prototype.initTHREE = function () {
  21955. this.renderer = new WebGLRenderer({
  21956. alpha: true,
  21957. premultipliedAlpha: false
  21958. });
  21959. this.renderer.setClearColor(0x000000, 0);
  21960. this.renderer.setSize(10, 10);
  21961. this.renderer.autoClear = false;
  21962. this.renderArea.append($(this.renderer.domElement));
  21963. this.renderer.domElement.tabIndex = '2222';
  21964. $(this.renderer.domElement).css('width', '100%');
  21965. $(this.renderer.domElement).css('height', '100%');
  21966. {
  21967. var gl = this.renderer.getContext();
  21968. if (gl.createVertexArray == null) {
  21969. var extVAO = gl.getExtension('OES_vertex_array_object');
  21970. if (!extVAO) {
  21971. throw new Error("OES_vertex_array_object extension not supported");
  21972. }
  21973. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  21974. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  21975. }
  21976. }
  21977. this.camera = new OrthographicCamera(-1000, 1000, 1000, -1000, -1000, 1000);
  21978. this.camera.up.set(0, 0, 1);
  21979. this.camera.rotation.order = "ZXY";
  21980. this.camera.rotation.x = Math.PI / 2.0;
  21981. this.scene = new Scene();
  21982. this.profileScene = new Scene();
  21983. var sg = new SphereGeometry(1, 16, 16);
  21984. var sm = new MeshNormalMaterial();
  21985. this.pickSphere = new Mesh(sg, sm);
  21986. this.scene.add(this.pickSphere);
  21987. this.viewerPickSphere = new Mesh(sg, sm);
  21988. };
  21989. //Potree_update_visibility
  21990. Potree.updatePointClouds = function (pointclouds, camera, areaSize) {
  21991. viewer.addTimeMark('updateClouds', 'start');
  21992. for (var pointcloud of pointclouds) {
  21993. var start = performance.now();
  21994. for (var profileRequest of pointcloud.profileRequests) {
  21995. profileRequest.update();
  21996. var _duration = performance.now() - start;
  21997. if (_duration > 5) {
  21998. break;
  21999. }
  22000. }
  22001. var duration = performance.now() - start;
  22002. }
  22003. var result = Potree.updateVisibility(pointclouds, camera, areaSize);
  22004. for (var _pointcloud5 of pointclouds) {
  22005. //pointcloud.updateMaterial(pointcloud.material, pointcloud.visibleNodes, camera, renderer);//转移到渲染时
  22006. _pointcloud5.updateVisibleBounds();
  22007. }
  22008. Potree.lru.freeMemory(); //即Potree.lru 能看到所有在加载的node
  22009. viewer.addTimeMark('updateClouds', 'end');
  22010. return result;
  22011. };
  22012. Potree.updateVisibilityStructures = function (pointclouds, camera, areaSize) {
  22013. var frustums = {};
  22014. var camObjPositions = {};
  22015. var camObjDirs = {}; //add
  22016. var priorityQueue = new BinaryHeap(function (x) {
  22017. return -x.weight; /* 1 / x.weight; */
  22018. }); //二叉堆。 改,之前的weight不支持负数
  22019. viewer.addTimeMark('visiStructure', 'start');
  22020. //camera.updateMatrixWorld();
  22021. var viewI = camera.matrixWorldInverse;
  22022. var proj = camera.projectionMatrix;
  22023. var view = camera.matrixWorld;
  22024. var projViewI = new Matrix4().multiply(proj).multiply(viewI);
  22025. /* let list = pointclouds // stopWhenAllUsed = !viewer.lastFrameChanged
  22026. let min = 5, max = Math.max(20 , Math.round(list.length / 10 ))
  22027. let result = Common.batchHandling.getSlice('pcGetFrustum', list, { min,max, durBound1: 3, durBound2: 10} ) //iphonex稳定后大概在7-10。
  22028. */
  22029. for (var i = 0; i < pointclouds.length; i++) {
  22030. var pointcloud = pointclouds[i];
  22031. if (!pointcloud.initialized()) {
  22032. continue;
  22033. }
  22034. /* let info = history.get(pointcloud)
  22035. if() */
  22036. pointcloud.numVisibleNodes = 0;
  22037. pointcloud.numVisiblePoints = 0;
  22038. pointcloud.deepestVisibleLevel = 0;
  22039. pointcloud.visibleNodes = [];
  22040. pointcloud.visibleGeometry = [];
  22041. // 因漫游模式而隐藏的话 依旧需要加入visibleNodes,因为pick需要
  22042. /* if (pointcloud.visible && pointcloud.root !== null) {
  22043. priorityQueue.push({pointcloud: i, node: pointcloud.root, weight: Number.MAX_VALUE});
  22044. } */
  22045. if (pointcloud.visible || !pointcloud.hasDepthTex && pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode' && pointcloud.root !== null) {
  22046. //改 visible ->
  22047. priorityQueue.push({
  22048. pointcloud: i,
  22049. node: pointcloud.root,
  22050. weight: Number.MAX_VALUE
  22051. });
  22052. } else {
  22053. continue;
  22054. }
  22055. // frustum in object space
  22056. var frustum = new Frustum();
  22057. var world = pointcloud.matrixWorld;
  22058. // use close near plane for frustum intersection
  22059. /* let frustumCam = camera.clone();
  22060. frustumCam.zoom = camera.zoom //add
  22061. frustumCam.near = Math.min(camera.near, 0.1);
  22062. frustumCam.updateProjectionMatrix(); */ //----没用到frustumCam,删了
  22063. var fm = new Matrix4().multiply(projViewI).multiply(world);
  22064. frustum.setFromProjectionMatrix(fm);
  22065. frustums[i] = frustum; //frustums.push(frustum);
  22066. // camera position in object space
  22067. var worldI = pointcloud.matrixWorldInverse;
  22068. var camMatrixObject = new Matrix4().multiply(worldI).multiply(view); //假设点云无变换的话,相机相对于点云的变换矩阵
  22069. var camObjPos = new Vector3().setFromMatrixPosition(camMatrixObject);
  22070. camObjPositions[i] = camObjPos; //camObjPositions.push(camObjPos);
  22071. var quaternion = new Quaternion().setFromRotationMatrix(camMatrixObject);
  22072. var camDir = new Vector3(0, 0, -1).applyQuaternion(quaternion);
  22073. camObjDirs[i] = camDir;
  22074. // hide all previously visible nodes
  22075. // if(pointcloud.root instanceof PointCloudOctreeNode){
  22076. // pointcloud.hideDescendants(pointcloud.root.sceneNode);
  22077. // }
  22078. if (pointcloud.root.isTreeNode()) {
  22079. pointcloud.hideDescendants(pointcloud.root.sceneNode);
  22080. }
  22081. for (var j = 0; j < pointcloud.boundingBoxNodes.length; j++) {
  22082. pointcloud.boundingBoxNodes[j].visible = false;
  22083. }
  22084. }
  22085. viewer.addTimeMark('visiStructure', 'end');
  22086. return {
  22087. 'frustums': frustums,
  22088. 'camObjPositions': camObjPositions,
  22089. 'priorityQueue': priorityQueue,
  22090. camObjDirs
  22091. };
  22092. };
  22093. Potree.updateVisibility = function (pointclouds, camera, areaSize) {
  22094. var numVisibleNodes = 0;
  22095. var numVisiblePoints = 0;
  22096. var numVisiblePointsInPointclouds = new Map(pointclouds.map(pc => [pc, 0]));
  22097. var visibleNodes = [];
  22098. var visibleGeometry = [];
  22099. var unloadedGeometry = [];
  22100. var lowestSpacing = Infinity;
  22101. // calculate object space frustum and cam pos and setup priority queue
  22102. var s = Potree.updateVisibilityStructures(pointclouds, camera, areaSize); //得到相机可见范围
  22103. var frustums = s.frustums;
  22104. var camObjPositions = s.camObjPositions;
  22105. var priorityQueue = s.priorityQueue;
  22106. var camObjDirs = s.camObjDirs;
  22107. var loadedToGPUThisFrame = 0;
  22108. var domWidth = areaSize.x; //renderer.domElement.clientWidth;
  22109. var domHeight = areaSize.y; //renderer.domElement.clientHeight;
  22110. var fov = camera.fov * Math.PI / 180;
  22111. var slope = Math.tan(fov / 2);
  22112. var projFactor0 = 0.5 * domHeight / slope;
  22113. // check if pointcloud has been transformed
  22114. // some code will only be executed if changes have been detected
  22115. if (!Potree._pointcloudTransformVersion) {
  22116. Potree._pointcloudTransformVersion = new Map();
  22117. }
  22118. var pointcloudTransformVersion = Potree._pointcloudTransformVersion;
  22119. for (var pointcloud of pointclouds) {
  22120. if (pointcloud.hasDepthTex ? !pointcloud.visible : !Potree.Utils.getObjVisiByReason(pointcloud, 'datasetSelection')) {
  22121. //改 visible ->
  22122. continue;
  22123. }
  22124. //if(!pointcloud.visible) continue
  22125. pointcloud.updateMatrixWorld();
  22126. if (!pointcloudTransformVersion.has(pointcloud)) {
  22127. pointcloudTransformVersion.set(pointcloud, {
  22128. number: 0,
  22129. transform: pointcloud.matrixWorld.clone()
  22130. });
  22131. } else {
  22132. var version = pointcloudTransformVersion.get(pointcloud);
  22133. if (!version.transform.equals(pointcloud.matrixWorld)) {
  22134. version.number++;
  22135. version.transform.copy(pointcloud.matrixWorld);
  22136. pointcloud.dispatchEvent({
  22137. type: "transformation_changed",
  22138. target: pointcloud
  22139. });
  22140. }
  22141. }
  22142. }
  22143. var _loop2 = function _loop2() {
  22144. var element = priorityQueue.pop(); //取出权重最大的一个
  22145. var node = element.node;
  22146. var parent = element.parent;
  22147. var pointcloud = pointclouds[element.pointcloud];
  22148. // { // restrict to certain nodes for debugging
  22149. // let allowedNodes = ["r", "r0", "r4"];
  22150. // if(!allowedNodes.includes(node.name)){
  22151. // continue;
  22152. // }
  22153. // }
  22154. var box = node.getBoundingBox();
  22155. var frustum = frustums[element.pointcloud];
  22156. var camObjPos = camObjPositions[element.pointcloud];
  22157. if (!frustum) return 0; // continue
  22158. //add
  22159. var camObjDir = camObjDirs[element.pointcloud];
  22160. var insideFrustum = frustum.intersectsBox(box);
  22161. var maxLevel = pointcloud.maxLevel == void 0 ? Infinity : pointcloud.maxLevel;
  22162. var minLevel = pointcloud.minLevel == void 0 ? 0 : pointcloud.minLevel; //add
  22163. var level = node.getLevel();
  22164. var visible = insideFrustum;
  22165. visible = visible && !(numVisiblePoints + node.getNumPoints() > Potree.pointBudget);
  22166. visible = visible && !(numVisiblePointsInPointclouds.get(pointcloud) + node.getNumPoints() > pointcloud.pointBudget); // pointcloud.pointBudget一直是Infinity
  22167. visible = visible && level <= maxLevel /* && level >= minLevel */; //< 改为 <=
  22168. //visible = visible || node.getLevel() <= 2;
  22169. var pcWorldInverse = pointcloud.matrixWorld.clone().invert();
  22170. /* let m = pcWorldInverse.elements
  22171. let pcWorldInvM3 = new THREE.Matrix3().set(m[0],m[4],m[12],m[1],m[5],m[13],m[3],m[7],m[15]) //去掉z的
  22172. */
  22173. //pointcloud.pcMatrix3 = new THREE.Matrix3().set(m[0],m[4],m[12],m[1],m[5],m[13],m[3],m[7],m[15]) //去掉z的
  22174. var intersectBox = clipBox => {
  22175. var toPCObject = pcWorldInverse.clone().multiply(clipBox.box.matrixWorld); //box乘上点云逆矩阵
  22176. return Potree.Utils.isIntersectBox(box, toPCObject);
  22177. };
  22178. //改 总共两种box : 可见和不可见(都是并集)
  22179. var clipBoxes_in = pointcloud.material.clipBoxes_in;
  22180. var clipBoxes_out = pointcloud.material.clipBoxes_out;
  22181. var bigClipInBox = pointcloud.material.bigClipInBox;
  22182. if (visible && bigClipInBox) {
  22183. //不在剪裁下载的框内
  22184. if (!intersectBox(bigClipInBox)) {
  22185. visible = false;
  22186. }
  22187. }
  22188. if (visible && clipBoxes_in.length > 0) {
  22189. //当有可见box时,需要在任一可见box内才可见
  22190. var visi = false;
  22191. for (var _i = 0, length = clipBoxes_in.length; _i < length; _i++) {
  22192. if (intersectBox(clipBoxes_in[_i])) {
  22193. visi = true;
  22194. break;
  22195. }
  22196. }
  22197. if (!visi) {
  22198. visible = false;
  22199. }
  22200. }
  22201. //outside不做处理。因为node必须完全在clipBox内才能完全隐藏,而这里的intersect只能识别出部分在clipBox内。因而只能说明不在任意一个box内绝对可见,没有意义,这里需要找出不可见的。
  22202. if (visible) {
  22203. var prism = pointcloud.material.activeAttributeName == 'prismHeight' && pointcloud.material.prisms && pointcloud.material.prisms.find(e => e.computing);
  22204. if (prism) {
  22205. var bound = box.clone().applyMatrix4(pointcloud.matrixWorld);
  22206. if (bound.intersectsBox(prism.prismBound)) {
  22207. /* //node box是否包含points中的一个点
  22208. let box2 = new THREE.Box2().copy(box)
  22209. let points2d = prisms.points.map(e=>new THREE.Vector2().copy(e).applyMatrix3(pcWorldInvM3))
  22210. let intersect = points2d.some(e=>{
  22211. return box2.containsPoint(e)
  22212. })
  22213. if(!intersect){
  22214. //或者多边形中是否包含node box中的一个点
  22215. intersect = [
  22216. new THREE.Vector2(box.min.x, box.min.y),
  22217. new THREE.Vector2(box.max.x, box.max.y),
  22218. new THREE.Vector2(box.min.x, box.max.y),
  22219. new THREE.Vector2(box.max.x, box.min.y),
  22220. ].some(e=>{
  22221. if(math.isPointInArea(points2d, null, e) ){
  22222. return true
  22223. }
  22224. })
  22225. //z是不是在外层已经判断好了?
  22226. if(!intersect){
  22227. visible = false
  22228. }
  22229. } */
  22230. //会有两个互不包含点但是交叉了的情况,所以就不仔细判断了(如横竖两个矩形构成十字架)
  22231. } else visible = false;
  22232. }
  22233. }
  22234. if (node.spacing) {
  22235. lowestSpacing = Math.min(lowestSpacing, node.spacing);
  22236. } else if (node.geometryNode && node.geometryNode.spacing) {
  22237. lowestSpacing = Math.min(lowestSpacing, node.geometryNode.spacing);
  22238. }
  22239. if (numVisiblePoints + node.getNumPoints() > Potree.pointBudget) {
  22240. viewer.dispatchEvent({
  22241. type: 'overPointBudget',
  22242. restQueueSize: priorityQueue.size(),
  22243. numVisiblePoints
  22244. });
  22245. return 1; // break
  22246. }
  22247. if (!visible) {
  22248. return 0; // continue
  22249. }
  22250. // TODO: not used, same as the declaration?
  22251. // numVisibleNodes++;
  22252. numVisiblePoints += node.getNumPoints();
  22253. var numVisiblePointsInPointcloud = numVisiblePointsInPointclouds.get(pointcloud);
  22254. numVisiblePointsInPointclouds.set(pointcloud, numVisiblePointsInPointcloud + node.getNumPoints());
  22255. pointcloud.numVisibleNodes++;
  22256. pointcloud.numVisiblePoints += node.getNumPoints();
  22257. if (node.isGeometryNode() && (!parent || parent.isTreeNode())) {
  22258. if (node.isLoaded() && loadedToGPUThisFrame < 2) {
  22259. node = pointcloud.toTreeNode(node, parent);
  22260. loadedToGPUThisFrame++;
  22261. } else {
  22262. //console.log('unloadedGeometry',node)
  22263. unloadedGeometry.push({
  22264. pointcloud,
  22265. node
  22266. }); //加载点云。虽然还没加载,但也计入了visibleNodes,只是无children,numPoints=0
  22267. visibleGeometry.push(node);
  22268. }
  22269. }
  22270. if (node.isTreeNode()) {
  22271. Potree.lru.touch(node.geometryNode); //在缓存中计入点云
  22272. node.sceneNode.visible = true;
  22273. node.sceneNode.material = pointcloud.material;
  22274. /* level >= minLevel && */
  22275. visibleNodes.push(node);
  22276. /* level >= minLevel && */
  22277. pointcloud.visibleNodes.push(node);
  22278. if (node._transformVersion === undefined) {
  22279. node._transformVersion = -1;
  22280. }
  22281. var transformVersion = pointcloudTransformVersion.get(pointcloud);
  22282. if (node._transformVersion !== transformVersion.number) {
  22283. node.sceneNode.updateMatrix();
  22284. //node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  22285. node.sceneNode.matrixWorld.multiplyMatrices(pointcloud.matrixWorld, node.sceneNode.matrix);
  22286. node._transformVersion = transformVersion.number;
  22287. }
  22288. if (pointcloud.showBoundingBox && !node.boundingBoxNode && node.getBoundingBox) {
  22289. var colorHue = level / (maxLevel + 1);
  22290. var _s = 0.1 + level / (maxLevel + 1);
  22291. var color = new Color().setHSL(colorHue, _s, _s);
  22292. var boxHelper = new Box3Helper$1(node.getBoundingBox(), color);
  22293. boxHelper.matrixAutoUpdate = false;
  22294. pointcloud.boundingBoxNodes.push(boxHelper);
  22295. node.boundingBoxNode = boxHelper;
  22296. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  22297. } else if (pointcloud.showBoundingBox) {
  22298. node.boundingBoxNode.visible = true;
  22299. node.boundingBoxNode.matrix.copy(pointcloud.matrixWorld);
  22300. } else if (!pointcloud.showBoundingBox && node.boundingBoxNode) {
  22301. node.boundingBoxNode.visible = false;
  22302. }
  22303. // if(node.boundingBoxNode !== undefined && exports.debug.allowedNodes !== undefined){
  22304. // if(!exports.debug.allowedNodes.includes(node.name)){
  22305. // node.boundingBoxNode.visible = false;
  22306. // }
  22307. // }
  22308. }
  22309. // add child nodes to priorityQueue 由近及远、由大及小逐渐加载
  22310. var children = node.getChildren();
  22311. for (var _i2 = 0; _i2 < children.length; _i2++) {
  22312. var child = children[_i2];
  22313. var weight = 0;
  22314. if (camera.isPerspectiveCamera) {
  22315. var sphere = child.getBoundingSphere();
  22316. var center = sphere.center;
  22317. var dd = sphere.center.distanceToSquared(camObjPos);
  22318. var addPow = 0.2; //viewer.mainViewport.view.isFlying() ? 0 : 0.5 //0-0.5,正常原本是0. 数字越大近处加载越快。但会造成远处加载慢甚至因pointBudge限制不加载。 isFlying:漫游时需要尽量加载一下远处的点云
  22319. //addPow *= window.devicePixelRatio //devicePixelRatio高的手机需要优先加载最近的高级点云,减少远处的中高级点云。
  22320. var distance = Math.pow(dd, 0.5 + addPow); //Math.sqrt(dd); //提高距离权重,为了提高近处加载速度。 某些场景近处加载慢优化明显,如SS-t-cqCAL6rJ5i
  22321. //let attenuateDis = 10;//add
  22322. var radius = sphere.radius;
  22323. var projFactor = projFactor0 / distance;
  22324. var screenPixelRadius = radius * projFactor;
  22325. /* if(distance > attenuateDis){
  22326. screenPixelRadius -= (distance - attenuateDis) * Math.sqrt(radius) * projFactor0 * 0.002
  22327. } */
  22328. //screenPixelRadius 和 domHeight 成正比,所以手机横屏后screenPixelRadius会变小。这是正常的,因为vhov不变,相同物体高度在横屏后高度变小,所需要的密度不需要那么高了。但hfov横屏后扩大,所以可见的node范围变大,又增加了一些可见node;只是总体的可见node还是减少了。
  22329. //使用hfov和domWidth计算结果相同。
  22330. if (screenPixelRadius < pointcloud.minimumNodePixelSize / Math.pow(dd, addPow)) {
  22331. //理论上因手机像素小,更不容易堆叠铺满,minimumNodePixelSize应该除以window.deviceRatio 但会造成加载过多,而内存小
  22332. continue;
  22333. }
  22334. weight = screenPixelRadius;
  22335. if (!sphere.containsPoint(camObjPos)) {
  22336. //add 优先加载屏幕中央的点云(手机端缩小离远效果明显,不会那么稀疏)
  22337. var dir = new Vector3().subVectors(center, camObjPos).normalize();
  22338. var cos = 1 + dir.dot(camObjDir); //0-2
  22339. weight *= cos / 2; //Math.pow(cos,0.5) //幂越高,旁边的容易加载不到,出现缺块 如SS-t-7DUfWAUZ3V
  22340. }
  22341. if (distance - radius < 0) {
  22342. weight = Number.MAX_VALUE;
  22343. }
  22344. //如果能得到每个方向上的密度,也就是node数量,密度大的远处少加载,因为被遮挡了显示也没有意义,就好了。
  22345. } else {
  22346. // TODO ortho visibility
  22347. //let bb = child.getBoundingBox();
  22348. var _sphere = child.getBoundingSphere();
  22349. //let diagonal = bb.max.clone().sub(bb.min).length();
  22350. var reduce = 0; //0-0.5,正常原本是0.
  22351. if (_sphere.radius * /* Math.pow( */camera.zoom /* ,1-reduce) */ < pointcloud.minimumNodePixelSize) {
  22352. continue;
  22353. }
  22354. var _distance = _sphere.center.distanceToSquared(camObjPos); //先加载中间然后四周
  22355. weight = _sphere.radius / _distance;
  22356. /* let vec = new THREE.Vector3().subVectors(sphere.center, camObjPos)
  22357. let disOnCamDir = vec.dot(camObjDir)
  22358. let vecOnCamDir = camObjDir.clone().multiplyScalar(disOnCamDir)
  22359. let vecSide = new THREE.Vector3().subVectors(vec, vecOnCamDir) //在屏幕上从中心到该node的向量
  22360. let disSide = vecSide.length()
  22361. //weight = sphere.radius / disSide * camera.zoom - disOnCamDir * 2; //如果用除的,ortho的camera离远了的话dis的影响就小了
  22362. weight = sphere.radius / ( disSide * 0.1 + disOnCamDir * 14 )
  22363. */
  22364. //weight = diagonal;
  22365. }
  22366. priorityQueue.push({
  22367. pointcloud: element.pointcloud,
  22368. node: child,
  22369. parent: node,
  22370. weight: weight
  22371. }); //貌似好像二叉堆中子节点和父节点没什么关系,就只是为了方便排序层层遍历
  22372. }
  22373. //手机上像素点更小,所以远处感觉会更稀疏
  22374. },
  22375. _ret;
  22376. while (priorityQueue.size() > 0) {
  22377. _ret = _loop2();
  22378. if (_ret === 0) continue;
  22379. if (_ret === 1) break;
  22380. } // end priority queue loop
  22381. {
  22382. // update DEM 这是什么
  22383. var maxDEMLevel = 4;
  22384. var candidates = pointclouds.filter(p => p.generateDEM && p.dem instanceof Potree.DEM);
  22385. for (var _pointcloud6 of candidates) {
  22386. var updatingNodes = _pointcloud6.visibleNodes.filter(n => n.getLevel() <= maxDEMLevel);
  22387. _pointcloud6.dem.update(updatingNodes);
  22388. }
  22389. }
  22390. unloadedGeometry = unloadedGeometry.filter(e => !e.loadFailed); //过滤加载失败的,否则有失败的就无法发送加载完成
  22391. if (unloadedGeometry.length) {
  22392. //加载点云
  22393. var maxNodesLoading = Common.getBestCount('unloadedGeometry', viewer.lastFrameChanged ? 1 : 3, 6, 4, 15 /* , true */); //dur在iphoneX中静止有7,pc是2 //!lastFrameChanged静止时加速下载
  22394. //THREE.Math.clamp(Math.round(9 - dur), 1, 6 )
  22395. //console.log('unloadedGeometry', unloadedGeometry.length)
  22396. //主要在手机端有效果。不改之前在展示的点云较多时前进会卡。
  22397. for (var i = 0; i < Math.min(maxNodesLoading, unloadedGeometry.length); i++) {
  22398. unloadedGeometry[i].node.load(unloadedGeometry[i].pointcloud.pcoGeometry);
  22399. }
  22400. if (!Potree.pointsLoading) {
  22401. Potree.pointsLoading = true;
  22402. //console.log('startLoad')
  22403. viewer.dispatchEvent('startLoadPoints');
  22404. }
  22405. } else {
  22406. if (Potree.pointsLoading) {
  22407. Potree.pointsLoading = false;
  22408. //console.log('load done!')
  22409. setTimeout(() => {
  22410. Potree.pointsLoading || viewer.dispatchEvent('pointsLoaded');
  22411. }, document.hidden ? 3000 : 50); //hidden时可能好几秒才更新一次,所以这个并不准
  22412. }
  22413. }
  22414. Potree.unloadedGeometry = unloadedGeometry;
  22415. //add:
  22416. Potree.numVisiblePoints = numVisiblePoints;
  22417. return {
  22418. visibleNodes: visibleNodes,
  22419. numVisiblePoints: numVisiblePoints,
  22420. lowestSpacing: lowestSpacing
  22421. };
  22422. };
  22423. Potree.numVisiblePoints = 0;
  22424. /*
  22425. note:
  22426. 缓存中的点数 Potree.lru.numPoints 一般会 大于 每个点云显示点总数的numVisiblePoints
  22427. 当超出缓冲区最大点云数时,加载的点云节点会被dispose彻底消除;否则,隐藏的节点就会等待再次被使用显示
  22428. 由于加载按照由近及远、由大及小的顺序,要降低卡顿,就只需要降低Potree.pointBudget即可。但目前只设置了三个层次;另外提供maxLevel细节调节,能显示更均匀. 最好多一个调节pointBudge的滑动条
  22429. Potree.lru.numPoints
  22430. Potree.numVisiblePoints
  22431. viewer.scene.pointclouds[0].visibleNodes.length
  22432. */
  22433. {
  22434. //HQSplatRenderer
  22435. var oldInit = HQSplatRenderer.prototype.init;
  22436. HQSplatRenderer.prototype.init = function () {
  22437. oldInit();
  22438. viewer.addEventListener('resize', this.resize.bind(this));
  22439. };
  22440. HQSplatRenderer.prototype.resize = function (e) {
  22441. this.rtDepth.setSize(e.canvasWidth, e.canvasHeight);
  22442. this.rtAttribute.setSize(e.canvasWidth, e.canvasHeight);
  22443. };
  22444. HQSplatRenderer.prototype.clear = function () {
  22445. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  22446. this.init();
  22447. var {
  22448. renderer,
  22449. background
  22450. } = this.viewer;
  22451. if (background === "skybox") {
  22452. renderer.setClearColor(0x000000, 0);
  22453. } else if (background === 'gradient') {
  22454. renderer.setClearColor(0x000000, 0);
  22455. } else if (background === 'black') {
  22456. renderer.setClearColor(0x000000, 1);
  22457. } else if (background === 'white') {
  22458. renderer.setClearColor(0xFFFFFF, 1);
  22459. } else {
  22460. renderer.setClearColor(0x000000, 0);
  22461. }
  22462. params.target || renderer.clear();
  22463. this.clearTargets(params);
  22464. };
  22465. HQSplatRenderer.prototype.render = function () {
  22466. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  22467. this.init();
  22468. var viewer = this.viewer;
  22469. var camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  22470. var {
  22471. width,
  22472. height
  22473. } = params.width ? params : this.viewer.renderer.getSize(new Vector2());
  22474. viewer.renderer.setRenderTarget(params.target || null);
  22475. viewer.dispatchEvent({
  22476. type: "render.pass.begin",
  22477. viewer: viewer
  22478. });
  22479. //params.target || this.resize(width, height);
  22480. var visiblePointClouds = viewer.scene.pointclouds.filter(pc => pc.visible);
  22481. var originalMaterials = new Map();
  22482. for (var pointcloud of visiblePointClouds) {
  22483. originalMaterials.set(pointcloud, pointcloud.material);
  22484. if (!this.attributeMaterials.has(pointcloud)) {
  22485. var attributeMaterial = new ExtendPointCloudMaterial();
  22486. this.attributeMaterials.set(pointcloud, attributeMaterial);
  22487. }
  22488. if (!this.depthMaterials.has(pointcloud)) {
  22489. var depthMaterial = new ExtendPointCloudMaterial();
  22490. depthMaterial.setDefine("depth_pass", "#define hq_depth_pass");
  22491. depthMaterial.setDefine("use_edl", "#define use_edl");
  22492. this.depthMaterials.set(pointcloud, depthMaterial);
  22493. }
  22494. }
  22495. {
  22496. // DEPTH PASS
  22497. for (var _pointcloud7 of visiblePointClouds) {
  22498. var octreeSize = _pointcloud7.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  22499. var material = originalMaterials.get(_pointcloud7);
  22500. var _depthMaterial = this.depthMaterials.get(_pointcloud7);
  22501. _depthMaterial.size = material.size;
  22502. _depthMaterial.minSize = material.minSize;
  22503. _depthMaterial.maxSize = material.maxSize;
  22504. _depthMaterial.pointSizeType = material.pointSizeType;
  22505. _depthMaterial.visibleNodesTexture = material.visibleNodesTexture;
  22506. _depthMaterial.weighted = false;
  22507. _depthMaterial.screenWidth = width;
  22508. _depthMaterial.shape = PointShape.CIRCLE;
  22509. _depthMaterial.screenHeight = height;
  22510. _depthMaterial.uniforms.visibleNodes.value = material.visibleNodesTexture;
  22511. _depthMaterial.uniforms.octreeSize.value = octreeSize;
  22512. _depthMaterial.spacing = _pointcloud7.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  22513. _depthMaterial.classification = material.classification;
  22514. _depthMaterial.uniforms.classificationLUT.value.image.data = material.uniforms.classificationLUT.value.image.data;
  22515. _depthMaterial.classificationTexture.needsUpdate = true;
  22516. _depthMaterial.uniforms.uFilterReturnNumberRange.value = material.uniforms.uFilterReturnNumberRange.value;
  22517. _depthMaterial.uniforms.uFilterNumberOfReturnsRange.value = material.uniforms.uFilterNumberOfReturnsRange.value;
  22518. _depthMaterial.uniforms.uFilterGPSTimeClipRange.value = material.uniforms.uFilterGPSTimeClipRange.value;
  22519. _depthMaterial.uniforms.uFilterPointSourceIDClipRange.value = material.uniforms.uFilterPointSourceIDClipRange.value;
  22520. _depthMaterial.clipTask = material.clipTask;
  22521. _depthMaterial.clipMethod = material.clipMethod;
  22522. _depthMaterial.setClipBoxes(material.clipBoxes);
  22523. _depthMaterial.setClipPolygons(material.clipPolygons);
  22524. _pointcloud7.material = _depthMaterial;
  22525. }
  22526. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, params.rtEDL || this.rtDepth, {
  22527. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume)
  22528. });
  22529. }
  22530. {
  22531. // ATTRIBUTE PASS
  22532. for (var _pointcloud8 of visiblePointClouds) {
  22533. var _octreeSize = _pointcloud8.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  22534. var _material = originalMaterials.get(_pointcloud8);
  22535. var _attributeMaterial = this.attributeMaterials.get(_pointcloud8);
  22536. _attributeMaterial.size = _material.size;
  22537. _attributeMaterial.minSize = _material.minSize;
  22538. _attributeMaterial.maxSize = _material.maxSize;
  22539. _attributeMaterial.pointSizeType = _material.pointSizeType;
  22540. _attributeMaterial.activeAttributeName = _material.activeAttributeName;
  22541. _attributeMaterial.visibleNodesTexture = _material.visibleNodesTexture;
  22542. _attributeMaterial.weighted = true;
  22543. _attributeMaterial.screenWidth = width;
  22544. _attributeMaterial.screenHeight = height;
  22545. _attributeMaterial.shape = PointShape.CIRCLE;
  22546. _attributeMaterial.uniforms.visibleNodes.value = _material.visibleNodesTexture;
  22547. _attributeMaterial.uniforms.octreeSize.value = _octreeSize;
  22548. _attributeMaterial.spacing = _pointcloud8.pcoGeometry.spacing; // * Math.max(...pointcloud.scale.toArray());
  22549. _attributeMaterial.classification = _material.classification;
  22550. _attributeMaterial.uniforms.classificationLUT.value.image.data = _material.uniforms.classificationLUT.value.image.data;
  22551. _attributeMaterial.classificationTexture.needsUpdate = true;
  22552. _attributeMaterial.uniforms.uFilterReturnNumberRange.value = _material.uniforms.uFilterReturnNumberRange.value;
  22553. _attributeMaterial.uniforms.uFilterNumberOfReturnsRange.value = _material.uniforms.uFilterNumberOfReturnsRange.value;
  22554. _attributeMaterial.uniforms.uFilterGPSTimeClipRange.value = _material.uniforms.uFilterGPSTimeClipRange.value;
  22555. _attributeMaterial.uniforms.uFilterPointSourceIDClipRange.value = _material.uniforms.uFilterPointSourceIDClipRange.value;
  22556. _attributeMaterial.elevationGradientRepeat = _material.elevationGradientRepeat;
  22557. _attributeMaterial.elevationRange = _material.elevationRange;
  22558. _attributeMaterial.gradient = _material.gradient;
  22559. _attributeMaterial.matcap = _material.matcap;
  22560. _attributeMaterial.intensityRange = _material.intensityRange;
  22561. _attributeMaterial.intensityGamma = _material.intensityGamma;
  22562. _attributeMaterial.intensityContrast = _material.intensityContrast;
  22563. _attributeMaterial.intensityBrightness = _material.intensityBrightness;
  22564. _attributeMaterial.rgbGamma = _material.rgbGamma;
  22565. _attributeMaterial.rgbContrast = _material.rgbContrast;
  22566. _attributeMaterial.rgbBrightness = _material.rgbBrightness;
  22567. _attributeMaterial.weightRGB = _material.weightRGB;
  22568. _attributeMaterial.weightIntensity = _material.weightIntensity;
  22569. _attributeMaterial.weightElevation = _material.weightElevation;
  22570. _attributeMaterial.weightRGB = _material.weightRGB;
  22571. _attributeMaterial.weightClassification = _material.weightClassification;
  22572. _attributeMaterial.weightReturnNumber = _material.weightReturnNumber;
  22573. _attributeMaterial.weightSourceID = _material.weightSourceID;
  22574. _attributeMaterial.color = _material.color;
  22575. _attributeMaterial.clipTask = _material.clipTask;
  22576. _attributeMaterial.clipMethod = _material.clipMethod;
  22577. _attributeMaterial.setClipBoxes(_material.clipBoxes);
  22578. _attributeMaterial.setClipPolygons(_material.clipPolygons);
  22579. _pointcloud8.material = _attributeMaterial;
  22580. }
  22581. var gl = this.gl;
  22582. //viewer.renderer.setRenderTarget(null);
  22583. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, this.rtAttribute, {
  22584. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume),
  22585. //material: this.attributeMaterial,
  22586. blendFunc: [gl.SRC_ALPHA, gl.ONE],
  22587. //depthTest: false,
  22588. depthWrite: false
  22589. });
  22590. }
  22591. for (var [_pointcloud9, _material2] of originalMaterials) {
  22592. _pointcloud9.material = _material2;
  22593. }
  22594. if (viewer.background === "skybox") {
  22595. viewer.renderer.setClearColor(0x000000, 0);
  22596. viewer.renderer.clear();
  22597. viewer.skybox.camera.rotation.copy(viewer.scene.cameraP.rotation);
  22598. viewer.skybox.camera.fov = viewer.scene.cameraP.fov;
  22599. viewer.skybox.camera.aspect = viewer.scene.cameraP.aspect;
  22600. viewer.skybox.parent.rotation.x = 0;
  22601. viewer.skybox.parent.updateMatrixWorld();
  22602. viewer.skybox.camera.updateProjectionMatrix();
  22603. viewer.renderer.render(viewer.skybox.scene, viewer.skybox.camera);
  22604. } else if (viewer.background === 'gradient') {
  22605. viewer.renderer.setClearColor(0x000000, 0);
  22606. viewer.renderer.clear();
  22607. viewer.renderer.render(viewer.scene.sceneBG, viewer.scene.cameraBG);
  22608. } else if (viewer.background === 'black') {
  22609. viewer.renderer.setClearColor(0x000000, 1);
  22610. viewer.renderer.clear();
  22611. } else if (viewer.background === 'white') {
  22612. viewer.renderer.setClearColor(0xFFFFFF, 1);
  22613. viewer.renderer.clear();
  22614. } else {
  22615. viewer.renderer.setClearColor(0x000000, 0);
  22616. viewer.renderer.clear();
  22617. }
  22618. {
  22619. // NORMALIZATION PASS
  22620. var normalizationMaterial = this.useEDL ? this.normalizationEDLMaterial : this.normalizationMaterial;
  22621. if (this.useEDL) {
  22622. normalizationMaterial.uniforms.edlStrength.value = viewer.edlStrength;
  22623. normalizationMaterial.uniforms.radius.value = viewer.edlRadius;
  22624. normalizationMaterial.uniforms.screenWidth.value = width;
  22625. normalizationMaterial.uniforms.screenHeight.value = height;
  22626. normalizationMaterial.uniforms.uEDLMap.value = (params.rtEDL || this.rtDepth).texture;
  22627. }
  22628. normalizationMaterial.uniforms.uWeightMap.value = this.rtAttribute.texture;
  22629. normalizationMaterial.uniforms.uDepthMap.value = this.rtAttribute.depthTexture;
  22630. Utils.screenPass.render(viewer.renderer, normalizationMaterial);
  22631. }
  22632. viewer.renderer.render(viewer.scene.scene, camera);
  22633. viewer.dispatchEvent({
  22634. type: "render.pass.scene",
  22635. viewer: viewer
  22636. });
  22637. viewer.renderer.render(viewer.scene.sceneOverlay, camera); // add 透明贴图层
  22638. viewer.renderer.clearDepth();
  22639. viewer.transformationTool.update();
  22640. if (!params.target) {
  22641. //测量线
  22642. viewer.dispatchEvent({
  22643. type: "render.pass.perspective_overlay",
  22644. viewer: viewer,
  22645. camera
  22646. });
  22647. viewer.renderer.render(viewer.overlay, camera); //从 viewer.renderDefault搬过来,为了reticule不遮住测量线
  22648. }
  22649. viewer.renderer.render(viewer.controls.sceneControls, camera);
  22650. viewer.renderer.render(viewer.clippingTool.sceneVolume, camera);
  22651. viewer.renderer.render(viewer.transformationTool.scene, camera);
  22652. viewer.renderer.setViewport(width - viewer.navigationCube.width, height - viewer.navigationCube.width, viewer.navigationCube.width, viewer.navigationCube.width);
  22653. viewer.renderer.render(viewer.navigationCube, viewer.navigationCube.camera);
  22654. viewer.renderer.setViewport(0, 0, width, height);
  22655. viewer.dispatchEvent({
  22656. type: "render.pass.end",
  22657. viewer: viewer
  22658. });
  22659. viewer.renderer.setRenderTarget(null);
  22660. };
  22661. }
  22662. //PointCloudOctreeGeometry.js
  22663. PointCloudOctreeGeometryNode.prototype.loadHierachyThenPoints = function (pointcloud) {
  22664. var node = this;
  22665. // load hierarchy
  22666. var callback = function callback(node, hbuffer) {
  22667. var tStart = performance.now();
  22668. var view = new DataView(hbuffer);
  22669. var stack = [];
  22670. var children = view.getUint8(0);
  22671. var numPoints = view.getUint32(1, true);
  22672. node.numPoints = numPoints;
  22673. stack.push({
  22674. children: children,
  22675. numPoints: numPoints,
  22676. name: node.name
  22677. });
  22678. var decoded = [];
  22679. var offset = 5;
  22680. while (stack.length > 0) {
  22681. var snode = stack.shift();
  22682. var mask = 1;
  22683. for (var i = 0; i < 8; i++) {
  22684. if ((snode.children & mask) !== 0) {
  22685. var childName = snode.name + i;
  22686. var childChildren = view.getUint8(offset);
  22687. var childNumPoints = view.getUint32(offset + 1, true);
  22688. stack.push({
  22689. children: childChildren,
  22690. numPoints: childNumPoints,
  22691. name: childName
  22692. });
  22693. decoded.push({
  22694. children: childChildren,
  22695. numPoints: childNumPoints,
  22696. name: childName
  22697. });
  22698. offset += 5;
  22699. }
  22700. mask = mask * 2;
  22701. }
  22702. if (offset === hbuffer.byteLength) {
  22703. break;
  22704. }
  22705. }
  22706. // console.log(decoded);
  22707. var nodes = {};
  22708. nodes[node.name] = node;
  22709. var pco = node.pcoGeometry;
  22710. var maxLevel_ = 0;
  22711. for (var _i3 = 0; _i3 < decoded.length; _i3++) {
  22712. var name = decoded[_i3].name;
  22713. var decodedNumPoints = decoded[_i3].numPoints;
  22714. var index = parseInt(name.charAt(name.length - 1));
  22715. var parentName = name.substring(0, name.length - 1);
  22716. var parentNode = nodes[parentName];
  22717. var level = name.length - 1;
  22718. maxLevel_ = Math.max(maxLevel_, level); //add
  22719. var boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  22720. var currentNode = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  22721. currentNode.level = level;
  22722. currentNode.numPoints = decodedNumPoints;
  22723. currentNode.hasChildren = decoded[_i3].children > 0;
  22724. currentNode.spacing = pco.spacing / Math.pow(2, level);
  22725. parentNode.addChild(currentNode);
  22726. nodes[name] = currentNode;
  22727. }
  22728. pco.dispatchEvent({
  22729. type: 'updateNodeMaxLevel',
  22730. level: maxLevel_
  22731. }); //add
  22732. var duration = performance.now() - tStart;
  22733. if (duration > 5) {
  22734. /* let msg = `duration: ${duration}ms, numNodes: ${decoded.length}`;
  22735. console.log(msg); */
  22736. }
  22737. node.loadPoints();
  22738. };
  22739. if (node.level % node.pcoGeometry.hierarchyStepSize === 0) {
  22740. // let hurl = node.pcoGeometry.octreeDir + "/../hierarchy/" + node.name + ".hrc";
  22741. var hurl = node.pcoGeometry.octreeDir + '/' + node.getHierarchyPath() + '/' + node.name + '.hrc';
  22742. hurl += '?m=' + node.pcoGeometry.timeStamp; //add
  22743. var xhr = XHRFactory.createXMLHttpRequest();
  22744. xhr.open('GET', hurl, true);
  22745. xhr.responseType = 'arraybuffer';
  22746. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  22747. xhr.onreadystatechange = () => {
  22748. if (xhr.readyState === 4) {
  22749. if (xhr.status === 200 || xhr.status === 0) {
  22750. var hbuffer = xhr.response;
  22751. callback(node, hbuffer);
  22752. } else {
  22753. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + hurl);
  22754. Potree.numNodesLoading--;
  22755. }
  22756. }
  22757. };
  22758. try {
  22759. xhr.send(null);
  22760. } catch (e) {
  22761. console.log('fehler beim laden der punktwolke: ' + e);
  22762. }
  22763. }
  22764. };
  22765. PointCloudOctreeGeometryNode.prototype.loadPoints = function () {
  22766. var name = this.name;
  22767. this.pcoGeometry.loader.load(this, () => {
  22768. //callback
  22769. viewer.dispatchEvent('pointcloud_changed');
  22770. //console.log('loadPoints success ', name)
  22771. });
  22772. };
  22773. //加载点云成功->准备渲染画面->更新点云可见性updateVisibility->请求加载新的点云
  22774. PointCloudOctreeGeometryNode.prototype.traverse = function (t, e) {
  22775. //add from navvis 25.js
  22776. void 0 === e && (e = !0);
  22777. for (var n, i = e ? [this] : []; void 0 !== (n = i.pop());) {
  22778. t(n);
  22779. for (var o = 0, r = n.children; o < r.length; o++) {
  22780. var a = r[o];
  22781. null !== a && i.push(a);
  22782. }
  22783. }
  22784. };
  22785. Object.assign(PointCloudOctreeGeometry.prototype, EventDispatcher.prototype);
  22786. LRU.prototype.freeMemory = function () {
  22787. if (this.elements <= 1) {
  22788. return;
  22789. }
  22790. var memoryRatio = browser.isMobile() ? 2 : 5;
  22791. //改成navvis的,使用pointBudget,否则四屏点云闪烁。 (似乎要比updateVisiblede的node时限制要宽些,作为缓存继续存着。否则会闪烁)
  22792. var max = MathUtils.clamp(viewer.viewports.length * memoryRatio * Potree.pointBudget, 0, 40e6);
  22793. for (; this.numPoints > max;) {
  22794. var node = this.getLRUItem();
  22795. node && this.disposeDescendants(node);
  22796. }
  22797. };
  22798. VolumeTool.prototype.update = function () {};
  22799. VolumeTool.prototype.startInsertion = function () {
  22800. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  22801. var volume;
  22802. if (args.type) {
  22803. volume = new args.type();
  22804. } else {
  22805. volume = new Potree.BoxVolume(Object.assign(args, {
  22806. clip: true
  22807. }));
  22808. }
  22809. volume.highlight = true;
  22810. volume.name = args.name || 'Volume-' + args.clipTask;
  22811. volume.isNew = true;
  22812. viewer.transformObject(null); //先清空
  22813. //console.log('startInsertion',volume.uuid)
  22814. var oldVisiBoxes;
  22815. if (args.clipTask == Potree.ClipTask.SHOW_INSIDE) {
  22816. //如果是显示类型,需要将所有同类型的解除效果,否则看不到效果。 (或者可以在添加非第一个时去除highlight效果,会更自然,但看不清全貌)
  22817. oldVisiBoxes = viewer.scene.volumes.filter(v => v.clipTask == Potree.ClipTask.SHOW_INSIDE && !v.highlight);
  22818. oldVisiBoxes.forEach(box => box.highlight = true);
  22819. }
  22820. var updatePose = () => {
  22821. //保证在视野中的大小一致:
  22822. var camera = this.viewer.scene.getActiveCamera();
  22823. var w = math.getScaleForConstantSize({
  22824. width2d: 300,
  22825. camera,
  22826. position: volume.getWorldPosition(new Vector3()),
  22827. resolution: viewer.mainViewport.resolution //2
  22828. });
  22829. /* let wp = volume.getWorldPosition(new THREE.Vector3()).applyMatrix4(camera.matrixWorldInverse);
  22830. // let pp = new THREE.Vector4(wp.x, wp.y, wp.z).applyMatrix4(camera.projectionMatrix);
  22831. let w = Math.abs((wp.z / 3));*/
  22832. if (!isNaN(w)) volume.scale.set(w, w, w);
  22833. {
  22834. //使水平朝向与camera一致
  22835. var direction = viewer.mainViewport.view.direction.setZ(0);
  22836. volume.quaternion.copy(math.getQuaByAim(direction));
  22837. }
  22838. };
  22839. this.dispatchEvent({
  22840. type: 'start_inserting_volume',
  22841. volume: volume
  22842. });
  22843. updatePose();
  22844. this.viewer.scene.addVolume(volume);
  22845. this.scene.add(volume);
  22846. var drag = e => {
  22847. if (e.hoverViewport.name == 'mapViewport') return;
  22848. var I = Utils.getMousePointCloudIntersection(viewer.mainViewport, viewer.inputHandler.mouse, viewer.inputHandler.pointer, this.viewer.scene.getActiveCamera(), this.viewer, this.viewer.scene.pointclouds, {
  22849. pickClipped: args.clipTask == Potree.ClipTask.SHOW_OUTSIDE
  22850. } //无视clip状态
  22851. );
  22852. var worldPos = I && I.location;
  22853. if (!worldPos) {
  22854. return;
  22855. }
  22856. volume.position.copy(worldPos);
  22857. updatePose();
  22858. };
  22859. var cancel = () => {
  22860. end('remove');
  22861. };
  22862. var end = e => {
  22863. if (e.button == MOUSE.RIGHT && e.pressDistance <= Potree.config.clickMaxDragDis) {
  22864. //remove
  22865. e = 'remove';
  22866. }
  22867. //console.log('end',volume.uuid, e)
  22868. if (e != 'remove' && (!e.isAtDomElement || e.pressDistance > Potree.config.clickMaxDragDis)) return continueDrag();
  22869. volume.removeEventListener('drag', drag);
  22870. volume.removeEventListener('drop', end);
  22871. this.viewer.removeEventListener('cancel_insertions', cancel);
  22872. volume.isNew = false;
  22873. viewer.removeEventListener('camera_changed', updatePose);
  22874. if (e == 'remove') {
  22875. viewer.scene.removeVolume(volume); //删除没完成的
  22876. } else {
  22877. viewer.transformObject(volume);
  22878. volume.highlight = false;
  22879. }
  22880. volume.dispatchEvent({
  22881. type: 'createFinish',
  22882. success: e != 'remove'
  22883. });
  22884. oldVisiBoxes && oldVisiBoxes.forEach(box => box.highlight = false);
  22885. };
  22886. var continueDrag = () => {
  22887. //console.log('continueDrag',volume.uuid )
  22888. var timer = setTimeout(() => {
  22889. //等 drag=null之后 //右键拖拽结束后需要重新得到drag
  22890. if (volume.parent && volume.isNew) {
  22891. viewer.inputHandler.startDragging(volume, {
  22892. notPressMouse: true
  22893. }
  22894. /* {endDragFun: e.drag.endDragFun, notPressMouse:e.drag.notPressMouse, dragViewport:e.drag.dragViewport} */);
  22895. }
  22896. }, 1);
  22897. return timer;
  22898. };
  22899. volume.addEventListener('drag', drag);
  22900. volume.addEventListener('drop', end);
  22901. this.viewer.addEventListener('cancel_insertions', cancel);
  22902. viewer.addEventListener('camera_changed', updatePose);
  22903. this.viewer.inputHandler.startDragging(volume, {
  22904. notPressMouse: true
  22905. });
  22906. return volume;
  22907. };
  22908. LineGeometry.prototype.setPositions = function (array) {
  22909. //xzw改成类似LineSegments的多段线 (第二个点和第三个点之间是没有线段的, 所以不用在意线段顺序)
  22910. var points = new Float32Array(array);
  22911. LineSegmentsGeometry.prototype.setPositions.call(this, points);
  22912. return this;
  22913. };
  22914. Object.assign(ExtendView.prototype, EventDispatcher.prototype);
  22915. Object.assign(ExtendScene.prototype, EventDispatcher.prototype);
  22916. function start(dom, mapDom, number) {
  22917. //t-Zvd3w0m
  22918. /* {
  22919. let obj = JSON.parse(localStorage.getItem('setting'))
  22920. for(let i in obj){
  22921. console.log(i + ': ' + obj[i])
  22922. }
  22923. }
  22924. */
  22925. Potree.settings.number = number || 't-o5YMR13'; // 't-iksBApb'// 写在viewer前
  22926. if (!Potree.settings.isOfficial) {
  22927. if ( /* Potree.settings.isTest && */browser.isMobile()) {
  22928. changeLog();
  22929. }
  22930. }
  22931. if (browser.urlHasValue('google')) Potree.settings.mapCompany = 'google';
  22932. if (browser.urlHasValue('timing')) Potree.measureTimings = 1;
  22933. var viewer = new Potree.Viewer(dom, mapDom);
  22934. /* viewer.addEventListener('allLoaded',()=>{
  22935. const baseGeometry = new THREE.BufferGeometry();
  22936. baseGeometry.setIndex([0, 1, 2, 0, 2, 3]);
  22937. const positionsArray = new Float32Array(4 * 3);
  22938. const positions = new THREE.BufferAttribute(positionsArray, 3);
  22939. baseGeometry.setAttribute('position', positions);
  22940. positions.setXYZ(0, -1.0, -1.0, 0.0);
  22941. positions.setXYZ(1, -1.0, 1.0, 0.0);
  22942. positions.setXYZ(2, 1.0, 1.0, 0.0);
  22943. positions.setXYZ(3, 1.0, -1.0, 0.0);
  22944. positions.needsUpdate = true;
  22945. const geometry = new THREE.InstancedBufferGeometry().copy(baseGeometry);
  22946. let maxSplatCount = 8
  22947. // Splat index buffer
  22948. const splatIndexArray = new Uint32Array(maxSplatCount);
  22949. const splatIndexes = new THREE.InstancedBufferAttribute(splatIndexArray, 1, false);
  22950. splatIndexes.setUsage(THREE.DynamicDrawUsage);
  22951. geometry.setAttribute('splatIndex', splatIndexes);
  22952. const splatPosArray = new Float32Array(maxSplatCount*3);
  22953. const splatPoses = new THREE.InstancedBufferAttribute(splatPosArray, 3, false);
  22954. splatPoses.setUsage(THREE.DynamicDrawUsage);
  22955. geometry.setAttribute('splatCenter', splatPoses);
  22956. splatPosArray.set([0,0,0,
  22957. 1,1,1,
  22958. 2,2,2,
  22959. 3,3,3,
  22960. 4,4,4,
  22961. 5,5,5,
  22962. 6,6,6,
  22963. 7,7,7])
  22964. let vertexShaderSource = `
  22965. precision highp float;
  22966. #include <common>
  22967. attribute vec3 splatCenter;
  22968. attribute float splatIndex;
  22969. varying vec2 vPosition;
  22970. const float sqrt8 = sqrt(8.0);
  22971. const float minAlpha = 1.0 / 255.0;
  22972. void main () {
  22973. mat4 transformModelViewMatrix = modelViewMatrix;
  22974. vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);
  22975. vec4 clipCenter = projectionMatrix * viewCenter;
  22976. float clip = 1.2 * clipCenter.w;
  22977. if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {
  22978. gl_Position = vec4(0.0, 0.0, 2.0, 1.0);
  22979. return;
  22980. }
  22981. vPosition = position.xy;
  22982. vec3 ndcCenter = clipCenter.xyz / clipCenter.w;
  22983. float eigenValue1 = 0.2;
  22984. float eigenValue2 = 0.2;
  22985. //vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));
  22986. vec2 eigenVector1 = normalize(vec2(0.5, 0.5));
  22987. vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);
  22988. vec2 basisVector1 = eigenVector1 * min(sqrt8 * sqrt(eigenValue1), 2048.0);
  22989. vec2 basisVector2 = eigenVector2 * min(sqrt8 * sqrt(eigenValue2), 2048.0);
  22990. vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) / viewport * 2.0 ;
  22991. gl_Position = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z , 1.0);
  22992. vPosition *= sqrt8;
  22993. }`;
  22994. //面片模拟椭球,总是有厚度
  22995. const fragmentShaderSource = `
  22996. precision highp float;
  22997. #include <common>
  22998. uniform vec3 color;
  22999. varying vec2 vPosition;
  23000. void main () {
  23001. float A = dot(vPosition, vPosition);
  23002. if (A > 8.0) discard; //position的范围半径为1。指一个rectangle面中的范围。椭圆外的完全透明
  23003. float opacity = exp(-0.5 * A) * vColor.a; //周围的透明度降低
  23004. gl_FragColor = vec4(color.rgb, opacity);
  23005. }`;
  23006. const uniforms = {
  23007. 'viewport': {
  23008. 'type': 'v2',
  23009. 'value': new THREE.Vector2()
  23010. } ,
  23011. color:{
  23012. 'type': 'v3',
  23013. 'value': new THREE.Color()
  23014. }
  23015. };
  23016. const material = new THREE.ShaderMaterial({
  23017. uniforms: uniforms,
  23018. vertexShader: vertexShaderSource,
  23019. fragmentShader: fragmentShaderSource,
  23020. transparent: true,
  23021. alphaTest: 1.0,
  23022. blending: THREE.NormalBlending,
  23023. depthTest: true,
  23024. depthWrite: false,
  23025. side: THREE.DoubleSide
  23026. });
  23027. window.splatMesh = new THREE.Mesh(geometry, material)
  23028. viewer.scene.scene.add(window.splatMesh)
  23029. viewer.addEventListener('resize',(e)=>{
  23030. if(e.viewport.name == 'mainViewport'){
  23031. uniforms.viewport.copy(e.viewport.resolution)
  23032. }
  23033. })
  23034. window.setSplatIndexes = (globalIndexes)=>{
  23035. geometry.attributes.splatIndex.set(globalIndexes);
  23036. geometry.attributes.splatIndex.needsUpdate = true;
  23037. geometry.instanceCount = globalIndexes.length
  23038. }
  23039. })
  23040. */
  23041. var Alignment = viewer.modules.Alignment;
  23042. viewer.setEDLEnabled(false);
  23043. viewer.setFOV(Potree.config.view.fov);
  23044. //viewer.loadSettingsFromURL();
  23045. Potree.settings.cameraFar = Potree.config.view.far;
  23046. if (!Potree.settings.isOfficial) {
  23047. viewer.loadGUI(() => {
  23048. viewer.setLanguage('en');
  23049. //$("#menu_appearance").next().show();
  23050. $("#menu_tools").next().show();
  23051. $("#menu_scene").next().show();
  23052. $("#siteModel").show();
  23053. //$("#alignment").show();
  23054. viewer.toggleSidebar();
  23055. });
  23056. Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  23057. Potree.settings.rotAroundPoint = false;
  23058. }
  23059. Potree.loadDatasetsCallback = function (data, ifReload) {
  23060. if (!data || data.length == 0) return console.error('getDataSet加载的数据为空');
  23061. Potree.datasetData = data;
  23062. viewer.transform = null;
  23063. var datasetLength = data.length;
  23064. var pointcloudLoaded = 0;
  23065. var panosLoaded = 0;
  23066. var pointcloudLoadDone = function pointcloudLoadDone() {//点云cloud.js加载完毕后
  23067. };
  23068. var panosLoadDone = function panosLoadDone() {
  23069. viewer.images360.loadDone();
  23070. viewer.scene.add360Images(viewer.images360);
  23071. viewer.mapViewer.addListener(viewer.images360);
  23072. viewer.updateModelBound(); //需等pano加载完
  23073. var {
  23074. boundSize,
  23075. center
  23076. } = viewer.bound;
  23077. if (!Potree.settings.isOfficial) {
  23078. Potree.loadMapEntity('all'); //加载floorplan
  23079. }
  23080. if (!ifReload) {
  23081. viewer.dispatchEvent({
  23082. type: 'loadPointCloudDone'
  23083. });
  23084. if (!Potree.settings.UserPointDensity) {
  23085. Potree.settings.UserPointDensity = 'high'; //'middle'
  23086. }
  23087. Potree.Log('loadPointCloudDone 点云加载完毕', {
  23088. font: [null, 10]
  23089. });
  23090. }
  23091. {
  23092. //初始位置
  23093. var panoId = browser.urlHasValue('pano', true);
  23094. if (panoId !== '') {
  23095. var pos;
  23096. var pano = viewer.images360.panos.find(e => e.id == panoId);
  23097. if (pano) {
  23098. viewer.images360.focusPano({
  23099. pano,
  23100. duration: 0,
  23101. callback: () => {/* Potree.settings.displayMode = 'showPanos' */}
  23102. });
  23103. }
  23104. } else {
  23105. //考虑到多数据集距离很远,或者像隧道那种场景,要使视野范围内一定能看到点云,最好初始点设置在漫游点上
  23106. var {
  23107. boundSize: _boundSize,
  23108. center: _center
  23109. } = viewer.bound;
  23110. var _pano = viewer.images360.findNearestPano(_center);
  23111. if (_pano) {
  23112. viewer.images360.flyToPano({
  23113. pano: _pano,
  23114. duration: 0,
  23115. target: viewer.images360.bound.center.setZ(_pano.position.z) //平视中心区域(但也不能保证这个方向一定能看到点云密集区,如果在边缘的话)
  23116. });
  23117. } else {
  23118. // 无漫游点 避免加载时看不到点云 SG-t-DXmdymgZ2sX SG-t-rVB03a5GXr8
  23119. //SG-t-XPf1k9pv3Zg 总有极端的场景,如这是倾斜的桥 - -, 只能调整为看到全局了
  23120. viewer.mainViewport.view.pitch = -0.7; //相对俯视
  23121. var bound = viewer.bound.boundingBox.clone();
  23122. viewer.focusOnObject({
  23123. boundingBox: bound
  23124. }, 'boundingBox', 0, {
  23125. dontChangeCamDir: true
  23126. });
  23127. if (viewer.bound.boundSize.length() > 20) {
  23128. //否则有可能超出far范围
  23129. viewer.mainViewport.camera.far = 10000;
  23130. viewer.mainViewport.camera.updateProjectionMatrix();
  23131. viewer.fixCamFar = true; //不允许修改camera.far
  23132. //等有点云加载出来后,再去focus其中一个,使camera.far不超过最大值
  23133. var count_ = 0;
  23134. var done = () => {
  23135. viewer.fixCamFar = false;
  23136. viewer.mainViewport.camera.far = Potree.settings.cameraFar;
  23137. viewer.mainViewport.camera.updateProjectionMatrix();
  23138. viewer.removeEventListener('pageVisible', focusPoint);
  23139. clearTimeout(timer);
  23140. };
  23141. var timer;
  23142. var focusPoint = e => {
  23143. //拉近到某个点
  23144. if (e && e.v === false) return;
  23145. viewer.removeEventListener('pageVisible', focusPoint);
  23146. var pointcloud = viewer.scene.pointclouds.find(e => e.root.geometryNode);
  23147. console.log('初始加载focus点云', e, pointcloud);
  23148. if (!pointcloud) {
  23149. if (count_ < 10) {
  23150. //可能没加载到,可能被隐藏
  23151. if (document.hidden) {
  23152. //等回到页面再focus
  23153. console.log('focus hidden');
  23154. return viewer.addEventListener('pageVisible', focusPoint);
  23155. }
  23156. count_++; //如果在别的
  23157. timer = setTimeout(focusPoint, 200);
  23158. } else {
  23159. //放弃
  23160. console.log('初始加载focus点云 放弃');
  23161. done();
  23162. }
  23163. return console.warn('no!!!!!!!!!!!!!!');
  23164. }
  23165. viewer.flyToDataset({
  23166. focusOnPoint: true,
  23167. pointcloud,
  23168. duration: 0
  23169. });
  23170. console.warn('ok!!!!!!!!!!!!!!!!');
  23171. done();
  23172. };
  23173. var focus = () => {
  23174. timer = setTimeout(focusPoint, 300);
  23175. };
  23176. viewer.addEventListener('setPose', () => {
  23177. //设置了初始画面
  23178. viewer.removeEventListener('pointcloud_changed', focus);
  23179. done();
  23180. });
  23181. viewer.addEventListener('pointcloud_changed', focus, {
  23182. once: true
  23183. }); //加载了点之后
  23184. }
  23185. }
  23186. }
  23187. }
  23188. viewer.addVideo(); //addFire()
  23189. viewer.scene.pointclouds.some(e => !e.hasDepthTex) && (Potree.config.shelterMargin *= 3); //没有深度图的话在全景模式测量有偏差
  23190. console.log('allLoaded');
  23191. viewer.addTube({
  23192. 't-8KbK1JjubE': [{
  23193. //地上管子 黄色
  23194. path: [{
  23195. "x": -109.83,
  23196. "y": -68.33,
  23197. "z": -7.52
  23198. }, {
  23199. "x": -95.17,
  23200. "y": -59.3,
  23201. "z": -7.38
  23202. }, {
  23203. "x": -38.75,
  23204. "y": -24.01,
  23205. "z": -6.01
  23206. }, {
  23207. "x": 0.5,
  23208. "y": 0.19,
  23209. "z": -3.89
  23210. }, {
  23211. "x": 39.29,
  23212. "y": 24.41,
  23213. "z": -1.31
  23214. }, {
  23215. "x": 43.58,
  23216. "y": 27.7,
  23217. "z": -0.97
  23218. }, {
  23219. "x": 40.22,
  23220. "y": 35.37,
  23221. "z": -0.67
  23222. } // 拐弯向右
  23223. , {
  23224. "x": 39.18,
  23225. "y": 36.71,
  23226. "z": 0.35
  23227. }, {
  23228. "x": 38.69,
  23229. "y": 36.04,
  23230. "z": 18.04
  23231. } // 拐弯向上 }
  23232. ],
  23233. color: '#b86',
  23234. radius: 0.08,
  23235. height: 0.13
  23236. }, {
  23237. //地下管子 藍色
  23238. path: [{
  23239. "x": -108.24,
  23240. "y": -70.61,
  23241. "z": -7.52
  23242. }, {
  23243. "x": -57.8,
  23244. "y": -39.31,
  23245. "z": -6.72
  23246. }, {
  23247. "x": -18.8,
  23248. "y": -15.35,
  23249. "z": -5.01
  23250. }, {
  23251. "x": 55.87,
  23252. "y": 31.67,
  23253. "z": -0.04
  23254. }, {
  23255. "x": 110.53,
  23256. "y": 66.48,
  23257. "z": 5.14
  23258. }],
  23259. color: '#48a',
  23260. radius: 0.08,
  23261. height: -0.5
  23262. }]
  23263. /* 'SG-t-h0I7LnfGFwj':[ //港华M层
  23264. {
  23265. path:[[20.295,-10.269,-1.152],[19.996,-10.252,-1.153],[19.98,-10.253,-1.156],[19.967,-10.252,-1.165],[19.957,-10.251,-1.179],[19.953,-10.251,-1.225],[19.961,-10.242,-1.267],[19.968,-10.223,-1.296],[19.967,-10.193,-1.304],[20.007,-10.092,-1.321],[19.997,-10.063,-1.309],[19.979,-10.039,-1.284],[19.989,-10.028,-1.256],[19.993,-10.024,-1.23],[19.972,-10.026,-1.181],[20.009,-10.045,-1.026],[20.025,-10.048,-1.013],[20.045,-10.05,-1.006],[20.056,-10.052,-1.001],[20.413,-10.073,-1.016],[20.461,-10.075,-1.02],[20.498,-10.053,-1.018],[20.525,-10.022,-1.025],[20.538,-9.983,-1.029],[20.554,-9.536,-1.111],[20.554,-9.487,-1.118],[20.545,-9.445,-1.129],[20.521,-9.418,-1.14],[20.478,-9.396,-1.156],[20.427,-9.379,-1.182],[20.367,-9.369,-1.198],[19.971,-9.304,-1.221],[19.749,-9.197,-1.345]]
  23266. ,color:'#8c99aa', radius:0.025, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房'
  23267. },
  23268. {
  23269. path:[[19.708,-2.921,-1.145],[19.721,-2.924,-1.119],[20.704,-2.881,-1.134],[20.736,-2.87,-1.138],[20.76,-2.852,-1.147],[20.773,-2.828,-1.148],[20.777,-2.809,-1.148],[20.794,-2.493,-1.167],[20.793,-2.461,-1.169],[20.776,-2.436,-1.174],[20.742,-2.425,-1.198],[20.14,-2.459,-1.309],[20.123,-2.457,-1.309],[20.108,-2.451,-1.31],[20.101,-2.439,-1.311],[20.095,-2.42,-1.313],[20.094,-2.399,-1.311],[20.092,-1.966,-1.295],[20.093,-1.945,-1.286],[20.094,-1.931,-1.269],[20.093,-1.929,-1.251],[20.09,-1.921,-1.197],[20.096,-1.914,-1.181],[20.107,-1.909,-1.174],[20.176,-1.893,-1.141],[20.699,-1.848,-1.076],[20.759,-1.824,-1.068],[20.81,-1.754,-1.076],[20.837,-1.71,-1.086],[20.85,-1.634,-1.1],[20.815,-1.01,-1.104],[20.824,-0.979,-1.115],[20.83,-0.957,-1.124],[20.843,-0.936,-1.132],[20.871,-0.925,-1.139],[21.065,-0.936,-1.166],[21.096,-0.935,-1.167],[21.115,-0.919,-1.167],[21.129,-0.887,-1.165],[21.136,-0.783,-1.167],[21.136,0.555,-1.201],[21.128,0.599,-1.201],[21.1,0.627,-1.199],[21.058,0.639,-1.198],[20.832,0.616,-1.179],[20.782,0.62,-1.186],[20.748,0.637,-1.19],[20.728,0.698,-1.21],[20.731,1.311,-1.233],[20.68,2.081,-1.292],[20.654,2.157,-1.307],[20.576,2.215,-1.314],[20.484,2.274,-1.321],[20.035,2.354,-1.353],[20.013,2.367,-1.363],[20.008,2.39,-1.371],[19.989,3.124,-1.384],[19.993,3.175,-1.39],[19.995,3.208,-1.393],[19.995,3.233,-1.374],[20.002,3.246,-1.324],[20.006,3.248,-1.266],[20.027,3.243,-1.245],[20.063,3.241,-1.239],[20.62,3.229,-1.226],[20.645,3.235,-1.204],[20.658,3.251,-1.191],[20.667,3.278,-1.184],[20.675,3.312,-1.193],[20.716,3.71,-1.24],[20.722,3.767,-1.251],[20.704,3.823,-1.268],[20.652,3.864,-1.279],[20.026,3.901,-1.368],[19.999,3.919,-1.37],[19.982,3.95,-1.361],[19.933,4.69,-1.285],[19.972,4.812,-1.332],[19.978,4.817,-1.233],[19.992,4.814,-1.203],[20.047,4.81,-1.196],[20.738,4.794,-1.196]]
  23270. ,color:'#8c99aa', radius:0.025, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房'
  23271. },
  23272. {
  23273. path:[[19.685,-2.896,-1.115],[19.699,-2.93,-1.274],[19.701,-2.936,-1.295],[19.707,-2.94,-1.316],[19.712,-2.951,-1.34],[19.714,-2.965,-1.353],[19.716,-2.986,-1.359],[19.7,-3.595,-1.309],[19.703,-3.619,-1.303],[19.704,-3.628,-1.274],[19.719,-3.632,-1.256],[20.063,-3.633,-1.275],[20.089,-3.637,-1.254],[20.103,-3.64,-1.227],[20.11,-3.642,-1.191],[20.083,-3.669,-1.027],[20.075,-3.68,-0.999],[20.053,-3.694,-0.978],[20.053,-3.805,-0.957],[20.063,-3.827,-0.963],[20.045,-3.836,-0.962],[20.01,-3.841,-0.957],[19.737,-3.818,-0.964],[19.712,-3.814,-0.985],[19.699,-3.819,-1.059],[19.724,-3.817,-1.247],[19.725,-3.827,-1.28],[19.719,-3.842,-1.309],[19.719,-3.858,-1.33],[19.714,-3.881,-1.341],[19.699,-4.56,-1.339],[19.7,-4.62,-1.336],[19.7,-4.643,-1.334],[19.699,-4.66,-1.326],[19.698,-4.675,-1.31],[19.697,-4.678,-1.279],[19.697,-4.678,-1.21],[19.704,-4.682,-1.187],[19.716,-4.682,-1.173],[19.736,-4.683,-1.164],[20.481,-4.817,-1.026],[20.529,-4.847,-0.984],[20.562,-4.89,-0.935],[20.585,-4.932,-0.909],[20.59,-4.992,-0.887],[20.565,-5.98,-0.847],[20.547,-6.08,-0.846],[20.541,-6.17,-0.86],[20.476,-6.21,-0.858],[19.847,-6.207,-0.808],[19.803,-6.22,-0.827],[19.775,-6.217,-0.885],[19.75,-6.188,-1.289],[19.743,-6.193,-1.341],[19.742,-6.207,-1.375],[19.75,-6.232,-1.401],[19.722,-6.905,-1.359],[19.723,-6.958,-1.352],[19.722,-6.987,-1.342],[19.721,-7.001,-1.31],[19.721,-7.004,-1.231],[19.734,-7.03,-0.976],[19.742,-7.041,-0.947],[19.747,-7.059,-0.922],[19.755,-7.284,-0.764],[19.761,-7.312,-0.731],[19.776,-7.337,-0.711],[19.795,-7.355,-0.702],[20.502,-7.453,-0.715],[20.578,-7.496,-0.715],[20.631,-7.557,-0.719],[20.66,-7.653,-0.718],[20.658,-8.639,-0.766],[20.654,-8.789,-0.763],[20.639,-8.856,-0.763],[20.605,-8.89,-0.76],[20.57,-8.916,-0.761],[20.539,-8.945,-0.773],[19.879,-9.028,-0.814],[19.853,-9.032,-0.828],[19.834,-9.033,-0.842],[19.83,-9.033,-0.876],[19.857,-9.033,-1.292],[19.837,-9.037,-1.333],[19.819,-9.051,-1.354],[19.812,-9.082,-1.381],[19.79,-9.184,-1.386]]
  23274. ,color:'#8c99aa', radius:0.02, height:-0, fromDataset:true, tension:0.01, spaceDis:0.02,visiEntity:'厨房'
  23275. }
  23276. ],
  23277. 'SG-t-RGUFiJAoxvL':[ //济南工地覆土后
  23278. {//--旧的 整条
  23279. path: [[23.522,-19.432,-1.744],[25.344,20.312,-1.855],[25.344,21.302,-1.861],[25.253,21.904,-1.861],[25.088,22.381,-1.859],[24.748,22.772,-1.861],[24.222,22.893,-1.873],[-24.547,16.774,-1.319]]
  23280. ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0.01,// spaceDis:0.1
  23281. },
  23282. {
  23283. path:[[22.726,22.678,-1.938],[-24.541,16.782,-1.319]]
  23284. ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0,// spaceDis:0.1
  23285. },
  23286. {
  23287. path:[[23.519,-19.473,-1.744],[25.117,15.447,-1.783]]
  23288. ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, tension:0,// spaceDis:0.1
  23289. }
  23290. ],
  23291. 'SG-t-TK0S5EqWBxd':[ //济南工地
  23292. {
  23293. path:[[-25.768,-12.695,-1.305],[-26.334,-21.834,-1.511],[-26.355,-22.153,-1.514],[-26.366,-22.418,-1.513],[-26.31,-22.66,-1.515],[-26.126,-22.841,-1.519],[-25.871,-22.968,-1.525],[-25.443,-22.969,-1.532],[-24.953,-22.956,-1.585],[-23.697,-22.854,-1.637]]
  23294. ,color:'#445', radius:0.08, height:-1.16, fromDataset:true, spaceDis:0.2// tension:0.01,
  23295. },
  23296. ],*/
  23297. });
  23298. viewer.dispatchEvent('allLoaded');
  23299. };
  23300. var transformPointcloud = (pointcloud, dataset) => {
  23301. var locationLonLat = dataset.location.slice(0, 3); // [lon,lat,高程海拔]
  23302. //当只有一个dataset时,无论如何transform 点云和漫游点都能对应上。
  23303. var location = viewer.transform.lonlatToLocal.forward(locationLonLat); //transform.inverse()
  23304. //初始化位置
  23305. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  23306. //dataset.orientation = 0
  23307. Alignment.rotate(pointcloud, null, dataset.orientation);
  23308. Alignment.translate(pointcloud, new Vector3(location[0], location[1], dataset.location[2] - originDataset.location[2])); //要使初始数据集的z为0,所以要减去初始数据集的z
  23309. pointcloud.updateMatrixWorld();
  23310. Potree.Log("\u70B9\u4E91".concat(pointcloud.dataset_id, "(").concat(pointcloud.name, ")\u65CB\u8F6C\u503C:").concat(pointcloud.orientationUser, ", \u4F4D\u7F6E").concat(math.toPrecision(pointcloud.translateUser.toArray(), 3), ", \u7ECF\u7EAC\u5EA6 ").concat(dataset.location, ", spacing ").concat(pointcloud.material.spacing), {
  23311. font: [null, 13]
  23312. });
  23313. };
  23314. if (!Potree.settings.originDatasetId) Potree.settings.originDatasetId = data[0].id;
  23315. var originDataset = data.find(e => e.id == Potree.settings.originDatasetId);
  23316. /* originDataset.location[0] = 113.60608878174709
  23317. originDataset.location[1] = 22.381189423935155
  23318. let ano = data.find(e=>e.name == 'SG-t-Jw0xyhL6oSY')
  23319. ano.location[0] = 113.6060509967498
  23320. ano.location[1] = 22.381061273279244 */
  23321. {
  23322. //拿初始数据集作为基准。它的位置要放到000
  23323. var locationLonLat = originDataset.location.slice(0, 2);
  23324. if (window.AMapWith84) {
  23325. //需要转换为高德的,但该函数不准确,转入后再转出,和原来的有偏差. navvis的我看data中存的globalLocation直接输入到高德地图后的定位和其要展示的定位一致,而我们要转为高德后才一致,猜测是navvis后台转为了高德可用的经纬度。 若不转的话,其他看起来没问题,仅高德地图定位不准确,因其为被加密后的火星坐标系。
  23326. locationLonLat = AMapWith84.wgs84ToAMap({
  23327. x: locationLonLat[0],
  23328. y: locationLonLat[1]
  23329. });
  23330. locationLonLat = [locationLonLat.x, locationLonLat.y];
  23331. }
  23332. proj4.defs("LOCAL", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //高德坐标系
  23333. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15)); //地图和本地一样
  23334. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  23335. var transform1 = proj4("WGS84", "LOCAL"); //这个ok 是展开的平面投影 LOCAL即NAVVIS:TMERC
  23336. var transform2 = proj4("+proj=tmerc +lat_0=0 +lon_0=123 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs;");
  23337. //注:转入后再转出,和原来的有偏差。如果输入是local坐标,数字越大偏差越大,当百万时就明显了。如果是lonlat,很奇怪经度小于50时就乱了。
  23338. viewer.transform = {
  23339. lonlatToLocal: transform1,
  23340. lonlatTo4550: transform2 // 转大地坐标EPSG:4550
  23341. };
  23342. if (window.AMapWith84 && Potree.settings.mapCompany != 'google') {
  23343. //需要转换, 因本地高德用的lonlat和数据里的84不一样. (google地图在国内也用的高德,国外84)
  23344. var change = transform => {
  23345. var forward = transform.forward;
  23346. var inverse = transform.inverse;
  23347. transform.forward = function (e, not84) {
  23348. var needTran = e.x == void 0;
  23349. if (needTran) var a1 = {
  23350. x: e[0],
  23351. y: e[1]
  23352. };else var a1 = e;
  23353. var a = not84 ? a1 : AMapWith84.wgs84ToAMap(a1);
  23354. if (needTran) {
  23355. a = [a.x, a.y];
  23356. e[2] != void 0 && (a[2] = e[2]);
  23357. } else {
  23358. e.z != void 0 && (a.z = e.z);
  23359. }
  23360. return forward(a);
  23361. };
  23362. transform.inverse = function (e, not84) {
  23363. var needTran = e.x == void 0;
  23364. var a = inverse(e);
  23365. needTran && (a = {
  23366. x: a[0],
  23367. y: a[1]
  23368. });
  23369. a = not84 ? a : AMapWith84.aMapToWgs84(a);
  23370. if (needTran) {
  23371. a = [a.x, a.y];
  23372. e[2] != void 0 && (a[2] = e[2]);
  23373. } else {
  23374. e.z != void 0 && (a.z = e.z);
  23375. }
  23376. return a;
  23377. };
  23378. };
  23379. for (var f in viewer.transform) {
  23380. change(viewer.transform[f]);
  23381. }
  23382. }
  23383. viewer.mapViewer && viewer.mapViewer.mapLayer.maps[0].updateProjection();
  23384. }
  23385. data.forEach((dataset, index) => {
  23386. if (!ifReload) {
  23387. var datasetCode = dataset.sceneCode || dataset.name; //对应4dkk的场景码
  23388. if (Potree.settings.isLocal && dataset.mapping) {
  23389. var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(dataset.mapping, "/").concat(dataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  23390. } else {
  23391. var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(dataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  23392. }
  23393. //var cloudPath = `${Potree.scriptPath}/data/test/${dataset.name}/cloud.js`
  23394. var timeStamp = dataset.updateTime ? dataset.updateTime.replace(/[^0-9]/ig, '') : ''; //每重算一次后缀随updateTime更新一次
  23395. //console.warn(dataset.name, 'timeStamp', timeStamp)
  23396. Potree.loadPointCloud(cloudPath, dataset.name, datasetCode, timeStamp, e => {
  23397. var scene = viewer.scene;
  23398. var pointcloud = e.pointcloud;
  23399. var config = Potree.config.material;
  23400. var material = pointcloud.material;
  23401. pointcloud.datasetData = dataset;
  23402. pointcloud.dataset_id = dataset.id; //供漫游点找到属于的dataset点云
  23403. pointcloud.hasDepthTex = Potree.settings.useDepthTex && (!!dataset.has_depth || Potree.settings.isLocalhost && Potree.settings.number == 'SS-t-7DUfWAUZ3V'); //test
  23404. material.minSize = config.minSize;
  23405. material.maxSize = config.maxSize;
  23406. material.pointSizeType = /* Potree.settings.isOfficial ? */config.pointSizeType; /* : 'ADAPTIVE' */ //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  23407. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  23408. pointcloud.changePointOpacity(1);
  23409. material.shape = Potree.PointShape.SQUARE;
  23410. pointcloud.color = pointcloud.material.color = dataset.color;
  23411. pointcloud.timeStamp = timeStamp;
  23412. transformPointcloud(pointcloud, dataset);
  23413. scene.addPointCloud(pointcloud);
  23414. if (!Potree.settings.isOfficial) {
  23415. Potree.settings.floorplanEnables[dataset.id] = true;
  23416. Potree.settings.floorplanType[dataset.id] = 'default';
  23417. }
  23418. pointcloudLoaded++;
  23419. if (pointcloudLoaded == datasetLength) pointcloudLoadDone();
  23420. Potree.loadPanos(dataset.id, data => {
  23421. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  23422. viewer.images360.addPanoData(data, dataset.id);
  23423. panosLoaded++;
  23424. if (panosLoaded == datasetLength) {
  23425. Potree.loadImgVersion(function () {
  23426. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  23427. Potree.settings.panoVersion = e.imgVersion; //全景图被替换后
  23428. panosLoadDone();
  23429. });
  23430. }
  23431. });
  23432. });
  23433. } else {
  23434. var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == dataset.id);
  23435. if (!pointcloud) {
  23436. Potree.Log('数据集id变了,自动使用第一个', {
  23437. font: ['#500']
  23438. });
  23439. pointcloud = viewer.scene.pointclouds[0];
  23440. }
  23441. //先归零
  23442. Alignment.translate(pointcloud, pointcloud.translateUser.clone().negate());
  23443. Alignment.rotate(pointcloud, null, -pointcloud.orientationUser);
  23444. transformPointcloud(pointcloud, dataset);
  23445. }
  23446. });
  23447. if (ifReload) {
  23448. //loadDone()
  23449. }
  23450. };
  23451. number && Potree.loadDatasets(Potree.loadDatasetsCallback);
  23452. /*
  23453. //调试用,加载多个本地
  23454. Potree.loadDatasetsCallback([
  23455. {name:'webcloud_0',id:0, orientation:0, location:[0,0,0]},
  23456. {name:'webcloud_1',id:1, orientation:0.047234761795199476, location:[-0.07925513345058573,-0.0010590072536559839,-2.403613132687564]},
  23457. {name:'webcloud_2',id:2, orientation:-1.5299545647758208, location:[1.5603736310030292, -0.0009340812579088904, -2.4464530770974139]},
  23458. ]) */
  23459. window.testTransform = function (locationLonLat, location1, location2) {
  23460. proj4.defs("NAVVIS:test", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  23461. var transform = proj4("WGS84", "NAVVIS:test"); //这个ok navvis里也是这两种转换 见proj4Factory
  23462. if (location1) {
  23463. //经纬度
  23464. return transform.forward(location1);
  23465. } else {
  23466. return transform.inverse(location2);
  23467. }
  23468. };
  23469. window.THREE = THREE$1;
  23470. window.buttonFunction = function () {
  23471. viewer.scene.pointclouds.forEach(e => e.predictNodeMaxLevel());
  23472. /*
  23473. viewer.startScreenshot({type:'measure', measurement:viewer.scene.measurements[0]})
  23474. viewer.modules.RouteGuider.routeStart = new THREE.Vector3(0,0,-1.3)
  23475. viewer.modules.RouteGuider.routeEnd = new THREE.Vector3(-10,0,-1.3)
  23476. */
  23477. };
  23478. if (Potree.settings.isLocalhost) {
  23479. var before = {};
  23480. viewer.inputHandler.addEventListener('keydown', e => {
  23481. //测试的代码
  23482. if (e.event.key == 't') {
  23483. viewer.images360.cube.visible = true;
  23484. viewer.images360.cube.material.wireframe = true;
  23485. } else if (e.event.key == 'y') {
  23486. viewer.images360.cube.material.wireframe = false;
  23487. viewer.images360.cube.visible = Potree.settings.displayMode == 'showPanos';
  23488. }
  23489. });
  23490. //--------------------------------
  23491. /* if(!number){
  23492. Potree.settings.boundAddObjs = true
  23493. Potree.settings.intersectOnObjs = true
  23494. // Load untextured bunny from ply
  23495. viewer.loadModel({
  23496. fileType:'ply',
  23497. url:Potree.resourcePath + "/models/indoor.ply",
  23498. name:'test',
  23499. },
  23500. (object)=>{
  23501. object.isModel = true
  23502. viewer.updateModelBound()
  23503. }
  23504. )
  23505. } */
  23506. }
  23507. }
  23508. //=======================================================================
  23509. /*
  23510. 漫游点编辑
  23511. */
  23512. //=======================================================================
  23513. function panoEditStart(dom, number, fileServer) {
  23514. Potree.settings.editType = 'pano';
  23515. Potree.settings.number = number;
  23516. Potree.settings.unableNavigate = true;
  23517. Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  23518. var viewer = new Potree.Viewer(dom);
  23519. var Alignment = viewer.modules.Alignment;
  23520. viewer.setEDLEnabled(false);
  23521. viewer.setFOV(Potree.config.view.fov);
  23522. //viewer.loadSettingsFromURL();
  23523. var datasetLoaded = 0;
  23524. if (!Potree.settings.isOfficial) {
  23525. viewer.loadGUI(() => {
  23526. viewer.setLanguage('en');
  23527. $("#menu_tools").next().show();
  23528. $("#panos").show();
  23529. $("#alignment").show();
  23530. viewer.toggleSidebar();
  23531. });
  23532. Potree.settings.sizeFitToLevel = true;
  23533. }
  23534. var pointcloudLoadDone = function pointcloudLoadDone() {
  23535. //所有点云cloud.js加载完毕后
  23536. viewer.scene.pointclouds.forEach(c => {
  23537. transformPointcloud(c);
  23538. });
  23539. viewer.images360.loadDone();
  23540. viewer.scene.add360Images(viewer.images360);
  23541. viewer.updateModelBound();
  23542. var {
  23543. boundSize,
  23544. center
  23545. } = viewer.bound;
  23546. Potree.Log("\u4E2D\u5FC3\u70B9: ".concat(math.toPrecision(center.toArray(), 2), ", boundSize: ").concat(math.toPrecision(boundSize.toArray(), 2), " "), {
  23547. font: [null, 12]
  23548. });
  23549. viewer.scene.view.setView({
  23550. position: center.clone().add(new Vector3(10, 5, 10)),
  23551. target: center
  23552. });
  23553. viewer.dispatchEvent({
  23554. type: 'loadPointCloudDone'
  23555. });
  23556. if (!Potree.settings.UserPointDensity) {
  23557. Potree.settings.UserPointDensity = 'panoEdit'; //'middle'
  23558. }
  23559. Potree.Log('loadPointCloudDone 点云加载完毕', {
  23560. font: [null, 10]
  23561. });
  23562. viewer.dispatchEvent('allLoaded');
  23563. };
  23564. var transformPointcloud = pointcloud => {
  23565. //初始化位置
  23566. viewer.sidebar && viewer.sidebar.addAlignmentButton(pointcloud);
  23567. var orientation = pointcloud.panos[0].dataRotation.z + Math.PI;
  23568. var location = pointcloud.panos[0].dataPosition.clone(); //.negate()
  23569. Alignment.rotate(pointcloud, null, orientation);
  23570. Alignment.translate(pointcloud, location);
  23571. pointcloud.updateMatrixWorld();
  23572. };
  23573. var loadPanosDone = Potree.loadPanosDone = (datasetId, panoData) => {
  23574. //一个数据集获取到它的panos后
  23575. Potree.settings.datasetsPanos[datasetId] = {
  23576. panoData,
  23577. panos: []
  23578. };
  23579. console.log('panoData', datasetId, panoData);
  23580. var panoCount = panoData.length;
  23581. var pointcloudLoaded = 0;
  23582. var datasetsCount = Object.keys(Potree.settings.datasetsPanos).length;
  23583. panoData.forEach((pano, index) => {
  23584. //let cloudPath = `${Potree.scriptPath}/data/panoEdit/uuidcloud/${pano.uuid}/cloud.js`
  23585. var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(Potree.settings.webSite, "/").concat(Potree.settings.number, "/data/bundle_").concat(Potree.settings.number, "/building/uuidcloud/").concat(pano.uuid, "/cloud.js");
  23586. /* if(Potree.settings.isLocal && dataset.mapping){
  23587. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.mapping}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  23588. }else{
  23589. var cloudPath = `${Potree.settings.urls.prefix1}/${dataset.webBin}` //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  23590. } */
  23591. var name = datasetId + '-' + pano.uuid;
  23592. var timeStamp = 0;
  23593. pano.index = index; //注意:index不等于uuid,因为有的uuid缺失。但是visibles中存的是下标!
  23594. Potree.loadPointCloud(cloudPath, name, name, timeStamp, e => {
  23595. //开始加载点云
  23596. var scene = viewer.scene;
  23597. var pointcloud = e.pointcloud;
  23598. var config = Potree.config.material;
  23599. var material = pointcloud.material;
  23600. material.minSize = config.minSize;
  23601. material.maxSize = config.maxSize;
  23602. material.pointSizeType = /* 'ADAPTIVE'// */config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  23603. pointcloud.changePointSize(0.1 /* config.realPointSize */); //material.size = config.pointSize;
  23604. pointcloud.changePointOpacity(1);
  23605. material.shape = Potree.PointShape.SQUARE;
  23606. pointcloud.color = config.pointColor;
  23607. pointcloud.dataset_id = datasetId; //多个点云指向一个datasetId
  23608. pointcloud.panoUuid = pano.uuid;
  23609. pointcloud.timeStamp = timeStamp;
  23610. //transformPointcloud(pointcloud, pano)
  23611. scene.addPointCloud(pointcloud);
  23612. pointcloudLoaded++;
  23613. if (pointcloudLoaded == panoCount) {
  23614. datasetLoaded++;
  23615. viewer.images360.addPanoData(panoData, datasetId);
  23616. if (datasetLoaded == datasetsCount) {
  23617. pointcloudLoadDone();
  23618. }
  23619. }
  23620. });
  23621. });
  23622. };
  23623. if (!Potree.settings.isOfficial) {
  23624. Potree.settings.datasetsPano = {
  23625. 'testDataset': null
  23626. };
  23627. Potree.loadPanosInfo(data => {
  23628. loadPanosDone('testDataset', data.sweepLocations);
  23629. });
  23630. }
  23631. }
  23632. function mergeEditStart(dom, mapDom) {
  23633. Potree.settings.editType = 'merge';
  23634. Potree.settings.intersectOnObjs = true;
  23635. Potree.settings.boundAddObjs = true;
  23636. Potree.settings.unableNavigate = true;
  23637. var viewer = new Potree.Viewer(dom, mapDom);
  23638. var Alignment = viewer.modules.Alignment;
  23639. viewer.setEDLEnabled(false);
  23640. viewer.setFOV(Potree.config.view.fov);
  23641. //viewer.loadSettingsFromURL();
  23642. {
  23643. viewer.mainViewport.view.position.set(30, 30, 30);
  23644. viewer.mainViewport.view.lookAt(0, 0, 0);
  23645. viewer.updateModelBound(); //init
  23646. //this.bound = new THREE.Box3(new THREE.Vector3(-1,-1,-1),new THREE.Vector3(1,1,1))
  23647. viewer.transformationTool.setModeEnable(['translation', 'rotation']);
  23648. //viewer.ssaaRenderPass.sampleLevel = 1 // sampleLevel为1 的话,ground就不会变黑
  23649. viewer.inputHandler.fixSelection = true; //不通过点击屏幕而切换transfrom选中状态
  23650. }
  23651. Potree.settings.sizeFitToLevel = true; //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  23652. Potree.loadPointCloudScene = function (url, type, id, title, done, onError) {
  23653. //对应4dkk的场景码
  23654. var loadCloud = _ref => {
  23655. var {
  23656. cloudPath,
  23657. sceneName,
  23658. sceneCode,
  23659. timeStamp,
  23660. color
  23661. } = _ref;
  23662. Potree.loadPointCloud(cloudPath, sceneName, sceneCode, timeStamp, e => {
  23663. var scene = viewer.scene;
  23664. var pointcloud = e.pointcloud;
  23665. var config = Potree.config.material;
  23666. var material = pointcloud.material;
  23667. material.minSize = config.minSize;
  23668. material.maxSize = config.maxSize;
  23669. material.pointSizeType = config.pointSizeType; //Potree.PointSizeType[config.pointSizeType]//Potree.PointSizeType.ADAPTIVE;//FIXED
  23670. pointcloud.changePointSize(config.realPointSize); //material.size = config.pointSize;
  23671. pointcloud.changePointOpacity(1);
  23672. material.shape = Potree.PointShape.SQUARE;
  23673. color && (pointcloud.color = pointcloud.material.color = color);
  23674. pointcloud.timeStamp = timeStamp;
  23675. //transformPointcloud(pointcloud, originDataset)
  23676. scene.addPointCloud(pointcloud);
  23677. {
  23678. viewer.updateModelBound();
  23679. var {
  23680. boundSize,
  23681. center
  23682. } = viewer.bound;
  23683. viewer.dispatchEvent({
  23684. type: 'loadPointCloudDone'
  23685. });
  23686. if (!Potree.settings.UserPointDensity) {
  23687. Potree.settings.UserPointDensity = 'high'; //'middle'
  23688. }
  23689. Potree.Log('loadPointCloudDone 点云加载完毕', {
  23690. font: [null, 10]
  23691. });
  23692. }
  23693. /* Potree.loadPanos(dataset.id, (data) => { //暂时不加载panos了,因为没有id
  23694. //console.log('loadPanos',dataset.sceneCode, dataset.id, data)
  23695. viewer.images360.addPanoData(data, dataset.id )
  23696. viewer.images360.loadDone()
  23697. viewer.scene.add360Images(viewer.images360); */
  23698. viewer.dispatchEvent('allLoaded');
  23699. done(pointcloud);
  23700. }, onError);
  23701. };
  23702. if (type == 'laser') {
  23703. var sceneCode = url;
  23704. Potree.loadDatasets(data => {
  23705. var originDataset = data.find(e => e.sceneCode == sceneCode); //只加载初始数据集
  23706. var timeStamp = originDataset.updateTime ? originDataset.updateTime.replace(/[^0-9]/ig, '') : ''; //每重算一次后缀随updateTime更新一次
  23707. //let cloudPath = `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${sceneCode}/data/${sceneCode}/webcloud/cloud.js`
  23708. var cloudPath = "".concat(Potree.settings.urls.prefix1, "/").concat(originDataset.webBin); //webBin添加原因:每次裁剪之类的操作会换路径,因为oss文件缓存太严重,更新慢
  23709. loadCloud({
  23710. cloudPath,
  23711. sceneName: originDataset.sceneName,
  23712. sceneCode,
  23713. timeStamp,
  23714. color: originDataset.color
  23715. });
  23716. }, sceneCode, onError);
  23717. } else {
  23718. //las or ply 直接用url
  23719. var name = type + '|' + id + '|' + title;
  23720. if (url instanceof Array) {
  23721. if (url.length == 1) {
  23722. url = url[0];
  23723. } else {
  23724. console.error('有多个点云?暂时还不支持', url, name); //多个点云要一起移动没想好怎么写
  23725. }
  23726. }
  23727. var cloudPath = url + '/cloud.js';
  23728. loadCloud({
  23729. cloudPath,
  23730. sceneName: name,
  23731. sceneCode: name,
  23732. timeStamp: ''
  23733. });
  23734. }
  23735. };
  23736. var setMatrix = pointcloud => {
  23737. //为了漫游点变换,要算一下 类似setMatrix
  23738. /* pointcloud.transformMatrix = new THREE.Matrix4().multiplyMatrices(pointcloud.matrix, pointcloud.pos1MatrixInvert)//还原一点位移
  23739. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert()
  23740. pointcloud.rotateMatrix = new THREE.Matrix4().makeRotationFromEuler(pointcloud.rotation);
  23741. pointcloud.rotateInvMatrix.copy(pointcloud.rotateMatrix).invert()
  23742. pointcloud.panos.forEach(e=>e.transformByPointcloud()) */
  23743. //pointcloud.updateBound()
  23744. //pointcloud.getPanosBound()
  23745. viewer.updateModelBound();
  23746. };
  23747. var moveModel = e => {
  23748. //根据鼠标移动的位置改变位置
  23749. var camera = viewer.mainViewport.camera;
  23750. var origin = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  23751. end = new Vector3(e.pointer.x, e.pointer.y, 1).unproject(camera);
  23752. var dir = end.sub(origin);
  23753. var planeZ = 0;
  23754. var r = (planeZ - origin.z) / dir.z;
  23755. var x = r * dir.x + origin.x;
  23756. var y = r * dir.y + origin.y;
  23757. //过后改为根据intersect的点来设置底部高度;这样的话,需要发送高度
  23758. /*let pos = new THREE.Vector3(x,y, planeZ )
  23759. modelEditing.updateMatrixWorld()
  23760. let boundCenter = modelEditing.boundingBox.getCenter(new THREE.Vector3).applyMatrix4(modelEditing.matrixWorld);
  23761. */
  23762. MergeEditor.moveBoundCenterTo(modelEditing, new Vector3(x, y, modelEditing.boundCenter.z)); //使模型中心的xy在鼠标所在位置
  23763. modelEditing.dispatchEvent("position_changed");
  23764. };
  23765. var cancelMove = () => {
  23766. modelEditing = null;
  23767. viewer.removeEventListener('global_mousemove', moveModel);
  23768. viewer.removeEventListener('global_click', confirmPos);
  23769. };
  23770. var confirmPos = () => {
  23771. MergeEditor.focusOn(modelEditing);
  23772. cancelMove();
  23773. return {
  23774. stopContinue: true
  23775. };
  23776. };
  23777. var modelType,
  23778. modelEditing,
  23779. MergeEditor = viewer.modules.MergeEditor;
  23780. Potree.addModel = function (prop, done, onProgress, onError) {
  23781. //加载模型
  23782. var loadDone = model => {
  23783. model.dataset_id = prop.id; //唯一标识
  23784. if (prop.position) {
  23785. model.position.copy(prop.position);
  23786. }
  23787. if (prop.rotation) {
  23788. //model.rotation.setFromVector3(prop.rotation)
  23789. model.rotation.copy(prop.rotation);
  23790. }
  23791. if (prop.scale) {
  23792. model.scale.set(prop.scale, prop.scale, prop.scale);
  23793. }
  23794. if (model.isPointcloud) {
  23795. model.renderOrder = Potree.config.renderOrders.model; //same as glb
  23796. }
  23797. if (Potree.settings.maintainBtmZ) {
  23798. //transform --------维持离地高度和中心点的版本(local ver)
  23799. var updateBound = () => {
  23800. model.updateMatrixWorld();
  23801. viewer.updateModelBound();
  23802. };
  23803. var maintainBtmZAndCenter = () => {
  23804. MergeEditor.maintainBoundXY(model);
  23805. MergeEditor.setModelBtmHeight(model);
  23806. updateBound();
  23807. model.dispatchEvent('transformChanged');
  23808. };
  23809. model.addEventListener('position_changed', () => {
  23810. updateBound();
  23811. MergeEditor.getBoundCenter(model); //更新boundcenter
  23812. MergeEditor.computeBtmHeight(model);
  23813. if (prop.bottomRange && (model.btmHeight > prop.bottomRange.max || model.btmHeight < prop.bottomRange.min)) {
  23814. model.btmHeight = MathUtils.clamp(model.btmHeight, prop.bottomRange.min, prop.bottomRange.max);
  23815. MergeEditor.setModelBtmHeight(model);
  23816. updateBound();
  23817. }
  23818. model.dispatchEvent('transformChanged');
  23819. });
  23820. model.addEventListener("rotation_changed", maintainBtmZAndCenter);
  23821. model.addEventListener("scale_changed", maintainBtmZAndCenter);
  23822. model.addEventListener('transformChanged', () => {
  23823. MergeEditor.modelTransformCallback(model);
  23824. });
  23825. //离地高度只是boundingbox在transform后的最低点的高度,而非模型transform后的最低点的高度,所以旋转过后看起来不太准确
  23826. } else {
  23827. //transform --------维持中心点的版本
  23828. var _updateBound = () => {
  23829. model.updateMatrixWorld();
  23830. viewer.updateModelBound();
  23831. };
  23832. var maintainCenter = () => {
  23833. //MergeEditor.maintainBoundXY(model)
  23834. MergeEditor.maintainBoundCenter(model);
  23835. _updateBound();
  23836. model.dispatchEvent('transformChanged');
  23837. };
  23838. model.addEventListener('position_changed', () => {
  23839. _updateBound();
  23840. MergeEditor.getBoundCenter(model); //更新boundcenter
  23841. model.dispatchEvent('transformChanged');
  23842. });
  23843. model.addEventListener("rotation_changed", maintainCenter);
  23844. model.addEventListener("scale_changed", maintainCenter);
  23845. model.addEventListener('transformChanged', () => {
  23846. MergeEditor.modelTransformCallback(model);
  23847. });
  23848. }
  23849. model.updateMatrixWorld();
  23850. viewer.updateModelBound();
  23851. MergeEditor.getBoundCenter(model); //初始化
  23852. model.lastMatrixWorld = model.matrixWorld.clone();
  23853. done(model); // 先发送成功,因为2d界面会随机执行changePosition等初始化,然后这边再将模型移到中心地面上
  23854. if (prop.isFirstLoad) {
  23855. MergeEditor.moveBoundCenterTo(model, new Vector3(0, 0, 0));
  23856. MergeEditor.setModelBtmHeight(model, 0); //初始加载设置离地高度为0
  23857. if (prop.mode != 'single') {
  23858. //如果不是模型展示页,模型会随着鼠标位置移动
  23859. modelEditing = model;
  23860. /* if(model.fileType == '3dTiles'){
  23861. setTimeout(()=>{
  23862. moveModel({pointer:{x:0,y:0}}) //3dTiles的移动会错乱,先默认放在当前视图中间吧
  23863. confirmPos()
  23864. },1)
  23865. }else{ */
  23866. viewer.addEventListener('global_mousemove', moveModel);
  23867. viewer.addEventListener('global_click', confirmPos, {
  23868. importance: 3
  23869. });
  23870. //}
  23871. }
  23872. model.dispatchEvent("position_changed");
  23873. } else {
  23874. //MergeEditor.setModelBtmHeight(model, prop.bottom || 0) //默认离地高度为0
  23875. modelEditing = null;
  23876. }
  23877. MergeEditor.modelAdded(model);
  23878. };
  23879. if (prop.type == 'glb') {
  23880. var _callback = object => {
  23881. //focusOnSelect(object, 1000)
  23882. object.isModel = true;
  23883. //object.dataset_id = Date.now() //暂时
  23884. object.traverse(e => e.material && (e.material.transparent = true));
  23885. /* object.addEventListener('click',(e)=>{
  23886. //只是为了能得到hoverElement识别才加这个侦听
  23887. }) */
  23888. loadDone(object);
  23889. };
  23890. var info = {
  23891. fileType: prop.type,
  23892. id: prop.id,
  23893. //unlit:true,
  23894. url: prop.url,
  23895. name: prop.title
  23896. /* transform : {
  23897. position : prop.position,
  23898. rotation : new THREE.Euler().setFromVector3(prop.rotation),
  23899. scale: new THREE.Vector3(prop.scale,prop.scale,prop.scale),
  23900. } */
  23901. };
  23902. viewer.loadModel(info, _callback, onProgress, onError);
  23903. } else if (prop.type == 'osgb' || prop.type == 'b3dm') {
  23904. //3d tiles
  23905. var _callback2 = object => {
  23906. object.isModel = true;
  23907. //透明度怎么办
  23908. //object.traverse(e=>e.material && (e.material.transparent = true))
  23909. loadDone(object);
  23910. };
  23911. viewer.loadModel({
  23912. fileType: '3dTiles',
  23913. id: prop.id,
  23914. name: prop.title,
  23915. maximumScreenSpaceError: prop.maximumScreenSpaceError,
  23916. /* tilesUrl: 'https://4dkk.4dage.com/scene_view_data/SS-Ds19qsmuFA/images/3dtiles/tileset.json',
  23917. transform : {
  23918. rotation : [Math.PI/2, 0, 0],
  23919. position : [0,0,0]
  23920. }
  23921. tilesUrl: 'https://testgis.4dage.com/LVBADUI_qp/tileset.json',
  23922. transform : {
  23923. rotation : [0, 0, 0],
  23924. position : [0,0,0]
  23925. } */
  23926. url: prop.url
  23927. }, _callback2, onprogress);
  23928. } else if (prop.type == 'shp') {
  23929. viewer.loadModel({
  23930. fileType: 'shp',
  23931. id: prop.id,
  23932. name: prop.title,
  23933. url: prop.url
  23934. }, callback, onprogress);
  23935. //shpModel.position.set(-330000, 900000,10)//尽量移动到原点。原位置在江门那
  23936. } else if (prop.type == '3dgs') {
  23937. var _callback3 = object => {
  23938. object.isModel = true;
  23939. loadDone(object);
  23940. };
  23941. viewer.loadModel({
  23942. fileType: '3dgs',
  23943. id: prop.id,
  23944. name: prop.title,
  23945. url: prop.url
  23946. }, _callback3, onprogress);
  23947. } else {
  23948. //else if(prop.type == 'las' || prop.type == 'ply' || prop.type == 'laz' )
  23949. Potree.loadPointCloudScene(prop.url, prop.type, prop.modelId, prop.title, pointcloud => {
  23950. pointcloud.matrixAutoUpdate = true;
  23951. pointcloud.initialPosition = pointcloud.position.clone();
  23952. pointcloud.pos1MatrixInvert = new Matrix4().setPosition(pointcloud.initialPosition).invert();
  23953. /* let maintainBtmZ = ()=>{
  23954. MergeEditor.setModelBtmHeight(pointcloud)
  23955. updateMatrix()
  23956. }
  23957. let updateMatrix = ()=>{
  23958. setMatrix(pointcloud)
  23959. pointcloud.dispatchEvent('transformChanged')
  23960. }
  23961. pointcloud.addEventListener('position_changed', updateMatrix )
  23962. pointcloud.addEventListener("orientation_changed", maintainBtmZ )
  23963. pointcloud.addEventListener("scale_changed", maintainBtmZ ) */
  23964. loadDone(pointcloud);
  23965. /* pointcloud.addEventListener('select',(e)=>{
  23966. if(Potree.settings.displayMode == 'showPanos')return
  23967. console.log('select',e)
  23968. //viewer.setControls(viewer.orbitControls)
  23969. MergeEditor.focusOnSelect(pointcloud)
  23970. viewer.outlinePass.selectedObjects = [pointcloud]
  23971. return {stopContinue:true}
  23972. },{importance:1})
  23973. pointcloud.addEventListener('deselect',(e)=>{
  23974. console.log('deselect',e)
  23975. //viewer.setControls(viewer.fpControls)
  23976. viewer.outlinePass.selectedObjects = []
  23977. }) */
  23978. }, onError);
  23979. }
  23980. };
  23981. return {
  23982. THREE: THREE$1
  23983. };
  23984. }
  23985. var changeLog = () => {
  23986. var textarea = document.createElement('textarea');
  23987. textarea.id = "consoleLog";
  23988. textarea.style.width = '160px';
  23989. textarea.style.height = '200px';
  23990. textarea.style.position = 'fixed';
  23991. textarea.style.left = 0;
  23992. textarea.style.bottom = '50px';
  23993. textarea.style['z-index'] = 9999;
  23994. textarea.style.color = 'black';
  23995. textarea.style.opacity = 0.9;
  23996. textarea.style['font-size'] = '12px';
  23997. textarea.style['backgroundColor'] = '#ffffff';
  23998. document.getElementsByTagName("body")[0].appendChild(textarea);
  23999. var list = ["log", "error", "warn", "debug", "info", "time", "timeEnd"];
  24000. var exchange = function exchange(o) {
  24001. console["old" + o] = console[o];
  24002. console[o] = function () {
  24003. var args = Array.from(arguments);
  24004. console["old" + o].apply(this, arguments);
  24005. var t = document.getElementById("consoleLog").innerHTML;
  24006. var str = '';
  24007. args.forEach(a => {
  24008. str += a + ' ';
  24009. });
  24010. document.getElementById("consoleLog").innerHTML = str + "\n\n" + t;
  24011. };
  24012. };
  24013. for (var i = 0; i < list.length; i++) {
  24014. exchange(list[i]);
  24015. }
  24016. };
  24017. /*
  24018. 坐标转换问题:
  24019. 由于控制点可以随便输入,所以本地和地理位置的转换也是可拉伸的。而navvis的转换是等比由中心展开,
  24020. 所以对比两种转化方式时误差较大。
  24021. 另外地理注册控制点是有参考数据集的,若参考数据集和我放置在0,0,0的数据集一致,就可直接使用,否则要转换。
  24022. ---------
  24023. lonlat和空间坐标其实并非线性关系,因为lonlat其实是角度。当两个数据集在地球两端时,它们之间的夹角都相差180度了。
  24024. 所以若要准确展示的话,需要将点云内所有物体,如漫游点,都先获取lonlat再去算local。或者直接将点云整体的transformMatrix考虑上在地球上相对于初始数据集的偏转。
  24025. 支持ctrl+z、ctrl+Y 撤销回退的页面有:
  24026. 测量、土方量、空间模型 这三个页面的点线拖拽;点云裁剪、点云下载中的裁剪 的框; 点云编辑的变换; 数据集校准;
  24027. (所有数据一旦删除则无效 )
  24028. 其他快捷键:
  24029. 按alt鼠标滚轮或WS键放慢。
  24030. 测量or土方量: 按Alt键可以平行拖拽点。&dragPolyBeyondPoint 后缀则可平行拖拽到无点云区域 。
  24031. 按M键拖拽点可以复制出当前点
  24032. 点云按空格键+左键拖拽场景,可以不改相机位置的旋转视角
  24033. */
  24034. //xzw add
  24035. var config$1 = {
  24036. //配置参数 不可修改
  24037. displayMode: {
  24038. showPointCloud: {
  24039. atPano: {
  24040. showPoint: true,
  24041. showSkybox: false,
  24042. pointUsePanoTex: false
  24043. },
  24044. transition: {
  24045. showPoint: true,
  24046. showSkybox: false,
  24047. pointUsePanoTex: false
  24048. },
  24049. canLeavePano: true //是否能离开pano位置
  24050. },
  24051. showPanos: {
  24052. atPano: {
  24053. showPoint: false,
  24054. showSkybox: true,
  24055. pointUsePanoTex: false
  24056. },
  24057. transition: {
  24058. //showPoint: true,
  24059. showSkybox: true
  24060. //pointUsePanoTex: true //是否使用全景贴图
  24061. },
  24062. canLeavePano: false
  24063. },
  24064. showBoth: {
  24065. atPano: {
  24066. showPoint: true,
  24067. showSkybox: true,
  24068. pointUsePanoTex: false //?
  24069. },
  24070. transition: {
  24071. showPoint: true,
  24072. showSkybox: true,
  24073. pointUsePanoTex: true
  24074. },
  24075. canLeavePano: true //是否能离开pano位置 离开后自动变为showPointCloud
  24076. },
  24077. //test:
  24078. pointUsePanoTex: {
  24079. //---静止时调点云
  24080. atPano: {
  24081. showPoint: true,
  24082. showSkybox: false,
  24083. pointUsePanoTex: true
  24084. },
  24085. transition: {
  24086. showPoint: true,
  24087. showSkybox: true,
  24088. pointUsePanoTex: true //是否使用全景贴图
  24089. },
  24090. canLeavePano: false
  24091. }
  24092. },
  24093. urls: {
  24094. //localTextures:'../resources/textures/',
  24095. prefix1: 'https://laser-oss.4dkankan.com',
  24096. //oss
  24097. prefix2: 'https://testlaser.4dkankan.com',
  24098. prefix3: 'https://4dkk.4dage.com',
  24099. prefix4: 'https://uat-laser.4dkankan.com',
  24100. //test.4dkankan
  24101. prefix5: 'https://laser.4dkankan.com/backend',
  24102. prefix6: 'https://mix3d.4dkankan.com/backend',
  24103. //融合
  24104. prefix7: 'https://xfhd.4dkankan.com/backend' //融合
  24105. },
  24106. transitionsTime: {
  24107. flyMinTime: 650,
  24108. // 毫秒/米
  24109. flytimeDistanceMultiplier: 120
  24110. },
  24111. view: {
  24112. fov: 70,
  24113. //navvis:50
  24114. near: 0.1,
  24115. far: 10000
  24116. },
  24117. map: {
  24118. //mapViewer
  24119. mapHeight: -1000,
  24120. //要比点云低。最低
  24121. cameraHeight: 1000 //最高 ,注意(如sitemodel)其他的物体不能超过这个高度
  24122. },
  24123. minNodeSize: 30,
  24124. // perspectiveCamera允许加载的node的最小可见像素宽度。越大越省性能
  24125. tiles3DMaxMemory: 100,
  24126. //M. 最大支持3dTiles的内存大小 超出会崩溃。 改太小太大都会卡,太大崩溃
  24127. pointDensity: {
  24128. magnifier: {
  24129. maxLevelPercent: 1,
  24130. pointBudget: 1 * 1000 * 1000,
  24131. //至少显示这么多
  24132. minNodeSize: 5 //pick时调高精度
  24133. },
  24134. panorama: {
  24135. //显示全景时的漫游。因为点只能显示1个像素的大小,所以必须很密集,但又要限制点的数量
  24136. maxLevelPercent: 0.6,
  24137. pointBudget: /* 4*1000*1000// */browser.isMobile() ? 0.2 * 1000 * 1000 : 0.4 * 1000 * 1000,
  24138. //点云总最大数
  24139. minNodeSize: 100
  24140. },
  24141. fourViewports: {
  24142. //分四屏时防止卡顿
  24143. maxLevelPercent: 0.9,
  24144. pointBudget: 3 * 1000 * 1000,
  24145. // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  24146. minNodeSize: 70
  24147. },
  24148. fourViewportsMain: {
  24149. //分四屏时防止卡顿
  24150. maxLevelPercent: 0.9,
  24151. pointBudget: 3 * 1000 * 1000,
  24152. // 只要限制这个就足够 (为什么分屏focus区域不同会闪烁,navvis不会)(navvis:maxLevel:5,pointBudget:1*1000*1000)
  24153. minNodeSize: 70
  24154. },
  24155. panoEdit: {
  24156. maxLevelPercent: 1,
  24157. //在远处时由于pointBudget限制而展示稀疏,凑近时就变为最高质量了
  24158. pointBudget: 4 * 1000 * 1000,
  24159. //要使点云达到200个以上时还不卡
  24160. percentByUser: true,
  24161. minNodeSize: 80 //点云多的话远处的尽量就不可见吧
  24162. },
  24163. low: {
  24164. //highPerformance
  24165. maxLevelPercent: 0.4,
  24166. //最小为0
  24167. percentByUser: true,
  24168. //如果用户定义了percent,使用用户的
  24169. pointBudget: browser.isMobile() ? 1 * 1000 * 1000 : 2 * 1000 * 1000,
  24170. minNodeSize: 40 / window.devicePixelRatio
  24171. },
  24172. middle: {
  24173. //balanced //不同场景相同级别所产生的numVisibleNodes和numVisiblePoints不同,如果分层比较细,可能要到level8才能看清,那么level5看到的点就很大且很少,如隧道t-e2Kb2iU
  24174. maxLevelPercent: 0.7,
  24175. percentByUser: true,
  24176. pointBudget: browser.isMobile() ? 1.5 * 1000 * 1000 : 3.5 * 1000 * 1000,
  24177. minNodeSize: 30 / window.devicePixelRatio
  24178. },
  24179. high: {
  24180. //highQuality
  24181. maxLevelPercent: 1,
  24182. percentByUser: true,
  24183. pointBudget: browser.isMobile() ? 3 * 1000 * 1000 : 6 * 1000 * 1000,
  24184. //原本最高是8,但是大部分电脑都太卡了,降
  24185. minNodeSize: 20 / window.devicePixelRatio //手机上因为像素点小,远一点的时候更需要加载密集的点云。(没事,有pointBudget限制着,会先从近处加载高级node,再远就不加载了)
  24186. },
  24187. screenshot: {
  24188. maxLevelPercent: 1,
  24189. pointBudget: browser.isMobile() ? 4 * 1000 * 1000 : 10 * 1000 * 1000,
  24190. //一般只有电脑需要截图,手机的加载多会崩
  24191. minNodeSize: 40 / window.devicePixelRatio
  24192. },
  24193. screenshot2: {
  24194. maxLevelPercent: 1,
  24195. pointBudget: browser.isMobile() ? 8 * 1000 * 1000 : 15 * 1000 * 1000,
  24196. minNodeSize: 20 / window.devicePixelRatio
  24197. },
  24198. ultraHigh: {
  24199. maxLevelPercent: 1,
  24200. pointBudget: 20 * 1000 * 1000,
  24201. minNodeSize: 10 / window.devicePixelRatio
  24202. }
  24203. //数值由testLevelSteps得来,其中nodeMaxLevel为2时,low和middle的都是1,如果真有这么低的点云就单独处理下。
  24204. //多个viewport尽量保证pointBudget一样,或者pointBudget不能太低于所需,否则会反复加载了又清除
  24205. },
  24206. clip: {
  24207. color: '#FFC266' //map
  24208. },
  24209. measure: {
  24210. color: '#00C8AF',
  24211. default: {
  24212. color: "#64C8BB",
  24213. //"#00c7b2",
  24214. opacity: 0.7
  24215. },
  24216. highlight: {
  24217. color: '#00C8AF',
  24218. //"#00c7b2",
  24219. opacity: 1,
  24220. labelOpacity: 0.7 //1会挡住线和端点
  24221. },
  24222. guide: {
  24223. color: '#FFFFFF',
  24224. opacity: 0.8
  24225. },
  24226. backColor: '#333333',
  24227. lineWidth: 3,
  24228. textColor: "#000000",
  24229. //"#FFFFFF"
  24230. mulLabelHideFaraway: false,
  24231. // 多折线根据远近显示label
  24232. adsorptMinDis: 30 //最小吸附距离(像素)
  24233. },
  24234. material: {
  24235. //初始化
  24236. pointSize: 0.1,
  24237. realPointSize: 0.1,
  24238. //实际上的ui滑动条默认大小(兼容旧的版本)
  24239. minSize: 0.1,
  24240. maxSize: 10000,
  24241. pointSizeType: 'ATTENUATED',
  24242. //'ADAPTIVE'//'ADAPTIVE' \ FIXED //ADAPTIVE的在小房间里大小会不太匹配,但在远景似乎更好
  24243. /*
  24244. ATTENUATED : 衰减 真实大小,靠近时感觉是点云一点点变多,缝隙变小
  24245. ADAPTIVE: 自适应 大小根据level变化,越高越小。靠近时感觉点云由大慢慢细分成小份。这个感觉更佳但是navvis为何不用这个
  24246. */
  24247. absolutePanoramaSize: 1.3,
  24248. //全景漫游时的size 是fixed的模式
  24249. //sizeAtPanoRtEDL : 2000,
  24250. pointColor: '#ffffff'
  24251. //sizeAddAtPanoRtEDL : 0.5, //全景模式静止时的size
  24252. //ADAPTIVE : 字会失真扭曲
  24253. //'ATTENUATED' 往旁边看有缝隙、点在浮动
  24254. },
  24255. skyboxBgWidth: 100,
  24256. renderLayers: {
  24257. //渲染层,方便分批渲染管理,替代scene的创建。数字不代表顺序。(数字不能太大)
  24258. bg: 20,
  24259. bg2: 21,
  24260. skybox: 1,
  24261. pointcloud: 11,
  24262. sceneObjects: 0,
  24263. //default
  24264. model: 2,
  24265. light: 15,
  24266. measure: 4,
  24267. magnifier: 5,
  24268. magnifierContent: 16,
  24269. volume: 6,
  24270. transformationTool: 7,
  24271. map: 8,
  24272. mapObjects: 9,
  24273. //default
  24274. bothMapAndScene: 3,
  24275. siteModeOnlyMapVisi: 12,
  24276. //只能mapViewer可见
  24277. siteModelMapUnvisi: 13,
  24278. //只有mapViewer不可见
  24279. siteModeSideVisi: 14,
  24280. //只有侧面可见
  24281. layer1: 18,
  24282. // 备用1
  24283. layer2: 17 // 备用2
  24284. },
  24285. renderOrders: {
  24286. //会影响到绘制、pick时的顺序。
  24287. model: 10,
  24288. reticule: 5,
  24289. measureMarker: 6,
  24290. measureLabelSub: 7,
  24291. measureLabel: 8,
  24292. sorptionSign: 10,
  24293. model: 10,
  24294. magnifier: 50
  24295. },
  24296. siteModel: {
  24297. names: {
  24298. 'building': '建筑',
  24299. 'floor': '楼层',
  24300. 'room': '房间'
  24301. },
  24302. floorHeightDefault: 5 //一层楼的高度
  24303. },
  24304. panosEdit: {},
  24305. tiling: {
  24306. panoPreRenderRepeatDelay: 2500,
  24307. panoPreRenderDelay: 500,
  24308. preRenderTourPanos: browser.valueFromHash("tileprerender", 0),
  24309. tilingFlagNames: ["usetiles", "tiles"],
  24310. maxNavPanoQuality: browser.valueFromHash("maxtileq", null),
  24311. maxZoomPanoQuality: browser.valueFromHash("maxztileq", null),
  24312. overlayStyle: browser.valueFromHash("tileoverlay", 0),
  24313. uploadIntervalDelay: browser.valueFromHash("tileupdelay", 10),
  24314. initialIntervalDelay: browser.valueFromHash("itiledelay", 0),
  24315. maxNonBaseUploadsPerFrame: browser.valueFromHash("maxnbtpf", 1),
  24316. maxBaseUploadsPerFrame: browser.valueFromHash("maxbtpf", 6),
  24317. customCompression: browser.valueFromHash("tilecustcomp", 0),
  24318. mobileHighQualityOverride: !1,
  24319. allowUltraHighResolution: !0
  24320. },
  24321. navigation: {
  24322. panoScores: !1,
  24323. mouseDirection: !0,
  24324. filterStrictness: .75,
  24325. angleFactor: -30,
  24326. directionFactor: 10,
  24327. distanceFactor: -1,
  24328. optionalityFactor: 3
  24329. },
  24330. axis: {
  24331. 'x': {
  24332. color: '#ea3f3f' /* '#d0021b' */ /* 'red' */
  24333. },
  24334. 'y': {
  24335. color: '#86c215' /* '#86c542' */ /* 'green' */
  24336. },
  24337. 'z': {
  24338. color: '#3396f8' /* '#3399c8' */ /* 'blue' */
  24339. },
  24340. 'xyz': {
  24341. color: '#ccc'
  24342. }
  24343. },
  24344. shelterMargin: 0.15,
  24345. //多少米内不算遮挡 (有的场景深度图不准,和点云差别蛮大如SG-t-24F0iT3pKAO)
  24346. highQualityMaxZoom: 2,
  24347. ultraHighQualityMaxZoom: 3,
  24348. panoFieldRadius: 10,
  24349. //当前位置多远范围内可以切全景模式
  24350. clickMaxDragDis: 3,
  24351. clickMaxPressTime: 200,
  24352. //ms
  24353. doubleClickTime: 300,
  24354. //双击间隔时间
  24355. testNodeCount1: browser.isMobile() ? 6 : 4,
  24356. //testMaxNode次数达到这个数字时,changePointSize才使用nodeMaxLevel。 (调试时比较卡,在线上实际只需要3)
  24357. background: '#232323',
  24358. mapBG: /* '#232323', */'#F5F5F5',
  24359. //地图的clearColor
  24360. pickFrontPointRatio: 50,
  24361. colors: {
  24362. //from navvis
  24363. red: [213, 0, 0],
  24364. pink: [197, 17, 98],
  24365. purple: [170, 0, 255],
  24366. "deep purple": [98, 0, 234],
  24367. blue: [41, 98, 255],
  24368. "light blue": [0, 145, 234],
  24369. cyan: [0, 184, 212],
  24370. teal: [0, 191, 165],
  24371. green: [0, 200, 83],
  24372. "light green": [100, 221, 23],
  24373. lime: [174, 234, 0],
  24374. yellow: [255, 214, 0],
  24375. amber: [255, 171, 0],
  24376. orange: [255, 109, 0],
  24377. "deep orange": [255, 61, 0]
  24378. },
  24379. depthTexUVyLimit: 0.141 // 在这个范围内是没有深度的,从图片算的0.14003, 设置为稍大于这个数值
  24380. };
  24381. config$1.OrthoCameraLimit = {
  24382. standard: {
  24383. zoom: {
  24384. min: 0.0004,
  24385. max: 500
  24386. },
  24387. //如果camera缩太小,地图会因为数字边界问题而扭曲
  24388. latPad: 20,
  24389. xBound: [-4e6, 4e6]
  24390. },
  24391. expand: {
  24392. zoom: {
  24393. min: 0.0004,
  24394. max: 500
  24395. },
  24396. //如果camera缩太小,地图会因为数字边界问题而扭曲
  24397. latPad: 20,
  24398. xBound: [-6e6, 6e6]
  24399. }
  24400. };
  24401. /* 显示模式:
  24402. 1只显示点云: 滚轮为前进后退,方向键可以行走。进入漫游点时自动变为混合(这样全景可以弥补缝隙),过渡时只显示点云。
  24403. 2只显示全景: 不能任意行走。 过渡时显示贴图材质非edl的点云(否则有折痕不贴合)。
  24404. 3混合:都显示。 不能任意行走。过渡时显示贴图材质非edl的点云(因为只显示点云的话不太美,点云很碎,不细腻)
  24405. */
  24406. window.testLevelSteps = function (steps) {
  24407. //[0.4,0.7,1]
  24408. if (!steps) {
  24409. var s = Potree.config.pointDensity;
  24410. steps = [s.low.maxLevelPercent, s.middle.maxLevelPercent, s.high.maxLevelPercent];
  24411. }
  24412. var max = 1;
  24413. while (++max <= 12) {
  24414. var r1 = steps.map(e => e * max);
  24415. var r2 = steps.map(e => Math.round(e * max));
  24416. console.log("\u5F53nodeMaxLevel\u4E3A".concat(max, "\u65F6\uFF0C\u6BCF\u4E00\u7EA7\u7684level\u5206\u522B\u4E3A").concat(r2, ", (\u5C0F\u6570\uFF1A").concat(r1, ")"));
  24417. }
  24418. console.log('请检查每一层的三个level是否有重复');
  24419. };
  24420. function getPrefix() {
  24421. var u = window.location.href.split('//');
  24422. var v = u[1].split('/');
  24423. return v[0];
  24424. }
  24425. var isTest = browser.urlHasValue('test');
  24426. var settings = {
  24427. //设置 可修改
  24428. editType: '',
  24429. number: '',
  24430. //场景序号
  24431. originDatasetId: '',
  24432. //场景原本的数据集id,应该就是数据集第一个吧
  24433. isOfficial: false,
  24434. webSite: 'testdata',
  24435. //正式:'datav1', //不同环境对应的静态文件的地址不同
  24436. isLocal: false,
  24437. //是否本地 局域网版本
  24438. libsUrl: '../libs/',
  24439. displayMode: '',
  24440. isTest,
  24441. prefix: getPrefix(),
  24442. pointDensity: '',
  24443. UserPointDensity: '',
  24444. //pointDensity会随着进入不同的模块而自动改变,UserPointDensity记录了用户的设置
  24445. UserDensityPercent: null,
  24446. //点云密度百分比
  24447. ifShowMarker: true,
  24448. //显示漫游点
  24449. floorplanType: {},
  24450. //平面图类型 'default' | 'diy' 不同数据集不同{datasetId:...}
  24451. floorplanEnable: false,
  24452. floorplanEnables: {},
  24453. floorplanRequests: {},
  24454. //开始加载了的
  24455. mapEnable: true,
  24456. //地图区域是否加载地图
  24457. cameraFar: config$1.view.far,
  24458. //相机最远范围 1-300
  24459. //limitFar: true, //是否使用setting的cameraFar来限制(如在点云裁剪时为false)
  24460. showPanoMesh: false,
  24461. //显示小球,
  24462. dblToFocusPoint: false,
  24463. //调试时如果需要双击飞向某个点云的点,就打开。此时不在漫游点的话单击将无法漫游。//因和单击漫游冲突
  24464. unableNavigate: false,
  24465. //进入如裁剪界面时 禁止漫游
  24466. sizeFitToLevel: false,
  24467. //当type为衰减模式时自动根据level调节大小。每长一级,大小就除以2
  24468. zoom: {
  24469. enabled: true,
  24470. min: 1,
  24471. max: config$1.highQualityMaxZoom
  24472. },
  24473. navConstantly: true,
  24474. navTileClass: /* browser.isMobile() ? '1k' : */'2k',
  24475. //默认加载到
  24476. tileClass: '4k',
  24477. //最高可达
  24478. /* loadTilesWhenUnfocus:false, //页面unfocus时也仍在加载tiles
  24479. loadPointsWhenUnfocus:true, //页面unfocus时也仍在加载点云 */
  24480. //initialShowPano:true
  24481. drawEntityData: false,
  24482. //包括marker、线
  24483. zoomFromPointert: {
  24484. //定点缩放(包括点云模式、全景模式、地图)
  24485. whenPanos: true,
  24486. whenPointCloud: true,
  24487. map: true
  24488. },
  24489. rotAroundPoint: true,
  24490. //点云模式是否能绕intersectPoint旋转
  24491. tourTestCameraMove: false,
  24492. //测试镜头时,不移动真实的镜头, 只移动frustum
  24493. cameraAniSmoothRatio: 20,
  24494. //镜头动画平滑系数,越高越平滑
  24495. urls: $.extend({}, config$1.urls, {
  24496. prefix: config$1.urls.prefix4 //主要使用的 是测试环境,根据不同工程更改
  24497. }),
  24498. useDepthTex: true,
  24499. //使用深度贴图,但不代表一定有(得到的intersect更快速准确和稳定) SS-t-7DUfWAUZ3V
  24500. //matUseDepth:false,
  24501. //panoEdit:
  24502. datasetsPanos: {},
  24503. //mergeModel:
  24504. boundAddObjs: false,
  24505. intersectOnObjs: false,
  24506. intersectWhenHover: true,
  24507. depTexLocBindDataset: true,
  24508. //是否在pano模式下,使用深度图得到intersect的话,改intersect能属于该pano所在的点云。也就相当于在全景模式下intersect的点属于该全景图
  24509. notAdditiveBlending: false,
  24510. //点云是否使用普通的blend, 否则会曝光过渡
  24511. precision: 2,
  24512. // 两位小数
  24513. unit: 'm',
  24514. useV4url: true,
  24515. //v4的全景图等路径不一样 scene_view_data
  24516. useRTskybox: true,
  24517. //直接使用rtEDL绘制到屏幕,当是全景模式时. 在降4倍时能给render节省1毫秒,gpu时间未测
  24518. useRTPoint: true,
  24519. //直接使用rtEDL绘制到屏幕,当是点云模式时。可以大大节省gpu时间。但有锯齿
  24520. pointEnableRT: false,
  24521. //点云模式时是否绘制到rtEDL。如果不需要遮挡效果就不需绘制
  24522. cloudSameMat: true,
  24523. //因为点云个数较多,就使用相同的材质,可见降低绘制速度(要保证所有点云的maxNodelevel一样,且要算出 material.spacing的平均值)
  24524. showCompass: false,
  24525. showAxis: isTest,
  24526. //testCube : true,
  24527. // moveToCenter:true, //针对数据集间隔很远的场景 dis>5000 容易抖动
  24528. tiles3DMaxMemory: config$1.tiles3DMaxMemory,
  24529. adsorption: false,
  24530. //测量时吸附点
  24531. pickFrontPointRatio: config$1.pickFrontPointRatio,
  24532. //默认pick点云时选中靠近镜头的点的偏向
  24533. dragPolyBeyondPoint: browser.urlHasValue('dragPolyBeyondPoint'),
  24534. //ctrlPolygon是否可以拖拽到没点云的地方
  24535. panoZoomByPointer: false,
  24536. //全景图是否定点缩放
  24537. areaAtNotPlane: false,
  24538. fastTran: isTest
  24539. };
  24540. Potree.config = config$1;
  24541. Potree.settings = settings;
  24542. settings.isLocalhost = settings.prefix.includes('localhost:') || settings.prefix.includes('localhost:');
  24543. settings.isFormal = browser.urlHasValue('formal'); //正式环境 本地测试
  24544. if (settings.isFormal) {
  24545. settings.urls.prefix = settings.urls.prefix5;
  24546. settings.webSite = 'datav1';
  24547. }
  24548. var texLoader$2 = new TextureLoader();
  24549. texLoader$2.crossOrigin = "anonymous";
  24550. var createErrorMaterial = function createErrorMaterial() {
  24551. var t = new MeshBasicMaterial({
  24552. transparent: !0,
  24553. depthWrite: !1,
  24554. depthTest: !0,
  24555. opacity: 1,
  24556. side: DoubleSide
  24557. });
  24558. return t.color = new Color(3355443), t;
  24559. };
  24560. var tempVector = new Vector3(),
  24561. //sharedata
  24562. face1 = new Face3(0, 1, 2),
  24563. face2 = new Face3(2, 3, 0),
  24564. errorMaterial = createErrorMaterial(),
  24565. uv00 = new Vector2(0, 0),
  24566. uv01 = new Vector2(0, 1),
  24567. uv10 = new Vector2(1, 0),
  24568. uv11 = new Vector2(1, 1),
  24569. face1UV = [uv00, uv10, uv11],
  24570. face2UV = [uv11, uv01, uv00];
  24571. var HALF_WORLD_SIZE = 21e6; //略大于半个周长(mapSizeM/2)
  24572. var MAX_VERTICAL_DIST = 2;
  24573. var MAX_VERTICAL_DIST_TO_BEST = 1;
  24574. function defineLocalProj(locationLonLat) {
  24575. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat[0].toPrecision(15) + " +lat_0=" + locationLonLat[1].toPrecision(15));
  24576. }
  24577. var getSid = function () {
  24578. var sid = 0;
  24579. return function () {
  24580. return sid++;
  24581. };
  24582. }();
  24583. //高德坐标拾取工具 : https://lbs.amap.com/tools/picker
  24584. class MapLayer extends EventDispatcher {
  24585. // 包括了 MapLayerBase SceneLayer
  24586. constructor(viewer_, viewport) {
  24587. super();
  24588. this.sceneGroup = new Object3D();
  24589. this.sceneGroup.name = "MapLayer";
  24590. this.waitQueue = []; //等待加载的
  24591. this.loadingInProgress = 0;
  24592. this.maps = [];
  24593. this.frustum = new Frustum();
  24594. this.frustumMatrix = new Matrix4();
  24595. this.tileColor = new Color(16777215);
  24596. this.viewport = viewport;
  24597. this.changeViewer(viewer_);
  24598. //添加地图
  24599. var map = new TiledMapOpenStreetMap(this, this.tileColor);
  24600. this.addMap(map);
  24601. //map.setEnable(false)
  24602. this.sceneGroup.addEventListener('isVisible', () => {
  24603. this.viewer.mapChanged = true;
  24604. });
  24605. }
  24606. addMapEntity(data, datasetId) {
  24607. if (!data || !data[0]) {
  24608. Potree.Log('平面图无数据', {
  24609. font: 'red'
  24610. });
  24611. return;
  24612. }
  24613. data[0].datasetId = datasetId;
  24614. var floorplan = new TiledMapFromEntity(this, this.tileColor, data[0]); //[0]?
  24615. if (floorplan) {
  24616. floorplan.name += "_" + datasetId;
  24617. this.addMap(floorplan);
  24618. floorplan.updateProjection();
  24619. floorplan.updateObjectGroup();
  24620. var visible = false;
  24621. if (datasetId in Potree.settings.floorplanEnables) {
  24622. visible = Potree.settings.floorplanEnables[datasetId];
  24623. } else {
  24624. visible = Potree.settings.floorplanEnable;
  24625. }
  24626. if (visible) {
  24627. this.needUpdate = true;
  24628. } else {
  24629. floorplan.setEnable(false);
  24630. }
  24631. this.dispatchEvent({
  24632. type: 'floorplanLoaded',
  24633. floorplan
  24634. });
  24635. }
  24636. return floorplan;
  24637. }
  24638. getFloorplan(datasetId) {
  24639. return this.maps.find(e => e.name == 'floorplan' + "_" + datasetId);
  24640. }
  24641. addMap(t) {
  24642. this.maps.push(t);
  24643. //this.view.invalidateScene()
  24644. this.needUpdate = true;
  24645. this.viewer.mapChanged = true;
  24646. }
  24647. removeMap(t) {
  24648. var e = this.maps.indexOf(t);
  24649. if (e >= 0) {
  24650. t.removeFromSceneGroup(this.sceneGroup);
  24651. this.maps.splice(e, 1);
  24652. }
  24653. /* this.view.invalidateScene() */
  24654. this.needUpdate = true;
  24655. this.viewer.mapChanged = true;
  24656. }
  24657. changeViewer(viewer_) {
  24658. //add
  24659. this.viewer = viewer_;
  24660. }
  24661. initProjection() {
  24662. this.maps.forEach(map => {
  24663. map.updateProjection();
  24664. map.updateObjectGroup();
  24665. });
  24666. }
  24667. visibilityChanged() {
  24668. if (!this.visible) for (var t = 0, e = this.maps; t < e.length; t++) {
  24669. e[t].removeFromSceneGroup(this.sceneGroup);
  24670. }
  24671. }
  24672. update() {
  24673. this.needUpdate = false;
  24674. if (this.disabled || !this.maps.find(e => !e.disabled) || !this.maps.find(e => e.objectGroup.visible)) return; //add
  24675. this.viewer.mapChanged = true;
  24676. var e, n, i, r, o;
  24677. this.updateTimer = void 0, e = this.viewport.camera, n = e.projectionMatrix.clone();
  24678. var expandRatio = 1.3;
  24679. n.elements[0] /= expandRatio;
  24680. n.elements[5] /= expandRatio; // 为了缓存吗,使边界处也提前加载,扩大显示区域
  24681. this.frustumMatrix.multiplyMatrices(n, e.matrixWorldInverse), this.frustum.setFromProjectionMatrix(this.frustumMatrix), this.frustum.planes[4].setComponents(0, 0, 0, 0), this.frustum.planes[5].setComponents(0, 0, 0, 0), i = !0;
  24682. //console.log('-------------update-----------')
  24683. for (r = 0; r < this.maps.length; r++) {
  24684. var map = this.maps[r];
  24685. i = map.update(this.frustum, this.sceneGroup) && i;
  24686. }
  24687. return [2, i];
  24688. }
  24689. updateProjection() {
  24690. for (var t = 0, e = this.maps; t < e.length; t++) {
  24691. var n = e[t];
  24692. n.clearProjection(), n.updateObjectGroup();
  24693. }
  24694. }
  24695. }
  24696. class TiledMapBase extends EventDispatcher {
  24697. constructor(name, mapLayer, tileColor, projection) {
  24698. super();
  24699. this.name = name;
  24700. this.mapLayer = mapLayer, this.tileColor = tileColor, this.bias = 0;
  24701. this.zIndex = -1;
  24702. this.objectGroup = new Object3D();
  24703. this.objectGroup.name = name;
  24704. this.objectGroupAdded = !1, this.baseTile = new MapTile(this, this.objectGroup, this.tileColor, null, '0'), this.isTileVisibleBox = new Box3(), this.isTileVisibleVec = new Vector3();
  24705. this.projection = projection;
  24706. this._zoomLevel = 0; //1-20
  24707. this.objectGroup.addEventListener('isVisible', () => {
  24708. this.mapLayer.viewer.mapChanged = true;
  24709. });
  24710. this.computeCount = 0;
  24711. this.maxLoading = 3;
  24712. this.loadFailCount = 0;
  24713. this.loadingInProgress = 0;
  24714. }
  24715. get zoomLevel() {
  24716. return this._zoomLevel;
  24717. }
  24718. set zoomLevel(zoomLevel) {
  24719. if (this._zoomLevel != zoomLevel) {
  24720. this._zoomLevel = zoomLevel;
  24721. this.dispatchEvent({
  24722. type: 'zoomLevelChange',
  24723. zoomLevel
  24724. });
  24725. //if(this.name == 'map')console.log(zoomLevel,viewer.mapViewer.camera.zoom)
  24726. }
  24727. }
  24728. updateObjectGroup() {
  24729. this.position && this.objectGroup.position.copy(this.position).setZ(0), this.quaternion && this.objectGroup.quaternion.copy(this.quaternion), this.objectGroup.updateMatrixWorld(!0);
  24730. }
  24731. updateProjection() {
  24732. if (!this.transformMapToLocal) {
  24733. this.transformMapToLocal = proj4(this.projection, "LOCAL_MAP");
  24734. }
  24735. }
  24736. clearProjection() {
  24737. this.transformMapToLocal = void 0;
  24738. this.projection !== 'LOCAL_MAP' && this.baseTile.remove();
  24739. }
  24740. setEnable(enable) {
  24741. //add
  24742. if (!this.disabled == enable) return;
  24743. if (enable) {
  24744. //console.log('setEnable',true)
  24745. }
  24746. this.disabled = !enable;
  24747. Potree.Utils.updateVisible(this.objectGroup, 'setEnable', enable);
  24748. if (!enable) {
  24749. this.baseTile.remove();
  24750. } else {
  24751. this.mapLayer.needUpdate = true;
  24752. }
  24753. }
  24754. update(e, n) {
  24755. this.computeCount = 0;
  24756. var unavailable = this.disabled || !this.objectGroup.visible; //地图即使不显示也要获得zoomlevel
  24757. if (this.name != 'map' && unavailable) return;
  24758. this.updateProjection();
  24759. if (!this.transformMapToLocal) return;
  24760. if (!this.isTileVisible(new Vector3(0, 0, 0), this.mapSizeM, e)) return this.removeFromSceneGroup(n), !0;
  24761. var viewport = this.mapLayer.viewport;
  24762. var i = new Vector3(-.5 * this.mapSizeM, 0, 0);
  24763. i.applyMatrix4(this.objectGroup.matrixWorld), i.project(viewport.camera);
  24764. var o = new Vector3(.5 * this.mapSizeM, 0, 0);
  24765. o.applyMatrix4(this.objectGroup.matrixWorld), o.project(viewport.camera);
  24766. var a = viewport.resolution.x,
  24767. s = viewport.resolution.y;
  24768. if (a <= 0 || s <= 0 || isNaN(i.x) || isNaN(o.x)) return !1;
  24769. i.sub(o), i.x *= a / 2, i.y *= s / 2;
  24770. var scale;
  24771. if (this.name == 'map') {
  24772. //add 高纬度的因倾斜而造成tile较小,所以放大些,否则会造成显示的tile过多而卡
  24773. var lonlat = viewer.transform.lonlatToLocal.inverse(viewport.camera.position.clone());
  24774. var cos = Math.cos(MathUtils.degToRad(lonlat.y)); //越小就在纬度上越高,tile表现越小
  24775. //为什么lonlat.y会超出90?
  24776. /* if(lonlat.y>90){
  24777. console.log('lonlat.y>90',lonlat.y)
  24778. } */
  24779. cos = MathUtils.clamp(cos, 0, 1);
  24780. var lonShift = Math.abs(viewer.mapViewer.camera.position.x / this.mapSizeM * 16); //越大就在经度离中心越远,tile表现越大 。
  24781. lonShift = MathUtils.clamp(lonShift, 0, Math.PI);
  24782. lonShift = (1 - Math.sin(1 / 2 * lonShift + Math.PI / 2)) * Math.PI; // 0-Math.PI sin增速向上
  24783. scale = 0.5 * cos * (1 + lonShift) + 0.5 * Math.pow(cos, lonShift);
  24784. } else {
  24785. scale = 1;
  24786. }
  24787. var c = this.tileSizePx / i.length() / scale //多除以一个scale缩放因子,scale越大level越小
  24788. ,
  24789. level = Math.ceil(-Math.log(c) / Math.log(2) - this.bias);
  24790. level = Math.max(level, 0);
  24791. level = Math.min(level, void 0 === this.maxDepth ? 1 / 0 : this.maxDepth);
  24792. this.zoomLevel = level; //add
  24793. /* if(isNaN(this.zoomLevel )){
  24794. console.log(level, cos , scale , lonlat )
  24795. } */
  24796. if (!unavailable) {
  24797. this.addToSceneGroup(n);
  24798. return this.baseTile.update(this, e, level, this.mapSizeM, 0, 0, "");
  24799. }
  24800. }
  24801. isTileVisible(e, n, i) {
  24802. if (n > HALF_WORLD_SIZE) return !0;
  24803. var r = .5 * n;
  24804. //简单版:
  24805. this.transformMapToLocal.forward(e); //e转化为local
  24806. this.isTileVisibleBox.makeEmpty();
  24807. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  24808. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  24809. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  24810. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  24811. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  24812. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  24813. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z).applyMatrix4(this.objectGroup.matrixWorld);
  24814. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec);
  24815. //仿造createMesh写的准确版,但会因为大的tile非矩形,而视口是矩形,若视口刚好在tile的曲线边缘外却识别为可见,就会创建冗余tile。 但上面那个简单版在zoomlevel低的时候地球边缘容易有识别不到的tile,造成黑色三角形。
  24816. //容易出现奇怪的mesh
  24817. /* this.isTileVisibleBox.makeEmpty()
  24818. this.isTileVisibleVec.set(e.x - r, e.y - r, e.z)
  24819. this.transformMapToLocal.forward(this.isTileVisibleVec)
  24820. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  24821. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  24822. this.isTileVisibleVec.set(e.x - r, e.y + r, e.z)
  24823. this.transformMapToLocal.forward(this.isTileVisibleVec)
  24824. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  24825. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  24826. this.isTileVisibleVec.set(e.x + r, e.y - r, e.z)
  24827. this.transformMapToLocal.forward(this.isTileVisibleVec)
  24828. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  24829. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec)
  24830. this.isTileVisibleVec.set(e.x + r, e.y + r, e.z)
  24831. this.transformMapToLocal.forward(this.isTileVisibleVec)
  24832. this.isTileVisibleVec.applyMatrix4(this.objectGroup.matrixWorld)
  24833. this.isTileVisibleBox.expandByPoint(this.isTileVisibleVec) */
  24834. return i.intersectsBox(this.isTileVisibleBox);
  24835. }
  24836. addToSceneGroup(t) {
  24837. this.objectGroupAdded || (t.add(this.objectGroup), this.objectGroupAdded = !0);
  24838. }
  24839. removeFromSceneGroup(t) {
  24840. this.baseTile.remove(), this.objectGroupAdded && (t.remove(this.objectGroup), this.objectGroupAdded = !1);
  24841. }
  24842. }
  24843. var loadDone = (tile, success) => {
  24844. tile.map.mapLayer.loadingInProgress--;
  24845. tile.map.loadingInProgress--;
  24846. //console.log('loaddone', tile.name, 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now())
  24847. tile.loading = false;
  24848. var next = tile.map.mapLayer.waitQueue[0];
  24849. if (next) {
  24850. addLoadTile(next);
  24851. } else {
  24852. if (tile.map.mapLayer.loadingInProgress == 0) {
  24853. //注意这时候不一定就加载完了,300ms后可能还会有新的tile加载
  24854. //console.log('loadDone All ?', Date.now())
  24855. tile.map.mapLayer.dispatchEvent('loadDone');
  24856. }
  24857. }
  24858. tile.mesh && (tile.mesh.material.needsUpdate = true);
  24859. };
  24860. function addLoadTile(tile) {
  24861. /* if(tile.texURL && tile.texURL.includes('testdata') ){
  24862. console.error('addLoadTile', tile.texURL.split('map_tiles/')[1] )
  24863. } */
  24864. if (tile.map.loadingInProgress < tile.map.maxLoading) {
  24865. if (!tile.mesh) return; //有时候会遇到这种情况, 为什么没有被cancelLoad呢?
  24866. tile.map.mapLayer.loadingInProgress++;
  24867. tile.map.loadingInProgress++;
  24868. tile.map.mapLayer.dispatchEvent('startLoad');
  24869. //console.log('addLoad', 'loadingInProgress',tile.map.mapLayer.loadingInProgress, Date.now())
  24870. //tile.texURL && tile.texURL.includes('testdata') && console.log('startloadTile ', tile.texURL.split('map_tiles/')[1] )
  24871. tile.loading = true;
  24872. var index = tile.map.mapLayer.waitQueue.indexOf(tile);
  24873. index > -1 && tile.map.mapLayer.waitQueue.splice(index, 1);
  24874. var tex = tile.mesh.material.map = texLoader$2.load(tile.texURL, tex => {
  24875. //如果一直加载不了会影响其他的加载,如google地图没有vpn会使全景图一直加载不了
  24876. if (tile.mesh) {
  24877. //如果还要显示的话
  24878. tile.textureLoaded = true;
  24879. tile.mesh.material.opacity = 1;
  24880. tile.map.mapLayer.viewer.mapChanged = true;
  24881. tile.map.mapLayer.needUpdate = true; //表示还要继续update(以removeChildren)
  24882. if (tile.map instanceof TiledMapOpenStreetMap) {
  24883. tile.map.maxLoading = browser.isMobile() ? 5 : 10;
  24884. }
  24885. } else {
  24886. //tile.texURL && tile.texURL.includes('testdata') && console.log('loadDone and dispose', tile.texURL.split('map_tiles/')[1] )
  24887. tex.dispose();
  24888. }
  24889. loadDone(tile, true);
  24890. }, void 0, () => {
  24891. //error
  24892. tile.textureLoaded = !0;
  24893. if (tile.mesh) {
  24894. tile.mesh.material.dispose();
  24895. tile.mesh.material = errorMaterial;
  24896. tile.map.mapLayer.viewer.mapChanged = true;
  24897. }
  24898. loadDone(tile, false);
  24899. tile.map.loadFailCount++;
  24900. if (tile.map instanceof TiledMapOpenStreetMap && Potree.settings.mapCompany == 'google' && tile.map.loadFailCount > 3) {
  24901. //极有可能没有vpn为了防止影响到其他资源加载,减少加载的个数
  24902. tile.map.maxLoading = 2;
  24903. }
  24904. });
  24905. tex.anisotropy = 0;
  24906. tex.generateMipmaps = !1;
  24907. tex.minFilter = LinearFilter;
  24908. tex.magFilter = LinearFilter;
  24909. } else {
  24910. tile.map.mapLayer.waitQueue.includes(tile) || tile.map.mapLayer.waitQueue.push(tile);
  24911. }
  24912. }
  24913. function cancelLoad(tile, log) {
  24914. //如果等待加载,但还没开始加载,取消加载
  24915. if (!tile.loading) {
  24916. var index = tile.map.mapLayer.waitQueue.indexOf(tile);
  24917. index > -1 && tile.map.mapLayer.waitQueue.splice(index, 1);
  24918. //index > -1 && tile.texURL && tile.texURL.includes('testdata') && console.log('cancelLoad', tile.texURL.split('map_tiles/')[1]/* , (log && waitQueue.indexOf(tile)>-1) ? log:'' , tile.loading */ )
  24919. }
  24920. }
  24921. class MapTile {
  24922. constructor(map, e, n, parent, name) {
  24923. this.map = map;
  24924. this.name = name;
  24925. this.parent = parent;
  24926. this.objectGroup = e, this.tileColor = n, this.meshAdded = !1, this.textureLoaded = !1, this.children = [];
  24927. this.id = getSid();
  24928. }
  24929. update(e, n, i, r, o, a, s) {
  24930. return !!this.doesNotContainTilesToBeDisplayed(e) || (0 === i ? this.updateTile(e, r, o, a) : this.updateSubTiles(e, n, i, r, o, a, s));
  24931. }
  24932. doesNotContainTilesToBeDisplayed(t) {
  24933. return t.tilePresenceMap && t.tilePresenceMap.empty;
  24934. }
  24935. updateTile(t, e, n, i) {
  24936. //真正显示mesh的是这一层,最高level
  24937. //if(this.map.name.includes('floorplan'))console.log('updateTile',this.name)
  24938. if (!this.mesh) {
  24939. this.createTileObject(t, e, n, i);
  24940. }
  24941. if (!this.meshAdded) {
  24942. this.objectGroup.add(this.mesh);
  24943. this.meshAdded = !0;
  24944. }
  24945. if (this.textureLoaded) {
  24946. //贴图加载完就不需要子集了
  24947. this.removeChildren();
  24948. } else {
  24949. this.cancelChildren(); //add 停止加载子集
  24950. }
  24951. return this.textureLoaded;
  24952. }
  24953. updateSubTiles(entity, n, level, o, a, s, c) {
  24954. //if(entity.name.includes('floorplan'))console.log('updateSubTiles',this.name) //名字越长代表level越高
  24955. for (var childrenLoaded = !0, u = [-.25 * o, .25 * o, -.25 * o, .25 * o], d = [.25 * o, .25 * o, -.25 * o, -.25 * o], p = 0; p < 4; ++p) {
  24956. var h = c + p.toString(10);
  24957. //一级(512):0 1 2 3分别为左上、右上、左下、右下。二级(1024)就是把一级的每一块分裂,如00 01 02 03分别是0的左上、右上、左下、右下……
  24958. if (!entity.tilePresenceMap || entity.tilePresenceMap[h]) {
  24959. //去掉判断,直接显示
  24960. var f = a + u[p],
  24961. m = s + d[p];
  24962. tempVector.set(f, m, 0);
  24963. this.map.computeCount++;
  24964. //console.log(this.map.computeCount, this.name, 'level:',level)
  24965. if (entity.isTileVisible(tempVector, .5 * o, n)) {
  24966. this.children[p] || (this.children[p] = new MapTile(this.map, this.objectGroup, this.tileColor, this, this.name + p));
  24967. //childrenLoaded = childrenLoaded && this.children[p].update(entity, n, level - 1, .5 * o, f, m, h) //这句会使若有一个tile还在加载,就阻断了。原版是这么写的。但是为了加快加载速度,改成下面两行。感觉直接全部updateTile也没太卡,不知道很大的场景会不会卡,单帧updateTile次数超过100次的话(应该不会吧,地图大小会限制住个数) -- 2023.12
  24968. var childLoaded = this.children[p].update(entity, n, level - 1, .5 * o, f, m, h);
  24969. childrenLoaded = childrenLoaded && childLoaded;
  24970. } else {
  24971. if (this.children[p]) {
  24972. this.children[p].remove();
  24973. delete this.children[p];
  24974. }
  24975. }
  24976. }
  24977. }
  24978. return childrenLoaded && this.removeObject3D(), childrenLoaded; //子项加载完,母项mesh可以去除。(最后母项的母项以及前面的都会被删除,只留最后的叶子结点)
  24979. }
  24980. /*
  24981. 一层层往后加载。加入第一次加载到第4层(因为level精细度是第4层),给第4层可见tile加上mesh。
  24982. 然后下一次加载到第5层,那么第4层的mesh就要被清空(当它所属的第5层子集都加载完后)
  24983. */
  24984. createTileObject(t, e, n, a) {
  24985. var s = this;
  24986. this.mesh = this.createMesh(t.transformMapToLocal, e, n, a), this.textureLoaded = !1;
  24987. var c = t.mapSizeM / e,
  24988. l = Math.log(c) / Math.log(2),
  24989. u = n / e + .5 * (c - 1),
  24990. d = -a / e + .5 * (c - 1),
  24991. p = t.getTileUrl(Math.round(l), Math.round(u), Math.round(d));
  24992. Potree.Utils.setObjectLayers(this.mesh, 'map');
  24993. this.mesh.renderOrder = -(1e6 - l - 100 * (t.zIndex || 0));
  24994. this.mesh.name = this.name; //add
  24995. this.texURL = p;
  24996. /* let area = math.getArea(this.mesh.geometry.vertices.slice(0,3));
  24997. if(area >0){
  24998. this.mesh.visible = false
  24999. console.log('area>0',this.mesh.name)
  25000. } */
  25001. addLoadTile(this);
  25002. }
  25003. createMesh(t, e, n, o) {
  25004. var a = new Geometry();
  25005. return tempVector.set(n - e / 2, o - e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n + e / 2, o - e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n + e / 2, o + e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), tempVector.set(n - e / 2, o + e / 2, 0), a.vertices.push(new Vector3().copy(t.forward(tempVector))), a.faces.push(face1), a.faces.push(face2), a.faceVertexUvs[0].push(face1UV), a.faceVertexUvs[0].push(face2UV), new Mesh(a, this.createMaterial());
  25006. }
  25007. createMaterial() {
  25008. var t = new MeshBasicMaterial({
  25009. transparent: !0,
  25010. depthWrite: !1,
  25011. depthTest: !0,
  25012. opacity: 0,
  25013. side: DoubleSide
  25014. });
  25015. if (Potree.settings.isTest) {
  25016. var colorHue = Math.random();
  25017. t.color = new Color().setHSL(colorHue, 0.6, 0.92);
  25018. } else {
  25019. t.color = this.tileColor ? this.tileColor : new Color(16777215);
  25020. }
  25021. return t;
  25022. }
  25023. traverse(f) {
  25024. //add
  25025. return Mesh.prototype.traverse.call(this, f);
  25026. }
  25027. remove() {
  25028. this.removeObject3D(), this.removeChildren();
  25029. }
  25030. removeObject3D() {
  25031. var hasMesh = !!this.mesh;
  25032. if (this.mesh) {
  25033. this.objectGroup.remove(this.mesh);
  25034. if (this.textureLoaded) {
  25035. var t = this.mesh.material.map;
  25036. t && t.dispose();
  25037. } else {
  25038. cancelLoad(this);
  25039. }
  25040. this.mesh.material.dispose(); //o.disposeMeshMaterial(this.mesh),
  25041. this.mesh.geometry.dispose();
  25042. this.mesh = void 0;
  25043. }
  25044. this.meshAdded = !1, this.textureLoaded = !1;
  25045. //this.texURL && this.texURL.includes('testdata') && console.log('removeObject3D', this.id, 'hasMesh',hasMesh, this.texURL.split('map_tiles/')[1] )
  25046. }
  25047. removeChildren() {
  25048. for (var t = 0, e = this.children; t < e.length; t++) {
  25049. var n = e[t];
  25050. n && (n.removeObject3D(), n.removeChildren());
  25051. }
  25052. this.children.length = 0;
  25053. }
  25054. cancelChildren() {
  25055. //子集全部停止加载
  25056. for (var t = 0, e = this.children; t < e.length; t++) {
  25057. var n = e[t];
  25058. n && (cancelLoad(n, '提前'), n.cancelChildren());
  25059. }
  25060. }
  25061. }
  25062. proj4.defs("EPSG:3857", "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");
  25063. //这里地图世界的中心是不是lon:0,lat:0
  25064. class TiledMapOpenStreetMap extends TiledMapBase {
  25065. constructor(mapLayer, tileColor) {
  25066. //Potree.settings.mapCompany = 'google'
  25067. super('map', mapLayer, tileColor /* , projection */); //EPSG projection
  25068. //this.baseUrl = "https://wprd03.is.autonavi.com/appmaptile?style=7&x=${x}&y=${y}&z=${z}",
  25069. //this.baseUrl = "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x=${x}&y=${y}&z=${z}" //最高只到18 level
  25070. this.switchStyle();
  25071. this.tileSizePx = 256;
  25072. this.mapSizeM = 40075017; //总占据多少米(地球赤道周长) 和三维空间的不一样 - -, 空间上的是直径,地图上的是半个圆周
  25073. this.bias = 0.5;
  25074. if (Potree.settings.mapCompany == 'google') {
  25075. this.attribution = "© PopSmart, © 谷歌地图";
  25076. this.projection = "EPSG:900913"; //"EPSG:4326"//4550
  25077. } else {
  25078. this.attribution = "© PopSmart, © 高德地图";
  25079. this.projection = "EPSG:3857";
  25080. }
  25081. }
  25082. getTileUrl(t, e, n) {
  25083. return this.baseUrl.replace(/\${z}/, t.toString(10)).replace(/\${x}/, e.toString(10)).replace(/\${y}/, n.toString(10));
  25084. }
  25085. switchStyle() {
  25086. var style = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'standard';
  25087. //if(Potree.settings.mapCompany == 'google')return
  25088. if (style == this.style) return;
  25089. if (Potree.settings.mapCompany == 'google') {
  25090. if (style == 'satellite') {
  25091. //卫星
  25092. this.baseUrl = "https://mt2.google.com/vt/lyrs=y@159000000&hl=zh-CN&gl=cn&x=${x}&y=${y}&z=${z}&s=mt1"; /* "http://mt2.google.cn/vt/lyrs=m@177000000&hl=zh-CN&gl=cn&src=app&x=${x}&y=${y}&z=${z}" */ //最高只到19
  25093. this.maxDepth = 22;
  25094. } else {
  25095. this.baseUrl = "https://mt2.google.com/vt/lyrs=m@159000000&hl=zh-CN&gl=cn&x=${x}&y=${y}&z=${z}&s=mt1"; /* "http://mt2.google.cn/vt/lyrs=m@177000000&hl=zh-CN&gl=cn&src=app&x=${x}&y=${y}&z=${z}" */ //最高只到19
  25096. this.maxDepth = 22;
  25097. }
  25098. /* 1)lyrs= 表示的是图层类型,即瓦片类型,具体含义如下:
  25099. m:路线图
  25100. t:地形图
  25101. p:带标签的地形图
  25102. s:卫星图
  25103. y:带标签的卫星图
  25104. h:标签层(路名、地名等)
  25105. 2)& gl=CN
  25106. 谷歌地图针对中国有两套坐标,一套做了偏移,一套没有。经测试在url加入gl=cn地图会有偏移。
  25107. Tips:如果谷歌地图和RTK测量的WGS84坐标有偏差,可以尝试在url里去掉& gl=cn。
  25108. 5)&hl=
  25109. 设置地图注记文字语言类型,缺省默认为中文。
  25110. hl=nl 中英双语
  25111. hl=zh-CN 中文
  25112. */
  25113. } else {
  25114. //baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}" //卫星 maxDepth = 18
  25115. //搜索高德地图瓦片url
  25116. if (Potree.settings.isJiangMen) {
  25117. if (style == 'satellite') {
  25118. //卫星
  25119. this.maxDepth = 18;
  25120. this.baseUrl = "http://a.map.jms.gd/tile/weixing/${z}/${x}/${y}.png";
  25121. } else {
  25122. this.maxDepth = 19;
  25123. this.baseUrl = "http://a.map.jms.gd/tile/gd_xiangtu/${z}/${x}/${y}.png";
  25124. }
  25125. } else {
  25126. if (style == 'satellite') {
  25127. //卫星
  25128. this.maxDepth = 18;
  25129. this.baseUrl = "https://webst01.is.autonavi.com/appmaptile?lang=zh_cn&style=6&yrs=m&x=${x}&y=${y}&z=${z}";
  25130. } else {
  25131. this.maxDepth = 19;
  25132. this.baseUrl = "https://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&style=7&yrs=m&x=${x}&y=${y}&z=${z}"; //
  25133. }
  25134. }
  25135. }
  25136. this.style = style;
  25137. this.setEnable(false);
  25138. this.setEnable(true);
  25139. viewer.dispatchEvent('content_changed');
  25140. }
  25141. }
  25142. class TiledMapFromEntity extends TiledMapBase {
  25143. constructor(mapLayer, tileColor, data) {
  25144. super('floorplan', mapLayer, tileColor, "LOCAL" /* "EPSG:3857" */ /* "WGS84" */); //直接就是本地坐标,没有projec
  25145. var entity = this.tiledMapEntity = this.fillFromData(data);
  25146. var time = entity.updateTime || entity.createTime;
  25147. this.tileSizePx = entity.tileSizePx, this.mapSizeM = entity.mapSizeM, this.maxDepth = entity.maxDepth;
  25148. this.postStamp = time ? time.replace(/[^0-9]/ig, '') : new Date().getTime();
  25149. //this.projection = n.crsLocal,
  25150. this.zIndex = 0, this.tilePresenceMap = this.decodeBitStream(this.tiledMapEntity.quadtree); //包含tile分裂信息,如果写错了会造成tile显示不全
  25151. this.maxLoading = 5;
  25152. this.bias = 0.5; //越大加载层级越低,越模糊
  25153. if (window.devicePixelRatio >= 2 && window.innerHeight * window.innerWidth < 768 * 1024) {
  25154. //手机还是加载高清点(反正也不需要截图等待),但平板太大了,要铺满屏幕可能慢,所以稍微模糊点?(反正可以继续放大去看)
  25155. this.bias = 0; //level更高些
  25156. }
  25157. }
  25158. fillFromData(e) {
  25159. var data = {};
  25160. data.id = e.id;
  25161. data.globalLocation = Potree.Utils.VectorFactory.fromArray3(e.location);
  25162. data.orientation = Potree.Utils.QuaternionFactory.fromArray(e.orientation);
  25163. var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == e.datasetId);
  25164. if (pointcloud.datasetData.mapping) {
  25165. data.filePath = "".concat(Potree.settings.urls.prefix1, "/").concat(pointcloud.datasetData.mapping).concat(e.file_path);
  25166. } else {
  25167. data.filePath = "".concat(Potree.settings.urls.prefix1).concat(e.file_path);
  25168. }
  25169. data.fileName = '$DEPTH/$X/$Y.png';
  25170. data.type = e.type, data.mapSizeM = e.map_size_m, data.tileSizePx = e.tile_size_px, data.maxDepth = e.max_depth, data.quadtree = e.quadtree, data.floorId = e.floor_id, data.bundleId = e.bundle_id;
  25171. //this.computeLocalCoordinates()
  25172. return data;
  25173. }
  25174. computeLocalCoordinates() {
  25175. if (proj4.defs("LOCAL_MAP")) {
  25176. var lonlat = this.tiledMapEntity.globalLocation;
  25177. /* if(window.AMapWith84){//需要转换
  25178. lonlat = AMapWith84.wgs84ToAMap(lonlat)
  25179. } */
  25180. lonlat = viewer.transform.lonlatToLocal.forward(lonlat);
  25181. this.tiledMapEntity.location = new Vector3().copy(lonlat);
  25182. }
  25183. }
  25184. updateProjection() {
  25185. super.updateProjection();
  25186. if (!this.position) {
  25187. this.computeLocalCoordinates();
  25188. }
  25189. /* this.projection = this.TransformService.crsLocal,
  25190. t.prototype.updateProjection.call(this) */
  25191. }
  25192. get position() {
  25193. return this.tiledMapEntity.location;
  25194. /* enumerable: !0,
  25195. configurable: !0 */
  25196. }
  25197. get quaternion() {
  25198. return this.tiledMapEntity.orientation;
  25199. /* enumerable: !0,
  25200. configurable: !0 */
  25201. }
  25202. getTileUrl(t, e, n) {
  25203. var i = (this.tiledMapEntity.filePath + "/" + this.tiledMapEntity.fileName).replace(/\$DEPTH/g, t.toString(10)).replace(/\$X/g, e.toString(10)).replace(/\$Y/g, n.toString(10));
  25204. return i += "?t=" + this.postStamp;
  25205. //this.RestService.addAuthorizationQueryParameter(i) //????
  25206. }
  25207. decodeBitStream(t) {
  25208. if (!t) return {
  25209. empty: !0
  25210. };
  25211. for (var e = {}, n = [e], i = 0; i < t.length; i++) {
  25212. var r = n.shift(),
  25213. o = parseInt(t.substr(i, 1), 16);
  25214. if (1 & o) {
  25215. var a = {};
  25216. r[0] = a, n.push(a);
  25217. }
  25218. 2 & o && (a = {}, r[1] = a, n.push(a)), 4 & o && (a = {}, r[2] = a, n.push(a)), 8 & o && (a = {}, r[3] = a, n.push(a));
  25219. }
  25220. var s = {
  25221. empty: !0
  25222. };
  25223. return this.computeHashes(s, e, ""), s;
  25224. }
  25225. computeHashes(t, e, n) {
  25226. for (var i = 0; i < 4; i++) e[i] && (t[n + i.toString(10)] = !0, t.empty = !1, this.computeHashes(t, e[i], n + i.toString(10)));
  25227. }
  25228. }
  25229. /*
  25230. note:
  25231. 目前缩小了能看出形态是一个地球。相机在高空朝下观测,地球平放着。
  25232. 所以越靠近赤道和地球朝上的那面所在的中央经度(也就是local 0,0,0所对应的初始经度),tile越接近正方形。
  25233. 所以在两极地区要怎么显示?
  25234. 注册地理坐标时需要滚动地球吗?(修改初始经度、重定义NAVVIS:TMERC, 就需要更新所有三维世界中的物体位置)
  25235. 切换中心点:
  25236. var locationLonLat = viewer.transform.lonlatToLocal.inverse(viewer.mapViewer.camera.position.clone())
  25237. proj4.defs("LOCAL_MAP", "+proj=tmerc +ellps=WGS84 +lon_0=" + locationLonLat.x.toPrecision(15) + " +lat_0=" + locationLonLat.y.toPrecision(15));
  25238. viewer.mapViewer.mapLayer.maps[0].transformMapToLocal = null
  25239. 地理注册部分地图上的1和2标记有两层意思。当地图全屏展示时,标记的是当前右侧经纬度的位置;当地图为小窗时,标记的是对应场景里三维位置。(所以感觉最好换一个ui?)且在2023.2.1之前才改好,之前都是后者。
  25240. 为什么边缘总是有奇怪的mesh,是因为有顶点到背面了吗
  25241. https://lbs.amap.com/tools/picker 高德坐标拾取器(手机登录),但和这里展示的不一样, 要用AMapWith84.aMapToWgs84({x: ,y: })转成84。 (qq or 手机登录) 所以potree本地和有AMapWith84函数的laser地图展现不一样
  25242. https://www.google.com/maps/@77.7730021,-34.4952712,4z google取点
  25243. 打印所有mapTile的名字,字符串最长的代表有显示的mesh。
  25244. viewer.mapViewer.mapLayer.maps[0].baseTile.traverse(function(e){console.log(e.name)})
  25245. 能查看有几个显示的mesh
  25246. viewer.mapViewer.mapLayer.maps[0].objectGroup.children
  25247. 图片地址中 tiles/4/3/9.png 第一个数字越高代表level越高,放得越大 . (tile.name.length也能反映出
  25248. viewer.mapViewer.mapLayer.maps[1].objectGroup.children.map(e=>e.name.length-1)
  25249. 目前看的几个场景floorplan原图是1米=33.03个像素 图宽度= 512*2^(max_depth-1) , map_size_m 代表整个地图是多少米
  25250. 经纬度精度小数点后5位为米级别,6位为分米,7位是厘米
  25251. */
  25252. /**
  25253. * @author mschuetz / http://mschuetz.at
  25254. *
  25255. * adapted from THREE.OrbitControls by
  25256. *
  25257. * @author qiao / https://github.com/qiao
  25258. * @author mrdoob / http://mrdoob.com
  25259. * @author alteredq / http://alteredqualia.com/
  25260. * @author WestLangley / http://github.com/WestLangley
  25261. * @author erich666 / http://erichaines.com
  25262. *
  25263. *
  25264. *
  25265. */
  25266. var Buttons = Potree.defines.Buttons;
  25267. class FirstPersonControls extends EventDispatcher {
  25268. constructor(viewer, viewport) {
  25269. var _this;
  25270. super();
  25271. _this = this;
  25272. this.viewer = viewer;
  25273. this.renderer = viewer.renderer;
  25274. this.scene = viewer.scene;
  25275. this.rotationSpeed = 200;
  25276. this.moveSpeed = 10;
  25277. this.setCurrentViewport({
  25278. hoverViewport: viewport,
  25279. force: true
  25280. }); //this.currentViewport = viewport
  25281. this.keys = {
  25282. FORWARD: ['W'.charCodeAt(0), 38],
  25283. BACKWARD: ['S'.charCodeAt(0), 40],
  25284. LEFT: ['A'.charCodeAt(0), 37],
  25285. RIGHT: ['D'.charCodeAt(0), 39],
  25286. UP: ['Q'.charCodeAt(0)],
  25287. DOWN: ['E'.charCodeAt(0)],
  25288. //SHIFT : [16],
  25289. ALT: [18],
  25290. SPACE: [32],
  25291. Rotate_LEFT: ['L'.charCodeAt(0)],
  25292. Rotate_RIGHT: ['J'.charCodeAt(0)],
  25293. Rotate_UP: ['K'.charCodeAt(0)],
  25294. Rotate_DOWN: ['I'.charCodeAt(0)]
  25295. };
  25296. this.fadeFactor = 20;
  25297. this.yawDelta = 0;
  25298. this.pitchDelta = 0;
  25299. this.translationDelta = new Vector3(0, 0, 0);
  25300. this.translationWorldDelta = new Vector3(0, 0, 0);
  25301. this.tweens = [];
  25302. this.dollyStart = new Vector2();
  25303. this.dollyEnd = new Vector2();
  25304. //this.enableChangePos = true
  25305. this.viewer.addEventListener('camera_changed', e => {
  25306. if (this.viewer.name == 'mapViewer' || e.changeInfo && e.changeInfo.positionChanged && !viewer.mainViewport.view.isFlying()) {
  25307. this.setFPCMoveSpeed(e.viewport);
  25308. }
  25309. });
  25310. var drag = e => {
  25311. if (!this.enabled) return;
  25312. var viewport = e.dragViewport;
  25313. if (!viewport) return;
  25314. var camera = viewport.camera;
  25315. var mode;
  25316. if (e.isTouch) {
  25317. if (e.touches.length == 1) {
  25318. mode = !e.dragViewport || e.dragViewport.name == 'MainView' ? 'rotate' : 'pan';
  25319. } else if (e.touches.length == 2) {
  25320. mode = Potree.settings.displayMode == 'showPanos' ? 'scale' : 'pan-scale';
  25321. } else {
  25322. mode = !e.dragViewport || e.dragViewport.name == 'MainView' ? 'pan' : 'scale';
  25323. }
  25324. } else {
  25325. //mode = e.buttons === Buttons.LEFT && (!e.dragViewport || e.dragViewport.name == 'MainView') ? 'rotate' : 'pan'
  25326. mode = e.buttons === Buttons.LEFT && camera.type != 'OrthographicCamera' ? 'rotate' : 'pan';
  25327. }
  25328. //console.log('mode ', mode )
  25329. var moveSpeed = this.currentViewport.getMoveSpeed();
  25330. if (e.drag.startHandled === undefined) {
  25331. ///???????
  25332. e.drag.startHandled = true;
  25333. this.dispatchEvent({
  25334. type: 'start'
  25335. });
  25336. }
  25337. if (mode.includes('rotate')) {
  25338. //旋转
  25339. //来自panoramaControl updateRotation
  25340. if (!this.pointerDragStart) {
  25341. return this.pointerDragStart = e.pointer.clone();
  25342. }
  25343. var view = this.scene.view;
  25344. if (this.rotateStartInfo.rotAroundPoint) {
  25345. //定点旋转: 以当前intersect的点为target旋转,不改点在屏幕中的位置
  25346. var distance = camera.position.distanceTo(this.rotateStartInfo.rotCenter /* this.intersectStart.location */); //不按下ctrl的话
  25347. var posDir = new Vector3().subVectors(this.rotateStartInfo.rotCenter, view.position);
  25348. if (posDir.dot(view.direction) < 0) distance *= -1; //在背面
  25349. //按照orbitControl的方式旋转:
  25350. var rotationSpeed = 2;
  25351. this.yawDelta -= e.drag.pointerDelta.x * rotationSpeed;
  25352. this.pitchDelta += e.drag.pointerDelta.y * rotationSpeed;
  25353. /* //旋转方向和偏移量尽量和在漫游点处旋转方式的一样
  25354. this.yawDelta += e.drag.pointerDelta.x / 500 * viewport.resolution.x
  25355. this.pitchDelta -= e.drag.pointerDelta.y / 500 * viewport.resolution.y */
  25356. //先更新一下相机:
  25357. this.update();
  25358. view.applyToCamera(camera);
  25359. //然后得到新的相机角度下,原先点在屏幕中的位置所对应的3d点现在的坐标。只需要平移一下新旧坐标差值即可。//感觉貌似也可以用project和unproject后的差值的方式,还不用判断z背面
  25360. var newPointerDir = viewer.inputHandler.getMouseDirection(this.rotateStartInfo.rotCenter2d).direction.clone().multiplyScalar(distance);
  25361. var pivot = new Vector3().addVectors(camera.position, newPointerDir); //新的3d点
  25362. var moveVec = new Vector3().subVectors(pivot, this.rotateStartInfo.rotCenter);
  25363. this.translationWorldDelta.copy(moveVec.negate());
  25364. //立即更新下,防止因update和此drag频率不同而打滑。
  25365. this.update();
  25366. view.applyToCamera(camera);
  25367. } else {
  25368. var _matrixWorld = camera.matrixWorld;
  25369. camera.matrixWorld = new Matrix4(); //unproject 前先把相机置于原点
  25370. var e1 = new Vector3(this.pointerDragStart.x, this.pointerDragStart.y, -1).unproject(camera),
  25371. t = new Vector3(e.pointer.x, e.pointer.y, -1).unproject(camera),
  25372. i = Math.sqrt(e1.x * e1.x + e1.z * e1.z),
  25373. n = Math.sqrt(t.x * t.x + t.z * t.z),
  25374. o = Math.atan2(e1.y, i),
  25375. a = Math.atan2(t.y, n);
  25376. this.pitchDelta += o - a; //上下旋转
  25377. e1.y = 0, t.y = 0;
  25378. var s = Math.acos(e1.dot(t) / e1.length() / t.length());
  25379. if (!isNaN(s)) {
  25380. var yawDelta = s; //左右旋转
  25381. this.pointerDragStart.x > e.pointer.x && (yawDelta *= -1);
  25382. this.yawDelta += yawDelta;
  25383. }
  25384. //console.log('rotate:', this.pitchDelta, e.pointer.toArray(), this.pointerDragStart.toArray())
  25385. this.pointerDragStart.copy(e.pointer);
  25386. camera.matrixWorld = _matrixWorld;
  25387. }
  25388. }
  25389. if (mode.includes('pan')) {
  25390. //平移
  25391. if (!this.canMovePos(viewport)) {
  25392. return;
  25393. }
  25394. if (camera.type == "OrthographicCamera") {
  25395. //console.log(e.drag.pointerDelta, e.pointer, e.drag.end)
  25396. var _moveVec = Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, camera); //最近一次移动向量
  25397. var pointclouds;
  25398. var Alignment = window.viewer.modules.Alignment;
  25399. var MergeEditor = window.viewer.modules.MergeEditor;
  25400. var handleState = Alignment.handleState;
  25401. //右键平移视图、左键操作点云
  25402. var _a = e.buttons === Buttons.LEFT && viewport.alignment && handleState && viewport.alignment[handleState];
  25403. if (Potree.settings.editType == 'pano') {
  25404. var PanoEditor = window.viewer.modules.PanoEditor;
  25405. if (_a && PanoEditor.selectedPano) {
  25406. if ( /* !PanoEditor.selectedGroup || */!PanoEditor.checkIfAllLinked({
  25407. group: PanoEditor.selectedGroup
  25408. })) {
  25409. if (handleState == 'translate' && (e.drag.intersectStart.pointclouds && Common.getMixedSet(PanoEditor.selectedClouds, e.drag.intersectStart.pointclouds).length || PanoEditor.selectedPano.hovered) //平移时 拖拽到点云上 或 circle。(其中点云只需要intersect的点云中包含选择的点云中之一即可)
  25410. || handleState == 'rotate')
  25411. //旋转模式不需要intersect
  25412. {
  25413. pointclouds = PanoEditor.selectedClouds;
  25414. }
  25415. } else {
  25416. PanoEditor.dispatchEvent('needToDisConnect');
  25417. console.warn('选中的漫游点连通了整个数据集,不允许移动');
  25418. }
  25419. }
  25420. if (!pointclouds && e.buttons === Buttons.LEFT && viewport.rotateSide) {
  25421. //侧视图 (有时候会卡顿,是mousemove执行延迟了,一般发生在突然加载很多点云时)
  25422. //console.log('rotateSide', -e.drag.pointerDelta.x )
  25423. return PanoEditor.rotateSideCamera(-e.drag.pointerDelta.x);
  25424. }
  25425. } else if (Potree.settings.editType == 'merge') {
  25426. if (e.buttons === Buttons.LEFT && viewport.rotateSide) {
  25427. return MergeEditor.rotateSideCamera(-e.drag.pointerDelta.x);
  25428. }
  25429. } else {
  25430. /* if(Alignment.selectedClouds && Alignment.selectedClouds.length){//多个点云
  25431. pointclouds = a && e.drag.intersectStart.pointclouds && Common.getMixedSet(Alignment.selectedClouds, e.drag.intersectStart.pointclouds).length && Alignment.selectedClouds
  25432. }else{ */
  25433. //pointclouds = a && e.drag.intersectStart.pointcloud && [e.drag.intersectStart.pointcloud]
  25434. //}
  25435. if (_a && e.drag.intersectStart.pointcloud) {
  25436. pointclouds = [e.drag.intersectStart.pointcloud];
  25437. if (e.drag.intersectStart.pointcloud.dataset_id == Potree.settings.originDatasetId) {
  25438. var p = e.drag.intersectStart.pointclouds.find(p => p.dataset_id != Potree.settings.originDatasetId);
  25439. if (p) pointclouds = [p];
  25440. }
  25441. }
  25442. }
  25443. if (pointclouds) {
  25444. if (handleState == 'translate' && viewport.alignment.translateVec) {
  25445. //只能沿某个方向移动
  25446. _moveVec.projectOnVector(viewport.alignment.translateVec);
  25447. }
  25448. this.dispatchEvent({
  25449. type: "transformPointcloud",
  25450. intersect: e.intersect.orthoIntersect,
  25451. intersectStart: e.drag.intersectStart.orthoIntersect,
  25452. moveVec: _moveVec,
  25453. pointclouds,
  25454. camera
  25455. });
  25456. } else {
  25457. this.translationWorldDelta.add(_moveVec.negate());
  25458. }
  25459. } else {
  25460. //perspectiveCamera:
  25461. if (e.drag.intersectStart) {
  25462. //如果拖拽着点云
  25463. var ifInit = e.drag.z == void 0;
  25464. var pointerStartPos2d = e.drag.intersectStart.location.clone().project(camera); //识别到的点云点的位置
  25465. e.drag.z = pointerStartPos2d.z; //记录z,保持拖拽物体到屏幕距离不变,所以z深度不变(如果拖拽过程中没有缩放,这个z其实不变)
  25466. if (ifInit) {
  25467. //拖拽开始
  25468. e.drag.projectionMatrixInverse = camera.projectionMatrixInverse.clone();
  25469. //防止吸附到最近点上(因为鼠标所在位置并非识别到的点云点的位置,需要得到鼠标所在位置的3d坐标。)
  25470. var pointerStartPos2dReal = new Vector3(this.pointerDragStart.x, this.pointerDragStart.y, e.drag.z);
  25471. e.drag.translateStartPos = pointerStartPos2dReal.clone().unproject(camera);
  25472. //console.log('开始拖拽', e.pointer.clone())
  25473. }
  25474. //拖拽的过程中将projectionMatrixInverse替换成开始拖拽时的,因为near、far一直在变,会导致unproject计算出的3d坐标改变很大而闪烁。
  25475. var _projectionMatrixInverse = camera.projectionMatrixInverse;
  25476. camera.projectionMatrixInverse = e.drag.projectionMatrixInverse;
  25477. var newPos2d = new Vector3(e.pointer.x, e.pointer.y, e.drag.z);
  25478. var newPos3d = newPos2d.clone().unproject(camera);
  25479. var _moveVec2 = newPos3d.clone().sub(e.drag.translateStartPos /* e.drag.intersectStart.location */); //移动相机,保持鼠标下的位置永远不变,所以用鼠标下的新位置减去鼠标下的原始位置
  25480. camera.projectionMatrixInverse = _projectionMatrixInverse;
  25481. this.translationWorldDelta.copy(_moveVec2.negate()); //这里没法用add,原因未知,打开console时会跳动
  25482. //console.log('pan 1', this.translationWorldDelta.clone())
  25483. //四指松开剩三指时会偏移一下,暂不知道哪里的问题,或许跟开头防止点云吸附有关?
  25484. } else {
  25485. //如果鼠标没有找到和点云的交点,就假设移动整个模型(也可以去扩大范围寻找最近点云)
  25486. /* let center = viewer.scene.pointclouds[0].position;
  25487. let radius = camera.position.distanceTo(center);
  25488. let ratio = radius * Math.tan(THREE.Math.degToRad(camera.fov)/2) / 1000 */
  25489. /* let speed = this.currentViewport.getMoveSpeed()
  25490. if(FirstPersonControls.boundPlane){
  25491. speed = FirstPersonControls.boundPlane.distanceToPoint(this.currentViewport.position)
  25492. speed = Math.max(1 , speed)
  25493. } */
  25494. var lastIntersect = this.target || viewport.lastIntersect && (viewport.lastIntersect.location || viewport.lastIntersect); //该viewport的最近一次鼠标和点云的交点
  25495. if (!lastIntersect || !(lastIntersect instanceof Vector3)) lastIntersect = viewer.bound.center;
  25496. var speed = camera.position.distanceTo(lastIntersect);
  25497. var fov = cameraLight.getHFOVForCamera(camera, true);
  25498. var ratio = speed * Math.tan(fov / 2);
  25499. this.translationDelta.x -= e.drag.pointerDelta.x * ratio;
  25500. this.translationDelta.z -= e.drag.pointerDelta.y * ratio;
  25501. //console.log('pan2', e.drag.pointerDelta)
  25502. }
  25503. }
  25504. this.useAttenuation = false;
  25505. }
  25506. if (mode.includes('scale')) {
  25507. //触屏缩放
  25508. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  25509. //if(!this.dollyStart)return
  25510. var scale = this.dollyEnd.length() / this.dollyStart.length();
  25511. var pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点
  25512. dolly({
  25513. pointer,
  25514. scale,
  25515. camera,
  25516. drag: e.drag
  25517. });
  25518. this.dollyStart.copy(this.dollyEnd);
  25519. }
  25520. //最好按ctrl可以变为dollhouse的那种旋转
  25521. };
  25522. var drop = e => {
  25523. if (!this.enabled) return;
  25524. this.dispatchEvent({
  25525. type: 'end'
  25526. });
  25527. };
  25528. var dolly = function dolly() {
  25529. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  25530. if (Potree.settings.displayMode == 'showPanos' && _this.currentViewport == viewer.mainViewport /* this.currentViewport.unableChangePos */) {
  25531. //全景时
  25532. _this.dispatchEvent({
  25533. type: 'dollyStopCauseUnable',
  25534. delta: e.delta,
  25535. scale: e.scale
  25536. });
  25537. return;
  25538. }
  25539. var camera = e.camera;
  25540. if (camera.type == "OrthographicCamera") {
  25541. var ratio;
  25542. if (e.delta != void 0) {
  25543. //滚轮缩放
  25544. if (e.delta == 0) {
  25545. //mac
  25546. return;
  25547. } else if (e.delta < 0) {
  25548. ratio = 0.9;
  25549. } else if (e.delta > 0) {
  25550. ratio = 1.12; //增加的需要比减少的多一些,否则缩放相同次数下,r0 * ([1+s)(1-s)]^n = r0 * (1-s^2)^n < r0
  25551. }
  25552. } else {
  25553. ratio = e.scale; //触屏缩放
  25554. }
  25555. var zoom = camera.zoom * ratio;
  25556. var limit = camera.zoomLimit;
  25557. if (limit) zoom = MathUtils.clamp(zoom, limit.min, limit.max);
  25558. var pointerPos = new Vector3(e.pointer.x, e.pointer.y, 0.5);
  25559. var oldPos = pointerPos.clone().unproject(camera);
  25560. if (camera.zoom != zoom) {
  25561. camera.zoom = zoom;
  25562. camera.updateProjectionMatrix();
  25563. }
  25564. var newPos = pointerPos.clone().unproject(camera);
  25565. //定点缩放, 恢复一下鼠标所在位置的位置改变量
  25566. var moveVec = new Vector3().subVectors(newPos, oldPos);
  25567. _this.translationWorldDelta.add(moveVec.negate());
  25568. _this.useAttenuation = false;
  25569. } else {
  25570. var speed = _this.currentViewport.getMoveSpeed() * 7,
  25571. direction;
  25572. if (e.delta != void 0) {
  25573. //滚轮缩放
  25574. if (e.delta == 0) return; //mac
  25575. /*if(this.target && !e.intersect){//如果没有intersect点云且有target的话,就朝target的方向. 但无限靠近时有问题,且到背面时前进却是后退
  25576. direction = new THREE.Vector3().subVectors(this.target, camera.position).normalize()
  25577. }else{ */
  25578. direction = _this.viewer.inputHandler.getMouseDirection().direction; //定点缩放
  25579. if (e.intersect && e.intersect.location) {
  25580. //和intersect的墙越接近,速度越慢,便于focus细节
  25581. var dis = camera.position.distanceTo(e.intersect.location);
  25582. speed = MathUtils.clamp(dis * 0.1, 0.3, speed);
  25583. }
  25584. if (e.delta < 0) {
  25585. speed *= -1;
  25586. }
  25587. var slightly = _this.keys.ALT.some(e => _this.viewer.inputHandler.pressedKeys[e]);
  25588. slightly && (speed *= 0.2);
  25589. _this.useAttenuation = true;
  25590. } else {
  25591. //触屏缩放
  25592. direction = _this.viewer.inputHandler.getMouseDirection(e.pointer).direction; //定点缩放
  25593. if (e.drag.intersectStart) {
  25594. //和intersect的墙越接近,速度越慢,便于focus细节
  25595. var _dis = camera.position.distanceTo(e.drag.intersectStart.location);
  25596. var r = 1 - 1 / e.scale;
  25597. var closeMin = 0.1,
  25598. standardMin = 0.001,
  25599. disBound1 = 2,
  25600. disBound2 = 5;
  25601. if (math.closeTo(e.scale, 1, 0.03)) {
  25602. //如果偏差小于0.01,就不限制最小值,因为平移容易正负抖动,近距离有最小值的话抖动明显
  25603. closeMin = 0; //所以若缩放不明显(双指滑动慢),就不设置最低值。(这时候穿越障碍物会比较困难。)
  25604. }
  25605. //console.log('closeMin',closeMin)
  25606. var min = math.linearClamp(_dis, [disBound1, disBound2], [closeMin, standardMin]); //触屏和滚轮不一样,触发较为连续,所以最小值设低一点。若要保持双指相对点云位置不变,理想最小值是0,但那样就无法穿越点云(最小值太小的话穿越密集点云如树丛很困难;太大会打滑)所以当离点云近时增大最小值
  25607. speed = Math.sign(r) * MathUtils.clamp(_dis * Math.abs(r), min, speed);
  25608. //console.log(speed, dis, e.scale)
  25609. } else {
  25610. _this.useAttenuation = true;
  25611. var accelerate = 40;
  25612. if (math.closeTo(e.scale, 1, 0.02)) {
  25613. //缩放小的时候很可能是双指平移时,容易抖动,所以降低移动速度
  25614. accelerate *= Math.min(40 * Math.abs(e.scale - 1), 0.8);
  25615. }
  25616. // console.log('accelerate',accelerate)
  25617. var constantDis = _this.currentViewport.getMoveSpeed() * accelerate; //constantDis = 10;//常量系数,当放大一倍时前进的距离。可以调整
  25618. speed = (e.scale - 1) * constantDis;
  25619. }
  25620. }
  25621. var vec = direction.multiplyScalar(speed);
  25622. //this.translationWorldDelta.copy(vec)
  25623. _this.translationWorldDelta.add(vec);
  25624. //console.log(direction.toArray(), speed, e.scale)
  25625. }
  25626. return true;
  25627. };
  25628. var scroll = e => {
  25629. if (!this.enabled || !e.hoverViewport) return;
  25630. this.setCurrentViewport(e);
  25631. e.camera = e.hoverViewport.camera;
  25632. dolly(e);
  25633. };
  25634. var dblclick = e => {
  25635. if (!this.enabled) return;
  25636. if (!Potree.settings.dblToFocusPoint) return; //调试时才可双击
  25637. if (Potree.settings.displayMode == 'showPointCloud' /* !viewer.images360.isAtPano() */) this.zoomToLocation(e.mouse);
  25638. };
  25639. this.viewer.addEventListener('global_drag', drag);
  25640. /* this.viewer.addEventListener('global_touchmove', (e)=>{
  25641. if(!this.enabled)return
  25642. if(e.touches.length>1){//单指的就触发上一句
  25643. //console.log('global_touchmove' )
  25644. drag(e)
  25645. }
  25646. }); */
  25647. this.viewer.addEventListener('global_drop', drop);
  25648. this.viewer.addEventListener('global_mousewheel', scroll);
  25649. this.viewer.addEventListener('global_dblclick', dblclick);
  25650. var prepareScale = e => {
  25651. //触屏的scale
  25652. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  25653. e.drag.camDisToPointStart = null;
  25654. };
  25655. var prepareRotate = e => {
  25656. this.pointerDragStart = e.pointer.clone();
  25657. if (e.viewer.name != 'mainViewer') return;
  25658. var intersect = e.intersect || e.dragViewport.lastIntersect;
  25659. //在数据集外部时绕中心点旋转,在数据集内部时绕intersect点旋转(其他数据集的点也可以) 或者 原地旋转镜头
  25660. var rotAroundPoint = Potree.settings.rotAroundPoint && e.dragViewport.camera.type != 'OrthographicCamera' && (viewer.atDatasets.length == 0 || intersect) && this.canMovePos(viewport) && !viewer.images360.isAtPano() && !this.viewer.inputHandler.pressedKeys[32];
  25661. var rotCenter2d, rotCenter;
  25662. if (rotAroundPoint) {
  25663. var pivotType = this.target ? 'target' : viewer.atDatasets.length > 0 ? 'intersect' : viewer.inputHandler.selection.length ? 'selection' : this.target2 ? 'target2' : 'boundCenter';
  25664. rotCenter = pivotType == 'target' ? this.target : pivotType == 'intersect' ? intersect.location : pivotType == 'selection' ? viewer.inputHandler.selection[0].position : pivotType == 'target2' ? this.target2 : viewer.bound && viewer.bound.center;
  25665. if (rotCenter) {
  25666. rotCenter2d = rotCenter.clone().project(e.dragViewport.camera); //点在屏幕中的位置。 若z>1 则在背面 或 超出far范围
  25667. } else {
  25668. rotAroundPoint = false;
  25669. }
  25670. }
  25671. this.rotateStartInfo = {
  25672. rotAroundPoint,
  25673. //定点旋转
  25674. rotCenter,
  25675. rotCenter2d
  25676. };
  25677. //缺点:多数据集绕中心点转很难操作,感觉可以也改为绕lastIntersect
  25678. //console.log('prepareRotate' )
  25679. };
  25680. var preparePan = e => {
  25681. //触屏的pan点云 还是会偏移
  25682. this.pointerDragStart = e.pointer.clone();
  25683. e.drag.z = void 0; //清空
  25684. drag(e); //触屏点击时更新的pointer直接用一次drag
  25685. //console.log('preparePan ' )
  25686. };
  25687. this.viewer.addEventListener('global_mousedown' /* 'startDragging' */, e => {
  25688. if (!this.enabled) return;
  25689. this.setCurrentViewport(e);
  25690. prepareRotate(e);
  25691. });
  25692. //注意,每次增减指头都会修改pointer,需要更新下状态
  25693. this.viewer.addEventListener('global_touchstart', e => {
  25694. if (!this.enabled) return;
  25695. if (e.touches.length == 2) {
  25696. //只监听开头两个指头
  25697. prepareScale(e);
  25698. preparePan(e);
  25699. } else if (e.touches.length >= 3) {
  25700. preparePan(e);
  25701. }
  25702. });
  25703. this.viewer.addEventListener('global_touchend', e => {
  25704. //e.touches是剩余的指头
  25705. if (!this.enabled) return;
  25706. if (e.touches.length == 2) {
  25707. //停止平移,开始scale
  25708. prepareScale(e);
  25709. preparePan(e);
  25710. } else if (e.touches.length == 1) {
  25711. //停止scale,开始rotate
  25712. prepareRotate(e);
  25713. } else if (e.touches.length >= 3) {
  25714. //重新准备下平移(因为抬起的指头可能包含平移使用的数据),否则抬起时漂移
  25715. preparePan(e);
  25716. }
  25717. });
  25718. /* this.viewer.addEventListener('enableChangePos', (e)=>{
  25719. if(!this.enabled)return
  25720. this.enableChangePos = e.canLeavePano
  25721. }) */
  25722. }
  25723. canMovePos(viewport) {
  25724. if (viewport == viewer.mainViewport && (Potree.settings.displayMode == 'showPanos' || viewer.images360.bumping || viewer.images360.latestToPano)) return false;else return true;
  25725. }
  25726. setEnable(enabled) {
  25727. this.enabled = enabled;
  25728. }
  25729. setTarget(target, index) {
  25730. //绕该点旋转,类似orbitControl
  25731. if (index == 2) this.target2 = target;else this.target = target;
  25732. }
  25733. setFPCMoveSpeed(viewport) {
  25734. if (viewport.camera.type == 'OrthographicCamera') {
  25735. var s = 1 / viewport.camera.zoom;
  25736. viewport.setMoveSpeed(s);
  25737. } else {
  25738. //根据和漫游点的最短距离算moveSpeed。缺点:对于导入的无漫游点的数据集没有意义。
  25739. if (viewport == viewer.mainViewport && viewer.images360) {
  25740. var position = viewer.mainViewport.view.position;
  25741. var speed;
  25742. var pano = viewer.images360.findNearestPano();
  25743. if (!pano) {
  25744. if (!viewer.bound || viewer.bound.boundSize.x == 0) return;
  25745. var boundFloor = viewer.bound.boundingBox.clone();
  25746. boundFloor.max.z = boundFloor.min.z;
  25747. speed = boundFloor.distanceToPoint(viewer.mainViewport.view.position);
  25748. speed = Math.sqrt(speed) / 50;
  25749. } else {
  25750. var dis = pano.position.distanceTo(position);
  25751. var minSpeed = 0.05,
  25752. minDis = 3,
  25753. multiplier = 0.005;
  25754. speed = dis <= minDis ? minSpeed : minSpeed + (dis - minDis) * multiplier;
  25755. //console.log('dis', dis, 'speed', speed, pano.id )
  25756. }
  25757. viewer.setMoveSpeed(speed * 2);
  25758. }
  25759. //调试场景t-FhDWmV5xur 两个数据集,大的数据集没有漫游点。
  25760. }
  25761. }
  25762. setCurrentViewport() {
  25763. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  25764. //add
  25765. if (!this.enabled && !o.force) return;
  25766. if (o.hoverViewport && this.currentViewport != o.hoverViewport) {
  25767. this.currentViewport = o.hoverViewport;
  25768. //this.viewer.setMoveSpeed(this.currentViewport.radius/100);
  25769. this.setFPCMoveSpeed(this.currentViewport);
  25770. }
  25771. if (this.currentViewport.camera.type == 'OrthographicCamera') {
  25772. this.lockElevationOri = true;
  25773. this.lockRotation = true;
  25774. } else {
  25775. this.lockElevationOri = false;
  25776. this.lockRotation = false;
  25777. }
  25778. }
  25779. setScene(scene) {
  25780. this.scene = scene;
  25781. }
  25782. stop() {
  25783. this.yawDelta = 0;
  25784. this.pitchDelta = 0;
  25785. this.translationDelta.set(0, 0, 0);
  25786. }
  25787. zoomToLocation(mouse) {
  25788. if (!this.enabled) return;
  25789. var camera = this.scene.getActiveCamera();
  25790. /* let I = Utils.getMousePointCloudIntersection(
  25791. mouse,
  25792. camera,
  25793. this.viewer,
  25794. this.scene.pointclouds); */
  25795. var I = this.viewer.inputHandler.intersect;
  25796. if (!I) {
  25797. return;
  25798. }
  25799. var targetRadius = 0;
  25800. {
  25801. var minimumJumpDistance = 0.2;
  25802. var domElement = this.renderer.domElement;
  25803. var ray = Utils.mouseToRay(this.viewer.inputHandler.pointer, camera);
  25804. var {
  25805. origin,
  25806. direction
  25807. } = this.viewer.inputHandler.getMouseDirection();
  25808. var raycaster = new Raycaster();
  25809. raycaster.ray.set(origin, direction);
  25810. var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  25811. var nodes2 = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, raycaster.ray);
  25812. var lastNode = nodes[nodes.length - 1];
  25813. var radius = lastNode.getBoundingSphere(new Sphere()).radius;
  25814. targetRadius = Math.min(this.scene.view.radius, radius);
  25815. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  25816. }
  25817. var d = this.scene.view.direction.multiplyScalar(-1);
  25818. var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  25819. // TODO Unused: let controlsTargetPosition = I.location;
  25820. var animationDuration = 600;
  25821. var easing = TWEEN.Easing.Quartic.Out;
  25822. {
  25823. // animate
  25824. var value = {
  25825. x: 0
  25826. };
  25827. var tween = new TWEEN.Tween(value).to({
  25828. x: 1
  25829. }, animationDuration);
  25830. tween.easing(easing);
  25831. this.tweens.push(tween);
  25832. var startPos = this.scene.view.position.clone();
  25833. var targetPos = cameraTargetPosition.clone();
  25834. var startRadius = this.scene.view.radius;
  25835. var _targetRadius = cameraTargetPosition.distanceTo(I.location);
  25836. tween.onUpdate(() => {
  25837. var t = value.x;
  25838. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  25839. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  25840. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  25841. this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius;
  25842. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  25843. });
  25844. tween.onComplete(() => {
  25845. this.tweens = this.tweens.filter(e => e !== tween);
  25846. });
  25847. tween.start();
  25848. }
  25849. }
  25850. update() {
  25851. var delta = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  25852. if (!this.enabled) return;
  25853. //console.log('update')
  25854. var view = this.currentViewport.view;
  25855. {
  25856. // cancel move animations on user input
  25857. var changes = [this.yawDelta, this.pitchDelta, this.translationDelta.length(), this.translationWorldDelta.length()];
  25858. var changeHappens = changes.some(e => Math.abs(e) > 0.001);
  25859. if (changeHappens && this.tweens.length > 0) {
  25860. this.tweens.forEach(e => e.stop());
  25861. this.tweens = [];
  25862. }
  25863. }
  25864. {
  25865. // accelerate while input is given
  25866. var ih = this.viewer.inputHandler;
  25867. var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  25868. var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  25869. var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  25870. var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  25871. var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  25872. var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  25873. var rotateLeft = this.keys.Rotate_LEFT.some(e => ih.pressedKeys[e]);
  25874. var rotateRight = this.keys.Rotate_RIGHT.some(e => ih.pressedKeys[e]);
  25875. var rotateUp = this.keys.Rotate_UP.some(e => ih.pressedKeys[e]);
  25876. var rotateDown = this.keys.Rotate_DOWN.some(e => ih.pressedKeys[e]);
  25877. this.lockElevation = this.lockElevationOri || this.keys.SPACE.some(e => ih.pressedKeys[e]);
  25878. var slightly = this.keys.ALT.some(e => ih.pressedKeys[e]);
  25879. if (!this.lockRotation) {
  25880. if (rotateLeft) {
  25881. this.yawDelta -= 0.01;
  25882. } else if (rotateRight) {
  25883. this.yawDelta += 0.01;
  25884. }
  25885. if (rotateUp) {
  25886. this.pitchDelta -= 0.01;
  25887. } else if (rotateDown) {
  25888. this.pitchDelta += 0.01;
  25889. }
  25890. }
  25891. if (this.canMovePos(this.currentViewport) && !this.lockKey) {
  25892. if (this.lockElevation) {
  25893. var dir = view.direction;
  25894. dir.z = 0;
  25895. dir.normalize();
  25896. if (moveForward && moveBackward) {
  25897. this.translationWorldDelta.set(0, 0, 0);
  25898. } else if (moveForward) {
  25899. this.translationWorldDelta.copy(dir.multiplyScalar(this.currentViewport.getMoveSpeed()));
  25900. } else if (moveBackward) {
  25901. this.translationWorldDelta.copy(dir.multiplyScalar(-this.currentViewport.getMoveSpeed()));
  25902. }
  25903. } else {
  25904. if (moveForward && moveBackward) {
  25905. this.translationDelta.y = 0;
  25906. } else if (moveForward) {
  25907. this.translationDelta.y = this.currentViewport.getMoveSpeed() * (slightly ? 0.2 : 1);
  25908. } else if (moveBackward) {
  25909. this.translationDelta.y = -this.currentViewport.getMoveSpeed() * (slightly ? 0.2 : 1);
  25910. }
  25911. }
  25912. if (moveLeft && moveRight) {
  25913. this.translationDelta.x = 0;
  25914. } else if (moveLeft) {
  25915. this.translationDelta.x = -this.currentViewport.getMoveSpeed();
  25916. } else if (moveRight) {
  25917. this.translationDelta.x = this.currentViewport.getMoveSpeed();
  25918. }
  25919. if (moveUp && moveDown) {
  25920. this.translationWorldDelta.z = 0;
  25921. } else if (moveUp) {
  25922. this.translationWorldDelta.z = this.currentViewport.getMoveSpeed();
  25923. } else if (moveDown) {
  25924. this.translationWorldDelta.z = -this.currentViewport.getMoveSpeed();
  25925. }
  25926. if (moveUp || moveDown || moveForward || moveBackward) {
  25927. this.useAttenuation = false;
  25928. }
  25929. }
  25930. }
  25931. {
  25932. // apply rotation
  25933. var yaw = view.yaw;
  25934. var pitch = view.pitch;
  25935. yaw += this.yawDelta; /* * delta; */
  25936. pitch += this.pitchDelta; /* * delta; */
  25937. view.yaw = yaw;
  25938. view.pitch = pitch;
  25939. if (this.yawDelta || this.pitchDelta) {
  25940. view.cancelFlying('rotate');
  25941. }
  25942. this.yawDelta = 0;
  25943. this.pitchDelta = 0;
  25944. }
  25945. /* if(this.translationWorldDelta.length()>0) {
  25946. // console.log('translationDelta')
  25947. } */
  25948. {
  25949. // apply translation
  25950. view.translate(this.translationDelta.x, /* * delta, */
  25951. this.translationDelta.y, /* * delta, */
  25952. this.translationDelta.z /* * delta */);
  25953. this.translationDelta.set(0, 0, 0);
  25954. //if(this.translationWorldDelta.length())console.log(translationWorldDelta)
  25955. view.translateWorld(this.translationWorldDelta.x /* * delta */, this.translationWorldDelta.y /* * delta */, this.translationWorldDelta.z /* * delta */);
  25956. //this.translationWorldDelta.set(0,0,0)
  25957. }
  25958. {// set view target according to speed
  25959. //view.radius = 1 * this.currentViewport.getMoveSpeed();
  25960. /* if(viewer.bound) view.radius = view.position.distanceTo(viewer.bound.center)
  25961. let speed = view.radius/100;
  25962. this.viewer.setMoveSpeed(speed); */
  25963. //this.setMoveSpeed()
  25964. }
  25965. if (this.useAttenuation) {
  25966. //只有滚轮缩放时开启
  25967. var attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  25968. /*this.yawDelta *= attenuation;
  25969. this.pitchDelta *= attenuation;
  25970. this.translationDelta.multiplyScalar(attenuation);*/
  25971. this.translationWorldDelta.multiplyScalar(attenuation);
  25972. } else {
  25973. this.translationWorldDelta.set(0, 0, 0);
  25974. }
  25975. }
  25976. }
  25977. ;
  25978. /**
  25979. * @author mschuetz / http://mschuetz.at
  25980. *
  25981. *
  25982. */
  25983. var {
  25984. Buttons: Buttons$1
  25985. } = Potree.defines;
  25986. class InputHandler extends EventDispatcher {
  25987. constructor(viewer, scene) {
  25988. super();
  25989. this.viewer = viewer;
  25990. this.renderer = viewer.renderer;
  25991. this.domElement = this.renderer.domElement;
  25992. this.enabled = true;
  25993. this.scene = scene;
  25994. this.interactiveScenes = [];
  25995. this.interactiveObjects = new Set();
  25996. this.inputListeners = [];
  25997. this.blacklist = new Set();
  25998. this.drag = null;
  25999. this.mouse = new Vector2(0, 0);
  26000. //add:
  26001. this.pointer = new Vector2(0, 0); //交互点的屏幕坐标,有别于DOM坐标,在此存放NDC坐标。(NDC,三维常用坐标系,二维坐标,整个屏幕映射范围(-1,1),屏幕中心为原点,+Y朝上,+X朝右)
  26002. this.mouseDownMouse = new Vector2(0, 0);
  26003. this.selection = [];
  26004. this.hoveredElements = [];
  26005. this.pressedKeys = {};
  26006. this.wheelDelta = 0;
  26007. this.speed = 1;
  26008. this.logMessages = false;
  26009. if (this.domElement.tabIndex === -1) {
  26010. this.domElement.tabIndex = 2222;
  26011. }
  26012. this.lastPointerUpTime = 0;
  26013. this.touches = [];
  26014. this.interactHistory = {
  26015. move: 0
  26016. }; //add
  26017. this.hoverViewport = viewer.viewports[0];
  26018. this.domElement.addEventListener('contextmenu', event => {
  26019. event.preventDefault();
  26020. }, false);
  26021. this.domElement.addEventListener('click', this.onMouseClick.bind(this), false);
  26022. this.domElement.addEventListener('mousedown', this.onMouseDown.bind(this), false);
  26023. window.addEventListener('mouseup', this.onMouseUp.bind(this), false);
  26024. if (Potree.isIframeChild) {
  26025. //子页面的话在父页面也要加侦听(应该不会有多层吧?否则要一直加到最外层)
  26026. //window.parent.addEventListener('mouseup', this.onMouseUp.bind(this), false); //可能跨域
  26027. //window.parent.postMessage('listenMouseup', '*');
  26028. window.addEventListener('mouseout', this.onMouseUp.bind(this), false); //cancel drag
  26029. }
  26030. this.domElement.addEventListener('mouseout', () => {
  26031. this.containsMouse = false;
  26032. }, false);
  26033. this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this), false);
  26034. //add
  26035. /* this.domElement.addEventListener("pointerout", this.onMouseUp.bind(this)),
  26036. this.domElement.addEventListener("pointercancel", this.onMouseUp.bind(this)),
  26037. */
  26038. this.domElement.addEventListener('mousewheel', this.onMouseWheel.bind(this), false);
  26039. this.domElement.addEventListener('DOMMouseScroll', this.onMouseWheel.bind(this), false); // Firefox
  26040. //this.domElement.addEventListener('dblclick', this.onDoubleClick.bind(this)); //因为双击时间间隔是跟随系统的所以不好判断
  26041. window.addEventListener('keydown', this.onKeyDown.bind(this)); //原先是this.domElement,这样的话一开始要点击屏幕后才能监听到
  26042. window.addEventListener('keyup', this.onKeyUp.bind(this));
  26043. window.addEventListener('blur', this.onKeyUp.bind(this)); //add
  26044. this.domElement.addEventListener('touchstart', this.onTouchStart.bind(this));
  26045. this.domElement.addEventListener('touchend', this.onTouchEnd.bind(this));
  26046. this.domElement.addEventListener('touchmove', this.onTouchMove.bind(this));
  26047. {
  26048. this.measuring = []; //正在编辑的measure
  26049. //let mesureInfo = new THREE.EventDispatcher()
  26050. this.addEventListener('measuring', e => {
  26051. //true优先级高于false, 正在添加时dropMarker也不会停止
  26052. //Potree.Utils.updateVisible(mesureInfo, e.situation, e.v, 0, e.v?'add':'cancel' )//借用该函数,使true优先级高于false,防止正在添加时dropMarker而停止
  26053. if (e.v) {
  26054. this.measuring.includes(e.object) || this.measuring.push(e.object);
  26055. } else {
  26056. var index = this.measuring.indexOf(e.object);
  26057. index > -1 && this.measuring.splice(index, 1);
  26058. }
  26059. if (this.measuring.length == 0 && this.measuring.length > 0) {
  26060. this.viewer.viewports.forEach(viewport => {
  26061. this.collectClosePoints(viewport, true); //forceUpdate
  26062. });
  26063. }
  26064. //console.log('measuring',e.v, e.cause, e.situation, this.measuring.length )
  26065. });
  26066. }
  26067. window.viewer.addEventListener('loopStart', () => {
  26068. this.interactHistory = {}; //清空
  26069. });
  26070. }
  26071. /* addInputListener (listener) {
  26072. this.inputListeners.push(listener);
  26073. }
  26074. removeInputListener (listener) {
  26075. this.inputListeners = this.inputListeners.filter(e => e !== listener);
  26076. }
  26077. getSortedListeners(){
  26078. return this.inputListeners.sort( (a, b) => {
  26079. let ia = (a.importance !== undefined) ? a.importance : 0;
  26080. let ib = (b.importance !== undefined) ? b.importance : 0;
  26081. return ib - ia;
  26082. });
  26083. } */
  26084. //统一跟第一个触碰的viewport相同
  26085. updateTouchesInfo(e) {
  26086. var viewport, pointer, camera;
  26087. var oldTouches = this.touches;
  26088. var changedTouches = Array.from(e.changedTouches);
  26089. var touches = Array.from(e.touches);
  26090. this.touches = touches.map(touch => {
  26091. var touch_ = oldTouches.find(a => a.touch.identifier == touch.identifier);
  26092. var pointer = touch_ && touch_.pointer; //复制原先的值
  26093. return {
  26094. touch,
  26095. pointer
  26096. };
  26097. });
  26098. if (e.touches.length > 0) {
  26099. var newTouches = touches.filter(e => !oldTouches.some(a => a.touch.identifier == e.identifier) && !changedTouches.some(a => a.identifier == e.identifier)); //从按钮处划过时e.touches中会出现this.touches和changedTouches中都没有的identifier
  26100. if (newTouches.length > 0) {
  26101. console.warn('has new', newTouches.map(e => e.identifier));
  26102. }
  26103. newTouches.concat(changedTouches).forEach(touch => {
  26104. //修改changedTouches的
  26105. var touch_ = this.touches.find(a => a.touch.identifier == touch.identifier);
  26106. if (touch_) {
  26107. var a = this.getPointerInViewport(touch.pageX, touch.pageY, this.dragViewport || viewport, new Vector2());
  26108. touch_.pointer = a.pointer.clone();
  26109. viewport = a.viewport;
  26110. camera = a.camera;
  26111. }
  26112. });
  26113. //使用当前touches的平均
  26114. if (e.touches.length > 1) {
  26115. var pageX = Common.average(e.touches, "pageX");
  26116. var pageY = Common.average(e.touches, "pageY");
  26117. var a = this.getPointerInViewport(pageX, pageY, viewport, new Vector2());
  26118. this.pointer.copy(a.pointer);
  26119. //console.log('updateTouchesInfo', this.pointer.clone())
  26120. } else {
  26121. this.pointer = this.touches[0].pointer.clone(); //更新,使用当前touches中的第一个
  26122. }
  26123. /* if(this.touches.find(e=>!e.pointer)){
  26124. console.error(' touches has no pointer', oldTouches.map(e=>e.touch.identifier),
  26125. Array.from(e.touches).map(e=>e.identifier), Array.from(e.changedTouches).map(e=>e.identifier) )
  26126. } */
  26127. //console.log(this.touches)
  26128. //console.log('更新pointer1',this.pointer.toArray())
  26129. return {
  26130. viewport,
  26131. camera /* , pointer:this.pointer */
  26132. };
  26133. }
  26134. }
  26135. onTouchStart(e) {
  26136. if (this.logMessages) console.log(this.constructor.name + ': onTouchStart');
  26137. e.preventDefault();
  26138. /* if (e.touches.length === 1 || !this.drag) { //!this.drag代表一次性下了两个指头
  26139. let rect = this.domElement.getBoundingClientRect();
  26140. let x = e.touches[0].pageX
  26141. let y = e.touches[0].pageY
  26142. this.dealPointerDown(x,y,e,true)
  26143. }else{
  26144. this.updateTouchesInfo(e)
  26145. this.drag.end.copy(this.pointer)
  26146. } */
  26147. this.dealPointerDown(e, true);
  26148. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), {
  26149. type: 'global_' + e.type,
  26150. changedTouches: e.changedTouches
  26151. }));
  26152. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  26153. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  26154. ) */
  26155. //console.log('')
  26156. }
  26157. onTouchMove(e) {
  26158. if (this.logMessages) console.log(this.constructor.name + ': onTouchMove');
  26159. e.preventDefault();
  26160. /* if (e.touches.length === 1) {
  26161. let rect = this.domElement.getBoundingClientRect();
  26162. let x = e.touches[0].pageX;
  26163. let y = e.touches[0].pageY;
  26164. }else{
  26165. this.updateTouchesInfo(e)
  26166. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end)
  26167. this.drag.end.copy(this.pointer)
  26168. }
  26169. */
  26170. this.dealPointerMove(e, true);
  26171. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), {
  26172. type: 'global_' + e.type,
  26173. changedTouches: e.changedTouches
  26174. }));
  26175. /* console.log('targetTouches :', Array.from(e.targetTouches).map(e=>'| identifier: '+ e.identifier),
  26176. 'changedTouches :', Array.from(e.changedTouches).map(e=>'| identifier: '+ e.identifier)
  26177. ) */
  26178. }
  26179. onTouchEnd(e) {
  26180. if (this.logMessages) console.log(this.constructor.name + ': onTouchEnd');
  26181. e.preventDefault();
  26182. //console.log('onTouchEnd')
  26183. this.updateTouchesInfo(e);
  26184. /* if (e.touches.length === 0) {
  26185. let rect = this.domElement.getBoundingClientRect();
  26186. let x = e.changedTouches[0].pageX //万一一次松开两个指头的怎么办
  26187. let y = e.changedTouches[0].pageY
  26188. this.dealPointerUp(x,y,e,true)
  26189. }else {
  26190. this.drag.end.copy(this.pointer)
  26191. } */
  26192. this.dealPointerUp(e, true);
  26193. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, true), {
  26194. type: 'global_' + e.type
  26195. }));
  26196. //console.log('touchend length '+e.touches.length, this.touches.length)
  26197. }
  26198. onKeyDown(e) {
  26199. if (this.logMessages) console.log(this.constructor.name + ': onKeyDown');
  26200. if (e.target.nodeName == 'INPUT' || e.target.nodeName == 'TEXTAREA') return; //正在输入文字 或e.srcElement
  26201. if (!this.containsMouse) return; //在别的ui上无效
  26202. // DELETE
  26203. /* if (e.keyCode === KeyCodes.DELETE && this.selection.length > 0) {
  26204. this.dispatchEvent({
  26205. type: 'delete',
  26206. selection: this.selection
  26207. });
  26208. this.deselectAll();
  26209. } */
  26210. this.dispatchEvent({
  26211. type: 'keydown',
  26212. keyCode: e.keyCode,
  26213. event: e
  26214. });
  26215. // for(let l of this.getSortedListeners()){
  26216. // l.dispatchEvent({
  26217. // type: "keydown",
  26218. // keyCode: e.keyCode,
  26219. // event: e
  26220. // });
  26221. // }
  26222. this.pressedKeys[e.keyCode] = true;
  26223. // e.preventDefault();
  26224. }
  26225. onKeyUp(e) {
  26226. if (this.logMessages) console.log(this.constructor.name + ': onKeyUp');
  26227. if (e.keyCode != void 0) {
  26228. delete this.pressedKeys[e.keyCode];
  26229. } else {
  26230. this.pressedKeys = {};
  26231. }
  26232. e.preventDefault();
  26233. }
  26234. onDoubleClick(e) {
  26235. if (this.logMessages) console.log(this.constructor.name + ': onDoubleClick');
  26236. var consumed = false;
  26237. for (var hovered of this.hoveredElements) {
  26238. if (hovered._listeners && hovered._listeners['dblclick']) {
  26239. hovered.object.dispatchEvent({
  26240. type: 'dblclick',
  26241. mouse: this.mouse,
  26242. object: hovered.object
  26243. });
  26244. consumed = true;
  26245. break;
  26246. }
  26247. }
  26248. if (!consumed) {
  26249. /* for (let inputListener of this.getSortedListeners()) {
  26250. inputListener. */
  26251. this.viewer.dispatchEvent({
  26252. type: 'global_dblclick',
  26253. mouse: this.mouse,
  26254. object: null
  26255. });
  26256. //}
  26257. }
  26258. this.needSingleClick = false; //add
  26259. e.preventDefault();
  26260. }
  26261. onMouseClick(e) {
  26262. if (this.logMessages) console.log(this.constructor.name + ': onMouseClick');
  26263. e.preventDefault();
  26264. }
  26265. dealPointerDown(e, isTouch) {
  26266. e.preventDefault();
  26267. //重新获取一下pointer, 因点击了浏览器的按钮展开列表时 move回来不会触发onmousemove,所以pointer是旧的
  26268. if (isTouch) {
  26269. var {
  26270. camera,
  26271. viewport
  26272. } = this.updateTouchesInfo(e);
  26273. if (this.drag) {
  26274. //因为触屏在按下前缺少pointermove所以要更新下
  26275. this.drag.end = this.pointer.clone();
  26276. }
  26277. } else {
  26278. var {
  26279. camera,
  26280. viewport
  26281. } = this.getPointerInViewport(e.clientX, e.clientY);
  26282. }
  26283. this.dragViewport = this.hoverViewport = viewport;
  26284. //if(isTouch || !Potree.settings.intersectWhenHover ){
  26285. if (isTouch || !this.dragViewport.view.isFlying() && Potree.settings.intersectWhenHover && Potree.settings.editType != 'pano') {
  26286. //漫游点编辑如果拖拽前getIntersect旋转会延迟
  26287. //isTouch必须更新 否则是旧的
  26288. this.hoveredElements = this.getHoveredElements();
  26289. var dontIntersect = false;
  26290. this.intersect = this.getIntersect({
  26291. viewport,
  26292. dontIntersect,
  26293. clientX: e.clientX,
  26294. clientY: e.clientY
  26295. }); //更新intersect,避免在没有mousemove但flyToPano后intersect未更新。
  26296. //this.intersect = this.getWholeIntersect()
  26297. }
  26298. if (!viewport) return; //why add this?
  26299. if (!this.drag) {
  26300. var target = (isTouch || e.button == MOUSE.LEFT) && this.hoveredElements.find(el =>
  26301. //只有左键能拖拽
  26302. el.object._listeners && el.object._listeners['drag'] && el.object._listeners['drag'].length > 0);
  26303. if (target) {
  26304. this.startDragging(target.object, {
  26305. location: target.point
  26306. });
  26307. } else {
  26308. this.startDragging(null);
  26309. }
  26310. }
  26311. this.drag.intersectStart = this.intersect;
  26312. if (!isTouch || e.touches.length == 1) {
  26313. var consumed = false;
  26314. var consume = () => {
  26315. return consumed = true;
  26316. };
  26317. //if (this.hoveredElements.length === 0) {
  26318. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26319. type: 'global_mousedown'
  26320. }));
  26321. for (var hovered of this.hoveredElements) {
  26322. var object = hovered.object;
  26323. object.dispatchEvent({
  26324. type: 'mousedown',
  26325. viewer: this.viewer,
  26326. consume: consume
  26327. });
  26328. if (consumed) {
  26329. break;
  26330. }
  26331. }
  26332. }
  26333. this.mouseDownMouse = this.mouse.clone();
  26334. this.pointerDownTime = Date.now();
  26335. }
  26336. onMouseDown(e) {
  26337. if (this.logMessages) console.log(this.constructor.name + ': onMouseDown');
  26338. this.dealPointerDown(e);
  26339. }
  26340. /* getWholeIntersect(hoveredElements, intersectPoint){//add
  26341. hoveredElements = hoveredElements || this.hoveredElements
  26342. intersectPoint = intersectPoint || this.intersectPoint
  26343. if(Potree.settings.intersectOnObjs && hoveredElements[0] && hoveredElements[0].object.isModel){
  26344. return {//模拟点云的intersectPoint的结构写法
  26345. hoveredElement : hoveredElements[0] ,
  26346. location: hoveredElements[0].point,
  26347. point: {normal: hoveredElements[0].face.normal },
  26348. distance: hoveredElements[0].distance,
  26349. object: hoveredElements[0].object
  26350. }
  26351. }else return intersectPoint
  26352. } */
  26353. getEventDesc(e, isTouch) {
  26354. //搜集dispatchEvent要给的一般数据
  26355. var o = {
  26356. viewer: this.viewer,
  26357. mouse: this.mouse,
  26358. pointer: this.pointer,
  26359. drag: this.drag,
  26360. isTouch,
  26361. dragViewport: this.dragViewport,
  26362. hoverViewport: this.hoverViewport,
  26363. // button: isTouch ? 0 : e.button,
  26364. //intersectPoint:this.intersectPoint,
  26365. hoveredElement: this.hoveredElements[0],
  26366. intersect: this.intersect //this.getWholeIntersect() , //可能包含mesh上的,针对融合页面
  26367. };
  26368. if (e) {
  26369. o.isAtDomElement = e.target == this.domElement;
  26370. }
  26371. if (isTouch) {
  26372. o.touches = this.touches;
  26373. } else if (e) {
  26374. o.button = e.button;
  26375. o.buttons = e.buttons;
  26376. }
  26377. return o;
  26378. }
  26379. dealPointerUp(e, isTouch) {
  26380. if (!this.drag) {
  26381. // 在canvas外mousedown
  26382. return;
  26383. }
  26384. this.drag.end.copy(this.pointer);
  26385. if (isTouch && e.touches.length >= 1) {
  26386. return;
  26387. }
  26388. var now = Date.now();
  26389. if (this.logMessages) console.log(this.constructor.name + ': onMouseUp');
  26390. e.preventDefault();
  26391. var pressDistance = this.mouseDownMouse.distanceTo(this.mouse);
  26392. var pressTime = now - this.pointerDownTime;
  26393. var noMovement = this.drag.pointerDelta.length() == 0; //this.getNormalizedDrag().length() === 0;
  26394. var consumed = false;
  26395. var consume = () => {
  26396. return consumed = true;
  26397. };
  26398. //if (this.hoveredElements.length === 0) {
  26399. /* for (let inputListener of this.getSortedListeners()) {
  26400. inputListener */
  26401. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26402. type: 'global_mouseup',
  26403. pressDistance,
  26404. consume
  26405. }));
  26406. /* if(consumed){//??
  26407. break;
  26408. } */
  26409. //}
  26410. //}
  26411. if (this.hoveredElements.length > 0) {
  26412. var hovered = this.hoveredElements.map(e => e.object).find(e => e._listeners && e._listeners['mouseup']);
  26413. if (hovered) {
  26414. hovered.dispatchEvent({
  26415. type: 'mouseup',
  26416. viewer: this.viewer,
  26417. consume: consume
  26418. });
  26419. }
  26420. }
  26421. if (this.drag) {
  26422. //拖拽结束
  26423. if (this.drag.object /* && e.button == THREE.MOUSE.LEFT */) {
  26424. //add LEFT
  26425. if (this.logMessages) console.log("".concat(this.constructor.name, ": drop ").concat(this.drag.object.name));
  26426. this.drag.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26427. type: 'drop',
  26428. pressDistance
  26429. }));
  26430. } else {
  26431. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26432. type: 'global_drop',
  26433. pressDistance
  26434. }));
  26435. }
  26436. // check for a click
  26437. if (pressDistance < Potree.config.clickMaxDragDis && pressTime < Potree.config.clickMaxPressTime && !e.unableClick) {
  26438. var clickElement,
  26439. _consumed = false;
  26440. if (this.hoveredElements) {
  26441. clickElement = this.hoveredElements.find(e => e.object._listeners['click']);
  26442. if (clickElement) {
  26443. var canceled;
  26444. var cancel = () => {
  26445. return canceled = true;
  26446. };
  26447. //console.log('clickElement',clickElement)
  26448. if (this.logMessages) console.log("".concat(this.constructor.name, ": click ").concat(clickElement.name));
  26449. clickElement.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26450. type: 'click',
  26451. pressDistance,
  26452. cancel
  26453. }));
  26454. if (canceled) {
  26455. //比如只需要右键的话,可以忽视左键的点击
  26456. clickElement = null;
  26457. }
  26458. }
  26459. }
  26460. var selectable;
  26461. if ( /* !consumed && */!this.fixSelection) {
  26462. if (e.button === MOUSE.LEFT) {
  26463. //if (noMovement) {
  26464. selectable = this.hoveredElements.find(el => el.object._listeners && el.object._listeners['select']);
  26465. if (selectable) {
  26466. selectable = selectable.object;
  26467. if (this.isSelected(selectable)) {
  26468. this.deselectAll();
  26469. } else {
  26470. this.deselectAll();
  26471. this.toggleSelection(selectable);
  26472. }
  26473. _consumed = true; //add
  26474. } else {
  26475. if (this.selection.length > 0) _consumed = true; //add 取消选择后,阻断后续
  26476. this.deselectAll();
  26477. }
  26478. //}
  26479. } else if (e.button === MOUSE.RIGHT /* && noMovement */) {
  26480. this.deselectAll();
  26481. }
  26482. }
  26483. var _consume = () => {
  26484. return _consumed = true;
  26485. };
  26486. var desc = this.getEventDesc(e, isTouch);
  26487. if (!_consumed) {
  26488. this.viewer.dispatchEvent($.extend(desc, {
  26489. type: 'global_click',
  26490. pressDistance,
  26491. clickElement: clickElement /* || selectable */,
  26492. consume: _consume
  26493. }));
  26494. }
  26495. //增加 单击:
  26496. this.needSingleClick = true;
  26497. _consumed || setTimeout(() => {
  26498. if (this.needSingleClick) {
  26499. this.viewer.dispatchEvent($.extend(desc, {
  26500. type: 'global_single_click',
  26501. pressDistance,
  26502. clickElement
  26503. }));
  26504. }
  26505. }, Potree.config.doubleClickTime + 1);
  26506. //自行执行双击:
  26507. if (now - this.lastClickTime < Potree.config.doubleClickTime) {
  26508. this.onDoubleClick(e);
  26509. }
  26510. this.lastClickTime = now;
  26511. }
  26512. this.drag = null;
  26513. }
  26514. this.dragViewport = null;
  26515. }
  26516. onMouseUp(e) {
  26517. this.dealPointerUp(e);
  26518. }
  26519. getPointerInViewport(clientX, clientY, viewForceAt, pointer) {
  26520. var rect = this.domElement.getBoundingClientRect();
  26521. var x = clientX - rect.left;
  26522. var y = clientY - rect.top;
  26523. var camera;
  26524. var viewport;
  26525. pointer = pointer || this.pointer;
  26526. //if(this.viewer.viewports || viewForceAt){
  26527. var getDimension = view => {
  26528. var left = Math.ceil(this.domElement.clientWidth * view.left),
  26529. bottom = Math.ceil(this.domElement.clientHeight * view.bottom),
  26530. width = Math.ceil(this.domElement.clientWidth * view.width),
  26531. height = Math.ceil(this.domElement.clientHeight * view.height),
  26532. top = this.domElement.clientHeight - bottom - height;
  26533. return {
  26534. left,
  26535. bottom,
  26536. width,
  26537. height,
  26538. top
  26539. };
  26540. };
  26541. var getView = (view, left, bottom, width, height, top) => {
  26542. this.mouse.set(x - left, y - top);
  26543. Utils.convertScreenPositionToNDC(pointer, this.mouse, width, height);
  26544. //console.log('更新pointer2',this.pointer.toArray())
  26545. camera = view.camera;
  26546. viewport = view;
  26547. };
  26548. if (viewForceAt) {
  26549. var {
  26550. left: _left,
  26551. bottom: _bottom,
  26552. width: _width,
  26553. height: _height,
  26554. top: _top
  26555. } = getDimension(viewForceAt);
  26556. getView(viewForceAt, _left, _bottom, _width, _height, _top);
  26557. } else {
  26558. var length = this.viewer.viewports.length;
  26559. //var getif = false
  26560. for (var i = 0; i < length; i++) {
  26561. var view = this.viewer.viewports[i];
  26562. if (!view.active) continue;
  26563. var {
  26564. left,
  26565. bottom,
  26566. width,
  26567. height,
  26568. top
  26569. } = getDimension(view);
  26570. if (x >= left && x <= left + width && y >= top && y <= top + height) {
  26571. getView(view, left, bottom, width, height, top);
  26572. //getif = true
  26573. break;
  26574. }
  26575. }
  26576. }
  26577. return {
  26578. camera,
  26579. viewport,
  26580. pointer
  26581. };
  26582. }
  26583. ifBlockedByIntersect() {
  26584. var {
  26585. point,
  26586. margin = 0,
  26587. cameraPos,
  26588. pickWindowSize,
  26589. pano,
  26590. useDepthTex,
  26591. viewport
  26592. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  26593. //某点是否被遮挡(不允许camera修改位置, 因为depthTex不好置换)
  26594. viewport = viewport || this.hoverViewport || viewer.mainViewport;
  26595. var intersect = this.getIntersect({
  26596. viewport,
  26597. onlyGetIntersect: true,
  26598. pickWindowSize,
  26599. useDepthTex,
  26600. point,
  26601. cameraPos,
  26602. pano
  26603. });
  26604. var cameraPos_ = !cameraPos && pano ? pano.position : cameraPos || viewport.view.position;
  26605. if (intersect && intersect.distance + margin <= point.distanceTo(cameraPos_)) {
  26606. return intersect; //被遮挡
  26607. }
  26608. //点云模式,对没加载出的点云不准确。 尤其是需要修改相机位置时,因临时修改并不能使点云加载。
  26609. }
  26610. collectClosePoints(viewport, forceUpdate) {
  26611. //获取吸附点
  26612. if (!Potree.settings.adsorption) return;
  26613. var point2ds = [];
  26614. //吸附测量线端点
  26615. viewer.scene.measurements.forEach(e => {
  26616. if (this.measuring.includes(e)) return; //不吸附到正在拖拽的自身
  26617. point2ds.push(...e.getPointsPos2d(viewport, forceUpdate));
  26618. });
  26619. return point2ds;
  26620. }
  26621. getIntersect() {
  26622. var {
  26623. viewport,
  26624. onlyGetIntersect,
  26625. pickWindowSize,
  26626. dontIntersect,
  26627. usePointcloud,
  26628. useDepthTex,
  26629. cameraPos,
  26630. point,
  26631. pano,
  26632. clientX,
  26633. clientY
  26634. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  26635. // usePointcloud:必须使用点云
  26636. var intersect, intersectPoint, intersectOnModel, allElements;
  26637. var camera = viewport.camera;
  26638. var raycaster;
  26639. viewer.addTimeMark('getIntersect', 'start');
  26640. var getByDepthTex = () => {
  26641. var intersect;
  26642. if (point) {
  26643. var _cameraPos = pano ? pano.position : camera.position;
  26644. var _dir = new Vector3().subVectors(point, _cameraPos).normalize();
  26645. intersect = {
  26646. dir: _dir
  26647. };
  26648. } else {
  26649. intersect = Utils.getIntersect(camera, [viewer.images360.cube], this.pointer, raycaster);
  26650. }
  26651. intersectPoint = viewer.images360.depthSampler.sample(intersect, pano, !!point); //可能不准确, 因pano可能未加载depthTex
  26652. if (intersectPoint && Potree.settings.depTexLocBindDataset) {
  26653. intersectPoint.pointcloud = (pano || viewer.images360.currentPano).pointcloud;
  26654. //在全景模式下,虽然深度图上的点可能对应别的pointcloud,但因为是在当前全景图处得到的,所以即使将原本对应的点云移走,该点也不移动是有道理的。它可以永远跟着该全景图。
  26655. }
  26656. };
  26657. var getByCloud = () => {
  26658. var pointer, mouse;
  26659. if (point) {
  26660. //指定了目标点,而非只是用pointer所在位置
  26661. cameraPos && camera.position.copy(cameraPos);
  26662. camera.lookAt(point);
  26663. camera.updateMatrixWorld();
  26664. pointer = this.pointer.clone();
  26665. mouse = this.mouse.clone();
  26666. this.pointer.set(0, 0); //画布中心
  26667. this.mouse.set(Math.round(viewport.resolution.x / 2), Math.round(viewport.resolution.y / 2));
  26668. }
  26669. intersectPoint = viewport.noPointcloud || dontIntersect ? null : Utils.getMousePointCloudIntersection(viewport, this.mouse, this.pointer, camera, this.viewer, this.viewer.scene.pointclouds, {
  26670. pickClipped: true,
  26671. measuring: this.measuring.length > 0,
  26672. pickWindowSize,
  26673. cameraChanged: !!point
  26674. });
  26675. //恢复
  26676. if (point) {
  26677. viewport.view.applyToCamera(camera);
  26678. this.pointer.copy(pointer);
  26679. this.mouse.copy(mouse);
  26680. }
  26681. };
  26682. if (this.measuring.length && Potree.settings.adsorption) {
  26683. //吸附
  26684. var points = this.collectClosePoints(viewport);
  26685. var points2 = points.filter(e => e.trueSide && e.inSight && math.closeTo(this.mouse, e.posInViewport, Potree.config.measure.adsorptMinDis));
  26686. var disArr = points2.map(e => e.pos.distanceToSquared(this.mouse));
  26687. var min = points2.slice().sort((a, b) => disArr[points.indexOf(a)] - disArr[points.indexOf(b)]);
  26688. if (min[0]) {
  26689. intersect = {
  26690. //hoveredElement
  26691. location: min[0].pos3d,
  26692. //point: {normal: allElements[0].face.normal },
  26693. //normal
  26694. //distance
  26695. object: min[0].object,
  26696. adsorption: true
  26697. };
  26698. console.log('找到吸附点', min[0].pos3d, min[0].object.uuid);
  26699. }
  26700. }
  26701. if (!intersect) {
  26702. var canUseDepthTex = (Potree.settings.displayMode == 'showPanos' || useDepthTex) && viewer.images360.currentPano.pointcloud.hasDepthTex && viewport == viewer.mainViewport && !usePointcloud;
  26703. if (canUseDepthTex) getByDepthTex();else getByCloud();
  26704. /* if(canUseDepthTex && this.measuring.length){
  26705. getByDepthTex()
  26706. }else{
  26707. getByCloud()
  26708. if(!intersectPoint && canUseDepthTex ){ //若在测量,先尝试点云,再用全景 //后来发现有深度图的点云全景visibleNode为空,pick不到的
  26709. getByDepthTex()
  26710. }
  26711. } */
  26712. //console.log(viewport.name , intersectPoint && intersectPoint.location )
  26713. if (Potree.settings.intersectOnObjs && !dontIntersect) {
  26714. if (point) {
  26715. raycaster = new Raycaster();
  26716. var dir = new Vector3().subVectors(point, camera.position).normalize();
  26717. raycaster.set(camera.position, dir); //var origin = new THREE.Vector3(pointer.x, pointer.y, -1).unproject(camera),
  26718. }
  26719. allElements = this.getHoveredElements(viewer.objs.children, true, raycaster);
  26720. if (allElements[0]) {
  26721. var quaternion = new Quaternion();
  26722. var nor = allElements[0].face && allElements[0].face.normal;
  26723. nor && allElements[0].oriObject.matrixWorld.decompose(new Vector3(), quaternion, new Vector3());
  26724. intersectOnModel = {
  26725. //模拟点云的intersectPoint的结构写法
  26726. hoveredElement: allElements[0],
  26727. location: allElements[0].point,
  26728. //point: {normal: allElements[0].face.normal },
  26729. normal: nor && nor.applyQuaternion(quaternion),
  26730. distance: allElements[0].distance,
  26731. object: allElements[0].object
  26732. };
  26733. }
  26734. }
  26735. if (intersectPoint && intersectOnModel) {
  26736. if (intersectPoint.distance < intersectOnModel.distance) {
  26737. intersect = intersectPoint;
  26738. } else {
  26739. intersect = intersectOnModel;
  26740. }
  26741. } else {
  26742. intersect = intersectOnModel || intersectPoint;
  26743. }
  26744. }
  26745. if (viewport.camera.type == 'OrthographicCamera' /* == 'mapViewport' */) {
  26746. var pos3d = new Vector3(this.pointer.x, this.pointer.y, -1).unproject(viewport.camera); //z:-1朝外
  26747. if (!intersect) {
  26748. intersect = {};
  26749. }
  26750. intersect.orthoIntersect = pos3d.clone();
  26751. }
  26752. //记录全部hover到的:
  26753. if (intersect) {
  26754. intersect.allElements = allElements;
  26755. intersect.pointclouds = intersectPoint ? intersectPoint.pointclouds : [];
  26756. }
  26757. viewer.addTimeMark('getIntersect', 'end');
  26758. //点云费时:2-15ms
  26759. //深度图费时: 0.1-0.2ms
  26760. /*
  26761. intersect && intersect.location && intersect.location.applyMatrix4(viewer.scene.scene.matrix)//add
  26762. */
  26763. if (onlyGetIntersect) {
  26764. return intersect;
  26765. }
  26766. if (intersect) {
  26767. if (viewer.showCoordType) {
  26768. //显示坐标位置时
  26769. var pos = intersect.point.position.toArray();
  26770. if (viewer.showCoordType == "local") {} else if (viewer.showCoordType == "lonlat") {
  26771. pos = viewer.transform.lonlatToLocal.inverse(pos);
  26772. } else {
  26773. pos = viewer.transform.lonlatToLocal.inverse(pos);
  26774. pos = viewer.transform.lonlatTo4550.forward(pos);
  26775. }
  26776. viewer.dispatchEvent({
  26777. type: "coordinateChange",
  26778. pos
  26779. });
  26780. }
  26781. }
  26782. //console.log('getIntersect', !!intersectPoint)
  26783. this.intersect = intersect;
  26784. intersect && (this.hoverViewport.lastIntersect = intersect);
  26785. return intersect;
  26786. }
  26787. onMouseMove(e) {
  26788. return this.dealPointerMove(e);
  26789. }
  26790. dealPointerMove(e, isTouch) {
  26791. if (this.interactHistory.move) return; //一帧只触发一次
  26792. this.interactHistory.move = 1;
  26793. if (isTouch) {
  26794. var {
  26795. camera,
  26796. viewport
  26797. } = this.updateTouchesInfo(e);
  26798. } else {
  26799. var {
  26800. camera,
  26801. viewport
  26802. } = this.getPointerInViewport(e.clientX, e.clientY, this.dragViewport);
  26803. }
  26804. this.hoverViewport = viewport;
  26805. if (!viewport) return; //刚变化viewport时会找不到
  26806. var isFlying = this.viewer.viewports.some(e => e.view.isFlying()) || viewer.scene.cameraAnimations.some(c => c.onUpdate);
  26807. var intersect;
  26808. if (e.onlyGetIntersect || !this.drag || this.drag.object || viewport.alignment) {
  26809. //没有拖拽物体,但按下鼠标了的话,不intersect。触屏的就能直接避免intersect
  26810. var dontIntersect = this.drag && viewport.alignment || isFlying || !Potree.settings.intersectWhenHover; // flying 时可能卡顿
  26811. //console.log('dontIntersectPointcloud',dontIntersectPointcloud)
  26812. intersect = this.getIntersect(Object.assign({}, e, {
  26813. viewport,
  26814. dontIntersect,
  26815. clientX: e.clientX,
  26816. clientY: e.clientY
  26817. })); //数据集多的时候卡顿
  26818. }
  26819. if (e.onlyGetIntersect) {
  26820. return intersect;
  26821. }
  26822. e.preventDefault();
  26823. if (this.drag) {
  26824. //有拖拽(不一定拖拽了物体, 也不一定按下了鼠标)
  26825. this.drag.mouse = isTouch ? 1 : e.buttons;
  26826. //add:
  26827. //this.drag.pointer = this.pointer.clone();
  26828. //this.drag.hoverViewport = this.hoverViewport
  26829. this.drag.pointerDelta.subVectors(this.pointer, this.drag.end);
  26830. this.drag.end.copy(this.pointer);
  26831. var dragConsumed = false;
  26832. if (this.drag.object && (e.buttons == Buttons$1.NONE || !this.drag.notPressMouse)) {
  26833. //如果是本不需要按鼠标的拖拽,但按下了鼠标,就不执行这段(改为拖拽场景,如添加测量时突然拖拽画面)
  26834. if (this.logMessages) console.log(this.constructor.name + ': drag: ' + this.drag.object.name);
  26835. var refused;
  26836. this.drag.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26837. type: 'drag',
  26838. //拖拽物体
  26839. refuse: () => {
  26840. refused = true;
  26841. }
  26842. }));
  26843. if (!refused) dragConsumed = true;
  26844. viewer.dispatchEvent('content_changed');
  26845. }
  26846. if (!dragConsumed) {
  26847. if (this.logMessages) console.log(this.constructor.name + ': drag: ');
  26848. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26849. type: 'global_drag' //拖拽画面
  26850. //consume: () => {dragConsumed = true;}
  26851. }));
  26852. }
  26853. }
  26854. if (!isTouch || e.touches.length == 1) {
  26855. if ((!this.drag || this.drag.notPressMouse || Potree.settings.intersectOnObjs && this.drag.object) && !isFlying) {
  26856. /* let blacklist = this.drag && this.drag */
  26857. var hoveredElements = this.getHoveredElements();
  26858. if (hoveredElements.length > 0) {
  26859. var names = hoveredElements.map(h => h.object.name).join(", ");
  26860. if (this.logMessages) console.log("".concat(this.constructor.name, ": onMouseMove; hovered: '").concat(names, "'"));
  26861. }
  26862. var cur = hoveredElements.find(a => a.object);
  26863. var curr = cur && cur.object; //hoveredElements.map(a => a.object).find(a => true);//只取第一个
  26864. var prev = this.lastMouseoverElement; //this.hoveredElements.map(a => a.object).find(a => true);
  26865. if (curr !== prev) {
  26866. if (curr) {
  26867. if (this.logMessages) console.log("".concat(this.constructor.name, ": mouseover: ").concat(curr.name));
  26868. curr.dispatchEvent({
  26869. type: 'mouseover',
  26870. object: curr,
  26871. hoveredElement: cur
  26872. });
  26873. }
  26874. if (prev) {
  26875. if (this.logMessages) console.log("".concat(this.constructor.name, ": mouseleave: ").concat(prev.name));
  26876. prev.dispatchEvent({
  26877. type: 'mouseleave',
  26878. object: prev
  26879. });
  26880. }
  26881. this.lastMouseoverElement = curr;
  26882. viewer.dispatchEvent('content_changed');
  26883. }
  26884. if (hoveredElements.length > 0) {
  26885. var object = hoveredElements.map(e => e.object).find(e => e._listeners && e._listeners['mousemove']);
  26886. if (object) {
  26887. object.dispatchEvent({
  26888. type: 'mousemove',
  26889. object: object
  26890. });
  26891. }
  26892. }
  26893. this.hoveredElements = hoveredElements;
  26894. }
  26895. //this.intersect = this.getWholeIntersect()
  26896. this.viewer.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26897. type: 'global_mousemove'
  26898. }));
  26899. this.containsMouse = true;
  26900. }
  26901. }
  26902. onMouseWheel(e) {
  26903. if (!this.enabled) return;
  26904. if (this.logMessages) console.log(this.constructor.name + ": onMouseWheel");
  26905. e.preventDefault();
  26906. var delta = 0;
  26907. if (e.wheelDelta !== undefined) {
  26908. // WebKit / Opera / Explorer 9
  26909. delta = e.wheelDelta;
  26910. } else if (e.detail !== undefined) {
  26911. // Firefox
  26912. delta = -e.detail;
  26913. }
  26914. var ndelta = Math.sign(delta);
  26915. // this.wheelDelta += Math.sign(delta);
  26916. if (!this.hoverViewport) {
  26917. //调试手机版时会无
  26918. var {
  26919. viewport
  26920. } = this.getPointerInViewport(e.clientX, e.clientY);
  26921. this.hoverViewport = viewport;
  26922. }
  26923. if (this.hoveredElement) {
  26924. this.hoveredElement.object.dispatchEvent($.extend(this.getEventDesc(e, isTouch), {
  26925. type: 'mousewheel',
  26926. delta: ndelta,
  26927. object: this.hoveredElement.object
  26928. }));
  26929. } else {
  26930. this.viewer.dispatchEvent($.extend(this.getEventDesc(e), {
  26931. type: 'global_mousewheel',
  26932. delta: ndelta
  26933. }));
  26934. }
  26935. setTimeout(() => {
  26936. this.dealPointerMove(e); //add 在更新完view后重新获取intersect 和 drag
  26937. }, 1); //只延迟1会崩溃吗
  26938. }
  26939. startDragging(object) {
  26940. var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  26941. var name = object ? object.name : "no name";
  26942. if (this.logMessages) console.log("".concat(this.constructor.name, ": startDragging: '").concat(name, "'"));
  26943. this.drag = {
  26944. start: this.pointer.clone(),
  26945. end: this.pointer.clone(),
  26946. pointerDelta: new Vector2(0, 0),
  26947. object: object,
  26948. hoverViewport: this.hoverViewport,
  26949. //会变化
  26950. dragViewport: this.hoverViewport //不变
  26951. };
  26952. if (args) {
  26953. for (var key of Object.keys(args)) {
  26954. this.drag[key] = args[key];
  26955. }
  26956. }
  26957. if (object) {
  26958. object.dispatchEvent($.extend(this.getEventDesc(), {
  26959. type: 'startDragging'
  26960. }));
  26961. }
  26962. }
  26963. /* getMousePointCloudIntersection (mouse) {
  26964. return Utils.getMousePointCloudIntersection(
  26965. this.mouse,
  26966. this.scene.getActiveCamera(),
  26967. this.viewer,
  26968. this.scene.pointclouds);
  26969. } */
  26970. toggleSelection(object) {
  26971. var oldSelection = this.selection;
  26972. var index = this.selection.indexOf(object);
  26973. if (index === -1) {
  26974. this.selection.push(object);
  26975. object.dispatchEvent({
  26976. type: 'select'
  26977. });
  26978. } else {
  26979. this.selection.splice(index, 1);
  26980. object.dispatchEvent({
  26981. type: 'deselect'
  26982. });
  26983. }
  26984. this.dispatchEvent({
  26985. type: 'selection_changed',
  26986. oldSelection: oldSelection,
  26987. selection: this.selection
  26988. });
  26989. viewer.dispatchEvent('content_changed');
  26990. }
  26991. deselect(object) {
  26992. var oldSelection = this.selection;
  26993. var index = this.selection.indexOf(object);
  26994. if (index >= 0) {
  26995. this.selection.splice(index, 1);
  26996. object.dispatchEvent({
  26997. type: 'deselect'
  26998. });
  26999. this.dispatchEvent({
  27000. type: 'selection_changed',
  27001. oldSelection: oldSelection,
  27002. selection: this.selection
  27003. });
  27004. }
  27005. viewer.dispatchEvent('content_changed');
  27006. }
  27007. deselectAll() {
  27008. for (var object of this.selection) {
  27009. object.dispatchEvent({
  27010. type: 'deselect'
  27011. });
  27012. }
  27013. var oldSelection = this.selection;
  27014. if (this.selection.length > 0) {
  27015. this.selection = [];
  27016. this.dispatchEvent({
  27017. type: 'selection_changed',
  27018. oldSelection: oldSelection,
  27019. selection: this.selection
  27020. });
  27021. }
  27022. viewer.dispatchEvent('content_changed');
  27023. }
  27024. isSelected(object) {
  27025. var index = this.selection.indexOf(object);
  27026. return index !== -1;
  27027. }
  27028. registerInteractiveObject(object) {
  27029. this.interactiveObjects.add(object);
  27030. }
  27031. removeInteractiveObject(object) {
  27032. this.interactiveObjects.delete(object);
  27033. }
  27034. registerInteractiveScene(scene) {
  27035. var index = this.interactiveScenes.indexOf(scene);
  27036. if (index === -1) {
  27037. this.interactiveScenes.push(scene);
  27038. }
  27039. }
  27040. unregisterInteractiveScene(scene) {
  27041. var index = this.interactiveScenes.indexOf(scene);
  27042. if (index > -1) {
  27043. this.interactiveScenes.splice(index, 1);
  27044. }
  27045. }
  27046. getHoveredElement() {
  27047. var hoveredElements = this.getHoveredElements();
  27048. if (hoveredElements.length > 0) {
  27049. return hoveredElements[0];
  27050. } else {
  27051. return null;
  27052. }
  27053. }
  27054. getHoveredElements(interactables, dontCheckDis, raycaster) {
  27055. if (!interactables) {
  27056. var scenes = this.hoverViewport.interactiveScenes || this.interactiveScenes.concat(this.scene);
  27057. var interactableListeners = ['mouseup', 'mousemove', 'mouseover', 'mouseleave', 'drag', 'drop', 'click', 'select', 'deselect'];
  27058. interactables = [];
  27059. for (var scene of scenes) {
  27060. scene.traverseVisible(node => {
  27061. //检测加了侦听的object
  27062. if (node._listeners && node.visible && !this.blacklist.has(node)) {
  27063. var hasInteractableListener = interactableListeners.filter(e => {
  27064. return node._listeners[e] !== undefined;
  27065. }).length > 0;
  27066. if (hasInteractableListener) {
  27067. interactables.push(node);
  27068. }
  27069. }
  27070. });
  27071. }
  27072. } else interactables = interactables.filter(e => e.visible);
  27073. var camera = this.hoverViewport.camera;
  27074. if (!raycaster) {
  27075. var ray = Utils.mouseToRay(this.pointer, camera);
  27076. raycaster = new Raycaster();
  27077. raycaster.ray.set(ray.origin, ray.direction);
  27078. raycaster.camera = camera; //add
  27079. }
  27080. if (camera.type == "OrthographicCamera") {
  27081. //使无论多远,threshold区域都是一样宽的
  27082. raycaster.params.Line.threshold = 20 / camera.zoom;
  27083. } else {
  27084. raycaster.params.Line.threshold = 0.04; //相对长度
  27085. }
  27086. raycaster.params.Line2 = {
  27087. threshold: browser.isMobile() ? 100 : 20
  27088. }; //拓宽的lineWidth
  27089. //raycaster.layers.enableAll()//add
  27090. Potree.Utils.setCameraLayers(raycaster,
  27091. //设置能识别到的layers(如空间模型里只有mapViewer能识别到marker)
  27092. ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model', 'bothMapAndScene'], this.hoverViewport && this.hoverViewport.extraEnableLayers);
  27093. //this.hoverViewport.beforeRender && this.hoverViewport.beforeRender()
  27094. viewer.dispatchEvent({
  27095. type: 'raycaster',
  27096. viewport: this.hoverViewport,
  27097. raycaster,
  27098. viewer: this.viewer,
  27099. interactables
  27100. }); //add
  27101. var intersections = raycaster.intersectObjects(interactables, true, null, true); //原本是false 检测不到children
  27102. var intersectionsCopy = intersections.slice();
  27103. if (this.intersect && this.intersect.distance != void 0 && !dontCheckDis) {
  27104. //add
  27105. intersections = intersections.filter(e => {
  27106. if (this.intersect.hoveredElement && this.intersect.hoveredElement.oriObject == e.object) return true;
  27107. var material = e.object.material;
  27108. return e.object.pickDontCheckDis || (material.depthTest == false || material.depthWrite == false) && !material.realUseDepth //!material.depthTestWhenPick
  27109. || (material.useDepth ? e.distance <= this.intersect.distance + material.uniforms.clipDistance.value : e.distance <= this.intersect.distance);
  27110. //maxClipFactor是否需要考虑?
  27111. });
  27112. }
  27113. intersections = intersections.map(e => {
  27114. //add 转化为interactables
  27115. var object = e.object;
  27116. do {
  27117. if (interactables.includes(object)) {
  27118. e.oriObject = e.object;
  27119. e.object = object;
  27120. break;
  27121. }
  27122. object = object.parent;
  27123. } while (object);
  27124. return e;
  27125. });
  27126. //add for测量线,在检测到sphere时优先选中sphere而非线
  27127. //intersections = intersections.sort(function(a,b){return b.object.renderOrder-a.object.renderOrder}) // 降序
  27128. intersections = intersections.sort(function (a, b) {
  27129. var order2 = b.object.pickOrder || 0;
  27130. var order1 = a.object.pickOrder || 0;
  27131. return order2 - order1;
  27132. }); // 降序
  27133. //console.log('getHoveredElement ', intersections)
  27134. return intersections;
  27135. }
  27136. /* setScene (scene) {
  27137. this.deselectAll();
  27138. this.scene = scene;
  27139. } */
  27140. update(delta) {}
  27141. /*getNormalizedDrag () {
  27142. if (!this.drag) {
  27143. return new THREE.Vector2(0, 0);
  27144. }
  27145. let diff = new THREE.Vector2().subVectors(this.drag.end, this.drag.start);
  27146. diff.x = diff.x / this.domElement.clientWidth;
  27147. diff.y = diff.y / this.domElement.clientHeight;
  27148. return diff;
  27149. }
  27150. getNormalizedLastDrag () {
  27151. if (!this.drag) {
  27152. return new THREE.Vector2(0, 0);
  27153. }
  27154. let mouseDelta = this.drag.mouseDelta.clone();
  27155. mouseDelta.x = mouseDelta.x / this.domElement.clientWidth;
  27156. mouseDelta.y = mouseDelta.y / this.domElement.clientHeight;
  27157. return mouseDelta;
  27158. } */
  27159. getMouseDirection(pointer) {
  27160. //add
  27161. pointer = pointer || this.pointer;
  27162. var camera = this.hoverViewport.camera;
  27163. var t = new Vector3(pointer.x, pointer.y, -1).unproject(camera),
  27164. i = new Vector3(pointer.x, pointer.y, 1).unproject(camera);
  27165. return {
  27166. origin: t,
  27167. direction: i.clone().sub(t).normalize()
  27168. };
  27169. }
  27170. }
  27171. class ViewerBase extends EventDispatcher {
  27172. constructor(domElement) {
  27173. var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  27174. super();
  27175. this.name = args.name;
  27176. this.renderArea = domElement;
  27177. this.oldResolution = new Vector2();
  27178. this.oldResolution2 = new Vector2();
  27179. this.screenSizeInfo = {
  27180. W: 0,
  27181. H: 0,
  27182. pixelRatio: 1,
  27183. windowWidth: 0,
  27184. windowHeight: 0
  27185. };
  27186. this.initContext(args);
  27187. this.addEventListener('content_changed', () => {
  27188. //画面改变,需要渲染
  27189. this.needRender = true;
  27190. //console.log('needRender')
  27191. });
  27192. }
  27193. initContext(args) {
  27194. //console.log(`initializing three.js ${THREE.REVISION}`);
  27195. var width = this.renderArea.clientWidth;
  27196. var height = this.renderArea.clientHeight;
  27197. var contextAttributes = {
  27198. alpha: true,
  27199. //支持透明
  27200. depth: true,
  27201. stencil: false,
  27202. antialias: !!args.antialias,
  27203. preserveDrawingBuffer: args.preserveDrawingBuffer || false,
  27204. powerPreference: "high-performance"
  27205. };
  27206. var canvas = document.createElement("canvas");
  27207. var context = canvas.getContext('webgl2', contextAttributes); //不用webgl2是因为有的写法在webgl2不支持 如gl_FragDepthEXT
  27208. if (context) {
  27209. Potree.settings.isWebgl2 = true;
  27210. }
  27211. this.renderer = new WebGLRenderer({
  27212. premultipliedAlpha: false,
  27213. canvas: canvas,
  27214. context: context
  27215. });
  27216. this.renderer.sortObjects = true; //原先false 打开了renderOrder才奏效
  27217. //this.renderer.setSize(width, height);
  27218. this.renderer.autoClear = args.autoClear || false;
  27219. //args.clearColor = args.clearColor || '#aa0033'
  27220. args.clearColor && this.renderer.setClearColor(args.clearColor);
  27221. this.renderArea.appendChild(this.renderer.domElement);
  27222. this.renderer.domElement.tabIndex = '2222';
  27223. this.renderer.domElement.style.position = 'absolute';
  27224. this.renderer.domElement.addEventListener('mousedown', () => {
  27225. this.renderer.domElement.focus();
  27226. });
  27227. //this.renderer.domElement.focus();
  27228. // NOTE: If extension errors occur, pass the string into this.renderer.extensions.get(x) before enabling
  27229. // enable frag_depth extension for the interpolation shader, if available
  27230. var gl = this.renderer.getContext();
  27231. gl.getExtension('EXT_frag_depth');
  27232. gl.getExtension('WEBGL_depth_texture');
  27233. gl.getExtension('WEBGL_color_buffer_float'); // Enable explicitly for more portability, EXT_color_buffer_float is the proper name in WebGL 2
  27234. if (gl.createVertexArray == null) {
  27235. var extVAO = gl.getExtension('OES_vertex_array_object');
  27236. if (!extVAO) {
  27237. throw new Error("OES_vertex_array_object extension not supported");
  27238. }
  27239. gl.createVertexArray = extVAO.createVertexArrayOES.bind(extVAO);
  27240. gl.bindVertexArray = extVAO.bindVertexArrayOES.bind(extVAO);
  27241. }
  27242. /* let oldClear = gl.clear;
  27243. gl.clear = (bits)=>{
  27244. console.error('clear')
  27245. }
  27246. */
  27247. }
  27248. updateScreenSize() {
  27249. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  27250. //有可能需要让viewport来判断,当窗口大小不变但viewport大小变时
  27251. if (this.screenshoting && !o.forceUpdateSize) return; //截图时不允许因窗口改变大小而updateScreenSize
  27252. var render = false,
  27253. ratio,
  27254. w,
  27255. h;
  27256. //记录应当render的大小
  27257. if (o.width != void 0 && o.height != void 0) {
  27258. w = o.width;
  27259. h = o.height;
  27260. render = true;
  27261. ratio = 1;
  27262. } else {
  27263. w = this.renderArea.clientWidth;
  27264. h = this.renderArea.clientHeight;
  27265. if (w !== this.screenSizeInfo.W || h !== this.screenSizeInfo.H || o.forceUpdateSize || this.screenSizeInfo.pixelRatio != window.devicePixelRatio) {
  27266. this.screenSizeInfo.W = w;
  27267. this.screenSizeInfo.H = h;
  27268. render = true;
  27269. this.screenSizeInfo.pixelRatio = window.devicePixelRatio; //如果player放在小窗口了,也要监测devicePixelRatio,因为缩放时client宽高不会改变
  27270. //config.isMobile ? (ratio = Math.min(window.devicePixelRatio, 2)) : (ratio = window.devicePixelRatio)
  27271. ratio = window.devicePixelRatio;
  27272. }
  27273. }
  27274. if (render) {
  27275. this.setSize(w, h, ratio, o.forTarget);
  27276. }
  27277. }
  27278. setSize(width, height, devicePixelRatio, onlyForTarget) {
  27279. //console.log('setSize', width)
  27280. if (!onlyForTarget) {
  27281. //onlyForTarget表示不更改当前renderer,只是为了rendertarget才要改变viewport
  27282. this.renderer.setPixelRatio(devicePixelRatio);
  27283. this.renderer.setSize(width, height); // resize之后会自动clear(似乎因为setScissor ),所以一定要立刻绘制,所以setSize要在cameraChanged、update之前
  27284. }
  27285. //this.composer && this.composer.setSize(width, height);
  27286. if (this.viewports) {
  27287. this.viewports.forEach((view, i) => {
  27288. //if(!view.active)return
  27289. var width_ = width * view.width;
  27290. var height_ = height * view.height;
  27291. view.setResolution(Math.ceil(width_), Math.ceil(height_), width, height);
  27292. if (height_ == 0) return; //avoid NAN
  27293. var aspect = width_ / height_; //camera的参数精确些,不用视口的归整的resolution像素值,否则hasChange无法为true, 导致canvasResize了但map没update从而闪烁
  27294. view.camera.aspect = aspect;
  27295. if (view.camera.type == "OrthographicCamera") {
  27296. /* //不改宽度 同4dkk
  27297. var heightHalf = view.camera.right / aspect
  27298. view.camera.top = heightHalf
  27299. view.camera.bottom = -heightHalf */
  27300. //高宽都改 使大小不随视口大小改变 navvis (直接和视口大小一致即可,通过zoom来定大小)
  27301. view.camera.left = -width_ / 2;
  27302. view.camera.right = width_ / 2;
  27303. view.camera.bottom = -height_ / 2;
  27304. view.camera.top = height_ / 2;
  27305. } else {}
  27306. view.camera.updateProjectionMatrix();
  27307. });
  27308. }
  27309. if (!onlyForTarget) {
  27310. //因为onlyForTarget不传递devicePixelRatio所以不发送了
  27311. this.dispatchEvent('viewerResize');
  27312. this.viewports.forEach(e => {
  27313. this.ifEmitResize({
  27314. viewport: e,
  27315. deviceRatio: devicePixelRatio
  27316. });
  27317. });
  27318. }
  27319. }
  27320. ifEmitResize(e) {
  27321. //切换viewport渲染时, 若这些viewport大小不同就发送一次, 通知一些材质更新resolution。
  27322. //console.log('ifEmitResize',e.viewport.name,e.viewport.resolution2 )
  27323. if (!e.viewport.resolution.equals(this.oldResolution) || !e.viewport.resolution2.equals(this.oldResolution2)) {
  27324. this.dispatchEvent($.extend(e, {
  27325. type: 'resize'
  27326. }));
  27327. this.oldResolution.copy(e.viewport.resolution);
  27328. this.oldResolution2.copy(e.viewport.resolution2);
  27329. }
  27330. }
  27331. cameraChanged() {
  27332. //判断相机是否改变
  27333. var changed = false;
  27334. /* if(this.needRender){
  27335. this.needRender = false
  27336. return true
  27337. } */
  27338. for (var i = 0, j = this.viewports.length; i < j; i++) {
  27339. var viewport = this.viewports[i];
  27340. var changeInfo = viewport.cameraChanged();
  27341. if (changeInfo.changed) {
  27342. changed = true;
  27343. //if(!this.changeTime ||this.changeTime<100){
  27344. this.dispatchEvent({
  27345. type: "camera_changed",
  27346. camera: viewport.camera,
  27347. viewport,
  27348. changeInfo
  27349. });
  27350. //this.changeTime = (this.changeTime || 0) +1
  27351. //}
  27352. viewport.needRender = true; //直接写这咯
  27353. if (changeInfo.resolutionChanged) {
  27354. this.ifEmitResize({
  27355. viewport
  27356. }); //for map
  27357. }
  27358. }
  27359. }
  27360. return changed;
  27361. }
  27362. makeScreenshot(size, viewports, compressRatio) {
  27363. //暂时不要指定viewports渲染,但也可以
  27364. var {
  27365. width,
  27366. height
  27367. } = size;
  27368. /* let oldBudget = Potree.pointBudget;
  27369. Potree.pointBudget = Math.max(10 * 1000 * 1000, 2 * oldBudget);
  27370. let result = Potree.updatePointClouds(this.scene.pointclouds, camera, size );
  27371. Potree.pointBudget = oldBudget;
  27372. this.dispatchEvent({ //resize everything such as lines targets
  27373. type: 'resize',
  27374. resolution: new THREE.Vector2(width,height),
  27375. });*/
  27376. var target = new WebGLRenderTarget(width, height, {
  27377. format: RGBAFormat
  27378. });
  27379. this.setSize(width, height, 1, true);
  27380. this.render({
  27381. target,
  27382. //camera ,
  27383. viewports: viewports || this.viewports,
  27384. screenshot: true,
  27385. width,
  27386. height,
  27387. resize: true //需要resize
  27388. });
  27389. var dataUrl = Potree.Utils.renderTargetToDataUrl(target, width, height, this.renderer, compressRatio);
  27390. /* let pixelCount = width * height;
  27391. let buffer = new Uint8Array(4 * pixelCount);
  27392. this.renderer.readRenderTargetPixels(target, 0, 0, width, height, buffer);
  27393. let dataUrl = Potree.Utils.pixelsArrayToDataUrl(buffer, width, height, compressRatio) */
  27394. target.dispose();
  27395. //resize back
  27396. //this.updateScreenSize({forceUpdateSize:true})
  27397. return {
  27398. width,
  27399. height,
  27400. dataUrl
  27401. };
  27402. }
  27403. dispose() {
  27404. var scene = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.scene;
  27405. scene.clear();
  27406. this.renderer.dispose();
  27407. this.renderer.forceContextLoss();
  27408. var gl = this.renderer.getContext();
  27409. gl.getExtension("WEBGL_lose_context") && gl.getExtension("WEBGL_lose_context").loseContext();
  27410. this.renderArea.removeChild(this.renderer.domElement);
  27411. this.dispatchEvent('dispose');
  27412. }
  27413. }
  27414. class Viewport extends EventDispatcher {
  27415. constructor(view, camera) {
  27416. var prop = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  27417. //目前不支持换camera
  27418. super();
  27419. this.left = prop.left;
  27420. this.bottom = prop.bottom;
  27421. this.width = prop.width;
  27422. this.height = prop.height;
  27423. this.name = prop.name;
  27424. this.view = view;
  27425. this.camera = camera;
  27426. this.active = true;
  27427. this.unableChangePos = false;
  27428. this.noPointcloud;
  27429. //this.keys = [...] firstPersonCtl....
  27430. this.resolution = new Vector2();
  27431. this.resolution2 = new Vector2();
  27432. this.offset = new Vector2(); //viewportOffset 范围从0-整个画布的像素
  27433. this.extraEnableLayers = prop.extraEnableLayers || []; //额外可展示的层
  27434. this.cameraLayers = prop.cameraLayers;
  27435. this.pixelRatio = prop.pixelRatio; //如果规定pixelRatio的话要传,这样就覆盖devicePicelRatio, 如magnifier
  27436. }
  27437. clone() {
  27438. return Common.CloneClassObject(this);
  27439. }
  27440. getMoveSpeed() {
  27441. return this.moveSpeed;
  27442. }
  27443. setMoveSpeed(e) {
  27444. this.moveSpeed = e;
  27445. }
  27446. layersAdd(name) {
  27447. this.extraEnableLayers.includes(name) || this.extraEnableLayers.push(name);
  27448. }
  27449. layersRemove(name) {
  27450. var index = this.extraEnableLayers.indexOf(name);
  27451. if (index > -1) {
  27452. this.extraEnableLayers.splice(index, 1);
  27453. }
  27454. }
  27455. cameraChanged() {
  27456. var copy = () => {
  27457. this.previousState = {
  27458. projectionMatrix: this.camera.projectionMatrix.clone(),
  27459. //worldMatrix在this.control时归零了所以不用了吧,用position和qua也一样
  27460. position: this.camera.position.clone(),
  27461. quaternion: this.camera.quaternion.clone(),
  27462. active: this.active,
  27463. resolution: this.resolution.clone(),
  27464. resolution2: this.resolution2.clone() //有时clientWidth没变但是ratio缩放了
  27465. };
  27466. };
  27467. var projectionChanged = true,
  27468. positionChanged = true,
  27469. quaternionChanged = true,
  27470. activeChanged = true,
  27471. resolutionChanged = true;
  27472. var getChanged = () => {
  27473. return {
  27474. projectionChanged,
  27475. positionChanged,
  27476. quaternionChanged,
  27477. activeChanged,
  27478. resolutionChanged,
  27479. changed: projectionChanged || positionChanged || quaternionChanged || activeChanged || resolutionChanged
  27480. };
  27481. };
  27482. if (this.previousState) {
  27483. projectionChanged = !this.camera.projectionMatrix.equals(this.previousState.projectionMatrix);
  27484. positionChanged = !this.camera.position.equals(this.previousState.position);
  27485. quaternionChanged = !this.camera.quaternion.equals(this.previousState.quaternion);
  27486. activeChanged = this.active != this.previousState.active;
  27487. resolutionChanged = !this.resolution.equals(this.previousState.resolution) || !this.resolution2.equals(this.previousState.resolution2);
  27488. }
  27489. copy();
  27490. return getChanged();
  27491. }
  27492. setResolution(w, h) {
  27493. var wholeW = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  27494. var wholeH = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  27495. this.resolution.set(w, h); //是client的width height
  27496. this.resolution2.copy(this.resolution).multiplyScalar(this.pixelRatio || window.devicePixelRatio);
  27497. this.offset.set(wholeW, wholeH).multiply(new Vector2(this.left, this.bottom)); //.multiplyScalar(window.devicePixelRatio)
  27498. this.dispatchEvent({
  27499. type: 'resize'
  27500. });
  27501. }
  27502. }
  27503. var prefixVertex = "precision highp float;\nprecision highp int;\n\nuniform mat4 modelMatrix;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform mat4 viewMatrix;\nuniform mat3 normalMatrix;\nuniform vec3 cameraPosition;\n attribute vec3 position;\n attribute vec3 normal;\n attribute vec2 uv;\n";
  27504. var prefixFragment = "precision highp float;\nprecision highp int;\n\nuniform mat4 viewMatrix;\nuniform vec3 cameraPosition;\n";
  27505. var shader = {
  27506. uniforms: {
  27507. opacity: {
  27508. type: "f"
  27509. // value: 1
  27510. },
  27511. progress: {
  27512. type: "f",
  27513. value: 0
  27514. },
  27515. pano0Map: {
  27516. type: "t",
  27517. value: null
  27518. },
  27519. pano1Map: {
  27520. type: "t",
  27521. value: null
  27522. },
  27523. depthMap0: {
  27524. type: "t",
  27525. value: null
  27526. },
  27527. depthMap1: {
  27528. type: "t",
  27529. value: null
  27530. },
  27531. pano0Position: {
  27532. type: "v3",
  27533. value: new Vector3()
  27534. },
  27535. pano0Matrix: {
  27536. type: "m4",
  27537. value: new Matrix4()
  27538. },
  27539. pano1Position: {
  27540. type: "v3",
  27541. value: new Vector3()
  27542. },
  27543. pano1Matrix: {
  27544. type: "m4",
  27545. value: new Matrix4()
  27546. },
  27547. /* pano1Matrix2: {
  27548. type: "m4",
  27549. value: new THREE.Matrix4
  27550. },
  27551. */
  27552. inverseProjectionMatrix: {
  27553. value: new Matrix4()
  27554. },
  27555. /* projectionMatrix:{//需要再写一遍吗
  27556. value: new THREE.Matrix4
  27557. }, */
  27558. viewport: {
  27559. value: new Vector4()
  27560. },
  27561. //如 {x: 0, y: 0, z: 428, w: 969} xy应该是offset, zw是宽高
  27562. cameraHeight0: {
  27563. type: "f",
  27564. value: 1
  27565. },
  27566. cameraHeight1: {
  27567. type: "f",
  27568. value: 1
  27569. },
  27570. ceilHeight0: {
  27571. type: "f",
  27572. value: 2
  27573. },
  27574. ceilHeight1: {
  27575. type: "f",
  27576. value: 2
  27577. }
  27578. },
  27579. vertexShader: prefixVertex + "\n\n uniform vec3 pano0Position;\n uniform mat4 pano0Matrix;\n \n uniform vec3 pano1Position;\n uniform mat4 pano1Matrix; \n\n \n varying vec2 vUv; \n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1;\n varying vec3 vWorldPosition12;\n \n vec3 transformAxis( vec3 direction ) //navvis->4dkk\n {\n float y = direction.y;\n direction.y = direction.z;\n direction.z = -y;\n return direction;\n }\n \n \n void main() {\n \n vUv = uv;\n vec4 worldPosition = modelMatrix * vec4(position, 1.0);\n \n \n \n vec3 positionLocalToPanoCenter0 = worldPosition.xyz - pano0Position;\n vWorldPosition0 = (vec4(positionLocalToPanoCenter0, 1.0) * pano0Matrix).xyz;\n vWorldPosition0.x *= -1.0;\n vWorldPosition0 = transformAxis(vWorldPosition0);\n \n vec3 positionLocalToPanoCenter1 = worldPosition.xyz - pano1Position;\n vWorldPosition1 = (vec4(positionLocalToPanoCenter1, 1.0) * pano1Matrix).xyz;\n vWorldPosition1.x *= -1.0;\n vWorldPosition1 = transformAxis(vWorldPosition1);\n \n /* \n vec3 positionLocalToPanoCenter12 = worldPosition.xyz - pano1Position;\n vWorldPosition12 = (vec4(positionLocalToPanoCenter12, 1.0) * pano1Matrix2).xyz;\n vWorldPosition12.x *= -1.0;\n vWorldPosition12 = transformAxis(vWorldPosition12);\n */\n \n \n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n \n }\n\n ",
  27580. fragmentShader: prefixFragment + "\n #extension GL_EXT_frag_depth : enable // otherwise error: 'GL_EXT_frag_depth' : extension is disabled\n \n #define PI 3.141592653 \n \n \n uniform float modelAlpha;\n uniform float opacity;\n uniform float progress;\n uniform int tranType;\n uniform vec3 pano0Position;\n uniform vec3 pano1Position;\n uniform float maxDistance;\n uniform float minDistance;\n uniform float minOpa;\n \n \n \n uniform samplerCube pano0Map;\n uniform samplerCube pano1Map;\n \n \n varying vec2 vUv; \n varying vec3 vWorldPosition0;\n varying vec3 vWorldPosition1; \n \n \n /* vec2 getSamplerCoord( vec3 direction ) \n {\n direction = normalize(direction);\n float tx=atan(direction.x,-direction.y)/(PI*2.0)+0.5;\n float ty=acos(direction.z)/PI;\n\n return vec2(tx,ty);\n } */\n\n vec2 getSamplerCoord2( vec3 direction ) \n { \n direction = normalize(direction);\n float tx=atan(direction.x,direction.z)/(PI*2.0)+0.5;\n float ty=acos(direction.y)/PI;\n\n return vec2(tx,ty); \n }\n \n \n #if defined(GL_EXT_frag_depth) && defined(hasDepthTex) \n uniform sampler2D depthMap0;\n uniform sampler2D depthMap1;\n uniform mat4 inverseProjectionMatrix;\n uniform mat4 projectionMatrix;\n uniform vec4 viewport; \n uniform float cameraHeight0;\n uniform float cameraHeight1;\n uniform float ceilHeight0;\n uniform float ceilHeight1;\n \n \n vec2 getDepth(vec3 dir, sampler2D depthMap, float heightDown, float heightUp, vec4 eyePos){\n vec2 depthValue = vec2(0.0, 0.0);\n vec2 uv2 = getSamplerCoord2( dir.xyz); //\u6682\u65F6\u53EA\u7528\u57FA\u4E8E\u76EE\u6807\u6F2B\u6E38\u70B9\u7684\u65B9\u5411\n uv2.x -= 0.25; //\u5168\u666F\u56FE\u548CCube\u7684\u6C34\u5E73\u91C7\u6837\u8D77\u59CB\u5750\u6807\u76F8\u5DEE90\u5EA6\uFF0C\u8FD9\u91CC\u77EB\u6B63 0.25 \u4E2A\u91C7\u6837\u504F\u79FB\n vec4 depth = texture2D(depthMap, uv2);\n //float distance = depth.r + 256. * (depth.g + 256. * depth.b);\n //distance *= 255. * .001; // distance is now in meters\n \n //\u66F4\u6539\n float distance = (depth.g + depth.r / 256.) * 255.; \n \n if(distance == 0.0){//\u6F2B\u6E38\u70B9\u5E95\u90E8\u8BC6\u522B\u4E0D\u5230\u7684\u533A\u57DF\uFF0C\u7ED9\u4E00\u4E2A\u5730\u677F\u9AD8\u5EA6 \n if(uv2.y < depthTexUVyLimit) distance = heightUp / dir.y; \n else if(uv2.y > 1.0 - depthTexUVyLimit) distance = heightDown / -dir.y; \n else distance = 100000.0;//\u7ED9\u4E2A\u8D85\u7EA7\u8FDC\u7684\u503C\n } \n \n if(distance == 0.0)distance = 100000.0;//\u7ED9\u4E2A\u8D85\u7EA7\u8FDC\u7684\u503C\n \n depthValue.x = distance;\n \n distance += .1; // add a safety margin\n\n vec4 eyePos2 = vec4(normalize(eyePos.xyz) * distance, 1.);\n vec4 clipPos2 = projectionMatrix * eyePos2;\n vec4 ndcPos2 = clipPos2 * 1. / clipPos2.w;\n\n \n depthValue.y = 0.5 * ((gl_DepthRange.far - gl_DepthRange.near) * ndcPos2.z\n + gl_DepthRange.near + gl_DepthRange.far); \n return depthValue; \n }\n //\u6CE8\uFF1A\u672A\u52A0\u8F7D\u597D\u7684\u8BDD\uFF0Cdepth\u4E3A0\uFF0C\u5BFC\u81F4\u7B2C\u4E00\u6B21\u6F2B\u6E38\u8FC7\u53BB\u7684\u65F6\u5019\u8BB8\u591Amesh\u4F1A\u7ACB\u523B\u88AB\u906E\u6321\uFF0C\u6240\u4EE5\u8981\u786E\u4FDD\u52A0\u8F7D\u5B8C\n #endif\n \n void main()\n {\n vec3 vWorldPosition0N = normalize(vWorldPosition0);\n vec3 vWorldPosition1N = normalize(vWorldPosition1);\n float progress_ = progress;\n \n vec4 colorFromPano0 = vec4(0.0,0.0,0.0,0.0);\n #if defined(usePanoMap0)\n //\u5373progress < 1.0 \u901A\u5E38\u662F1\n colorFromPano0=textureCube(pano0Map,vWorldPosition0N.xyz);\n #else \n progress_ = 1.0;\n #endif\n vec4 colorFromPano1=textureCube(pano1Map,vWorldPosition1N.xyz);\n \n gl_FragColor = mix(colorFromPano0,colorFromPano1,progress_);\n \n \n \n \n //\u6DF1\u5EA6\u56FE\u4FEE\u6539\u6DF1\u5EA6\n \n #if defined(GL_EXT_frag_depth) && defined(hasDepthTex) \n vec4 ndcPos;\n ndcPos.xy = ((2.0 * gl_FragCoord.xy) - (2.0 * viewport.xy)) / (viewport.zw) - 1.;\n ndcPos.z = (2.0 * gl_FragCoord.z - gl_DepthRange.near - gl_DepthRange.far) /\n (gl_DepthRange.far - gl_DepthRange.near);\n ndcPos.w = 1.0;\n\n vec4 clipPos = ndcPos / gl_FragCoord.w;\n vec4 eyePos = inverseProjectionMatrix * clipPos;\n vec2 depth0 = vec2(0.0,0.0); \n #if defined(usePanoMap0)\n depth0 = getDepth(vWorldPosition0N, depthMap0, cameraHeight0, ceilHeight0, eyePos);\n #endif\n vec2 depth1 = getDepth(vWorldPosition1N, depthMap1, cameraHeight1, ceilHeight1, eyePos);\n \n \n gl_FragDepthEXT = mix(depth0.y,depth1.y,progress_); \n gl_FragDepthEXT = clamp(gl_FragDepthEXT, 0.0, 1.0); //\u9632\u6B62\u90E8\u5206\u624B\u673A\u51FA\u73B0\u9ED1\u5757\u3002ios 16 \u3002 \u56E0\u4E3A\u6211\u7ED9\u7684\u8D85\u8FDC\u503C\u8D85\u51FA\u8303\u56F4\n \n\n #endif\n\n \n }\n "
  27581. };
  27582. //注:gl_FragDepthEXT 修改了确实能像真实mesh那样遮挡住在后面的物体。但是为过渡时不能直接像有模型那样,和角度有关。
  27583. class ModelTextureMaterial extends RawShaderMaterial {
  27584. constructor() {
  27585. var defines = {
  27586. depthTexUVyLimit: Potree.config.depthTexUVyLimit
  27587. };
  27588. var {
  27589. vs,
  27590. fs
  27591. } = Common.changeShaderToWebgl2(shader.vertexShader, shader.fragmentShader, 'RawShaderMaterial');
  27592. super({
  27593. fragmentShader: fs,
  27594. vertexShader: vs,
  27595. uniforms: UniformsUtils.clone(shader.uniforms),
  27596. side: DoubleSide,
  27597. name: "ModelTextureMaterial",
  27598. defines
  27599. });
  27600. this.glslVersion = Potree.settings.isWebgl2 && '300 es';
  27601. var setSize = e => {
  27602. var viewport = e.viewport;
  27603. //let viewportOffset = viewport.offset || new Vector2()
  27604. var resolution = viewport.resolution2;
  27605. //this.uniforms.viewport.value.set(viewportOffset.x, viewportOffset.y, resolution.x, resolution.y)
  27606. this.uniforms.viewport.value.set(0, 0, resolution.x, resolution.y); // xy是在viewport中的left和bottom,和整个窗口没有关系,所以不是viewportOffset。几乎都是0,0
  27607. };
  27608. var viewport = viewer.mainViewport;
  27609. setSize({
  27610. viewport
  27611. });
  27612. viewer.addEventListener('resize', e => {
  27613. if (e.viewport.name != "MainView") return;
  27614. setSize(e);
  27615. });
  27616. //var supportExtDepth = !!Features.EXT_DEPTH.isSupported()
  27617. {
  27618. //add
  27619. viewer.addEventListener('camera_changed', e => {
  27620. if (e.viewport.name != "MainView") return;
  27621. //this.uniforms.projectionMatrix.value.copy(e.camera.projectionMatrix)
  27622. e.camera && this.uniforms.inverseProjectionMatrix.value.copy(e.camera.projectionMatrixInverse);
  27623. });
  27624. }
  27625. var progress = 0;
  27626. Object.defineProperty(this.uniforms.progress, 'value', {
  27627. get: function get() {
  27628. return progress;
  27629. },
  27630. set: e => {
  27631. if (e < 1 && !Potree.settings.fastTran) {
  27632. if (!('usePanoMap0' in this.defines)) {
  27633. this.defines.usePanoMap0 = '';
  27634. this.needsUpdate = true;
  27635. }
  27636. } else {
  27637. if ('usePanoMap0' in this.defines) {
  27638. delete this.defines.usePanoMap0;
  27639. this.needsUpdate = true;
  27640. }
  27641. }
  27642. progress = e;
  27643. }
  27644. });
  27645. //-------------------------------------
  27646. }
  27647. /**
  27648. *
  27649. * @param {Panorama} pano0
  27650. * @param {Panorama} pano1
  27651. * @param {boolean} flag
  27652. 更新全景图的材质uniforms
  27653. */
  27654. setProjectedPanos(pano0, pano1, progressValue) {
  27655. progressValue != void 0 && (this.uniforms.progress.value = progressValue);
  27656. //pano0.ensureSkyboxReadyForRender();
  27657. if (pano0) {
  27658. this.uniforms.pano0Map.value = pano0.getSkyboxTexture(); //pano0.texture
  27659. this.uniforms.pano0Position.value.copy(pano0.position);
  27660. this.uniforms.pano0Matrix.value.copy(pano0.panoMatrix /* pano0.mesh.matrixWorld */);
  27661. //pano1.ensureSkyboxReadyForRender();
  27662. }
  27663. this.uniforms.pano1Map.value = pano1.getSkyboxTexture(); //pano1.texture;
  27664. this.uniforms.pano1Position.value.copy(pano1.position);
  27665. this.uniforms.pano1Matrix.value.copy(pano1.panoMatrix /* pano1.mesh.matrixWorld */);
  27666. this.pano0 = pano0;
  27667. this.pano1 = pano1;
  27668. this.updateDepthTex(pano0);
  27669. this.updateDepthTex(pano1);
  27670. //console.log('setProjectedPanos', pano0&&pano0.id, pano1&&pano1.id)
  27671. this.needsUpdate = true;
  27672. }
  27673. updateDepthTex(pano, extra) {
  27674. if (!Potree.settings.useDepthTex || !pano || !pano.depthTex || pano != this.pano0 && pano != this.pano1) return;
  27675. //console.log('updateDepthTex', pano.id, this.pano0 && this.pano0.id, this.pano1 && this.pano1.id)
  27676. if (this.pano0) {
  27677. this.uniforms.depthMap0.value = this.pano0.entered ? this.pano0.depthTex : null; //dispose了就不要赋值否则dispose会失败
  27678. this.uniforms.cameraHeight0.value = this.pano0.floorPosition.distanceTo(this.pano0.position);
  27679. this.uniforms.ceilHeight0.value = this.pano0.getCeilHeight() - this.pano0.position.z;
  27680. }
  27681. if (this.pano1) {
  27682. this.uniforms.depthMap1.value = this.pano1.depthTex; //pano1还没entered时也需要,可能在飞入
  27683. this.uniforms.cameraHeight1.value = this.pano1.floorPosition.distanceTo(this.pano1.position);
  27684. this.uniforms.ceilHeight1.value = this.pano1.getCeilHeight() - this.pano1.position.z;
  27685. }
  27686. this.updateDepthTexEnable();
  27687. }
  27688. updateDepthTexEnable() {
  27689. var hasDepthTex = this.pano0 && this.pano1 && this.pano0.pointcloud.hasDepthTex && this.pano1.pointcloud.hasDepthTex; //暂时不知道一个有图一个没图怎么写所以
  27690. Potree.Utils.addOrRemoveDefine(this, 'hasDepthTex', hasDepthTex ? 'add' : 'remove');
  27691. }
  27692. /* EnableDepthTex(){//开启DepthTex
  27693. if(this.defines['hasDepthTex']){
  27694. return
  27695. }
  27696. this.defines['hasDepthTex'] = ''
  27697. this.needsUpdate = true;
  27698. } */
  27699. }
  27700. class FastTranPass {
  27701. constructor(renderer) {
  27702. this.renderer = renderer;
  27703. this.coverRenderTarget = new WebGLRenderTarget(100, 100, {
  27704. minFilter: LinearFilter,
  27705. magFilter: LinearFilter,
  27706. format: RGBAFormat
  27707. });
  27708. this.coverTex = this.coverRenderTarget.texture;
  27709. this.enabled = false;
  27710. /* this.oldClearColor = new THREE.Color();
  27711. this.oldClearAlpha = 1;
  27712. this.camera = new THREE.OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  27713. this.scene = new THREE.Scene(); */
  27714. this.material = this.getMaskMaterial();
  27715. /* var copyShader = THREE.CopyShader;
  27716. this.materialCopy = new THREE.ShaderMaterial( {
  27717. uniforms: this.copyUniforms,
  27718. vertexShader: copyShader.vertexShader,
  27719. fragmentShader: copyShader.fragmentShader,
  27720. blending: THREE.NoBlending,
  27721. depthTest: false,
  27722. depthWrite: false,
  27723. transparent: true
  27724. } );
  27725. this.quad = new THREE.Mesh( new THREE.PlaneBufferGeometry( 2, 2 ), this.material);
  27726. this.quad.frustumCulled = false; // Avoid getting clipped
  27727. this.scene.add( this.quad );
  27728. this.renderToScreen = true*/
  27729. }
  27730. setSize(width, height) {
  27731. this.coverRenderTarget.setSize(width, height);
  27732. }
  27733. start() {
  27734. this.enabled = true;
  27735. var {
  27736. x,
  27737. y
  27738. } = viewer.mainViewport.resolution2;
  27739. this.setSize(x, y);
  27740. //draw coverTex
  27741. var oldTarget = this.renderer.getRenderTarget();
  27742. //let oldClearColor = this.renderer.getClearColor()
  27743. this.renderer.setRenderTarget(this.coverRenderTarget);
  27744. //this.renderer.setClearColor( 0x000000, 0)
  27745. var oldLayer = viewer.mainViewport.camera.layers.mask;
  27746. Potree.Utils.setCameraLayers(viewer.mainViewport.camera, ['skybox']);
  27747. this.renderer.render(viewer.scene.scene, viewer.mainViewport.camera);
  27748. //this.renderer.setClearColor( 0x000000, 0)
  27749. this.renderer.setRenderTarget(oldTarget);
  27750. viewer.mainViewport.camera.layers.mask = oldLayer;
  27751. this.material.uniforms.progress.value = 1;
  27752. console.log('start111');
  27753. }
  27754. render(scene, camera, viewports, renderer, writeBuffer, readBuffer) {
  27755. /* var oldAutoClear = renderer.autoClear;
  27756. renderer.autoClear = false;
  27757. */
  27758. var {
  27759. x,
  27760. y
  27761. } = viewer.mainViewport.resolution2;
  27762. var uniforms = this.material.uniforms;
  27763. //uniforms.bgTex.value = readBuffer.texture; //更新
  27764. uniforms.coverTex.value = this.coverTex;
  27765. uniforms.progress.value = viewer.images360.cube.material.uniforms.progress.value;
  27766. uniforms.screenRatio.value = x / y; // 使波纹为圆形
  27767. uniforms.screenRatio.value *= uniforms.screenRatio.value;
  27768. Potree.Utils.screenPass.render(viewer.renderer, viewer.images360.fastTranMaskPass.material);
  27769. //renderer.autoClear = oldAutoClear;
  27770. }
  27771. stop() {
  27772. this.enabled = false;
  27773. console.log('stop111');
  27774. }
  27775. getMaskMaterial() {
  27776. return new ShaderMaterial({
  27777. uniforms: {
  27778. coverTex: {
  27779. type: "t",
  27780. value: null
  27781. },
  27782. progress: {
  27783. type: "f",
  27784. value: 0
  27785. },
  27786. screenRatio: {
  27787. type: "f",
  27788. value: 1
  27789. }
  27790. },
  27791. vertexShader: " \n varying vec2 vUv;\n \n void main() \n {\n vUv = uv;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n } \n \n ",
  27792. fragmentShader: " \n uniform sampler2D coverTex; \n uniform float progress; \n uniform float screenRatio;\n varying vec2 vUv;\n \n void main() {\n \n const float maxRadius = 0.708; // sqrt(0.5^2+0.5^2)\n const float minRadius = 0.0 ;\n \n float radius = screenRatio>1.0 ? sqrt((vUv.x - 0.5)*(vUv.x - 0.5) + (vUv.y - 0.5)*(vUv.y - 0.5)/screenRatio) : sqrt((vUv.x - 0.5)*(vUv.x - 0.5)*screenRatio+ (vUv.y - 0.5)*(vUv.y - 0.5));\n float diff = 0.292; //1.0-maxRadius;\n float radiusIn = maxRadius * progress + minRadius * (1.0-progress);\n float radiusOut = radiusIn + diff;\n if(radius < radiusIn) {\n \n discard;\n \n }else if(radius>radiusOut){\n gl_FragColor = texture2D(coverTex, vUv) ;\n //gl_FragColor = vec4(1.0,1.0,0.0,1.0);//\n \n }else{\n \n /* vec4 color1 = texture2D(bgTex, vUv);\n vec4 color2 = texture2D(coverTex, vUv);\n float rotio = smoothstep(radiusIn ,radiusOut,radius);\n \n gl_FragColor = mix(color1, color2, rotio); */\n \n float rotio = smoothstep(radiusIn ,radiusOut, radius);\n \n vec4 color2 = texture2D(coverTex, vUv);\n color2.a = rotio;\n \n \n }\n }\n "
  27793. });
  27794. }
  27795. /* getMaskMaterial(){
  27796. return new THREE.ShaderMaterial( {
  27797. uniforms: {
  27798. coverTex: {
  27799. type: "t",
  27800. value: null
  27801. },
  27802. bgTex: {
  27803. type: "t",
  27804. value: null
  27805. },
  27806. progress:{
  27807. type: "f",
  27808. value: 0
  27809. },
  27810. screenRatio:{
  27811. type: "f",
  27812. value: 1
  27813. }
  27814. },
  27815. vertexShader: `
  27816. varying vec2 vUv;
  27817. void main()
  27818. {
  27819. vUv = uv;
  27820. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  27821. }
  27822. `,
  27823. fragmentShader: `
  27824. uniform sampler2D coverTex;
  27825. uniform sampler2D bgTex;
  27826. uniform float progress;
  27827. uniform float screenRatio;
  27828. varying vec2 vUv;
  27829. void main() {
  27830. const float maxRadius = 0.708; // sqrt(0.5^2+0.5^2)
  27831. const float minRadius = 0.0 ;
  27832. float radius = screenRatio>1.0 ? sqrt((vUv.x - 0.5)*(vUv.x - 0.5) + (vUv.y - 0.5)*(vUv.y - 0.5)/screenRatio) : sqrt((vUv.x - 0.5)*(vUv.x - 0.5)*screenRatio+ (vUv.y - 0.5)*(vUv.y - 0.5));
  27833. float diff = 0.292; //1.0-maxRadius;
  27834. float radiusIn = maxRadius * progress + minRadius * (1.0-progress);
  27835. float radiusOut = radiusIn + diff;
  27836. if(radius < radiusIn) {
  27837. gl_FragColor = texture2D(bgTex, vUv);
  27838. //gl_FragColor = vec4(0.0,0.0,1.0,1.0);//
  27839. }else if(radius>radiusOut){
  27840. gl_FragColor = texture2D(coverTex, vUv) ;
  27841. //gl_FragColor = vec4(1.0,1.0,0.0,1.0);//
  27842. }else{
  27843. vec4 color1 = texture2D(bgTex, vUv);
  27844. vec4 color2 = texture2D(coverTex, vUv);
  27845. float rotio = smoothstep(radiusIn ,radiusOut,radius);
  27846. gl_FragColor = mix(color1, color2, rotio);
  27847. }
  27848. }
  27849. `
  27850. } );
  27851. } */
  27852. }
  27853. var GLCubeFaces$1 = Potree.defines.GLCubeFaces;
  27854. var TileUtils = {};
  27855. TileUtils.TILE_SIZE = 512, TileUtils.FACES_PER_PANO = 6, TileUtils.LocationOnTile = {
  27856. Center: 0,
  27857. UpperLeft: 1,
  27858. UpperRight: 2,
  27859. LowerRight: 3,
  27860. LowerLeft: 4
  27861. },
  27862. /*
  27863. * 获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的指定位置)。spherical通过先求uv,再直接得到dir
  27864. * @param {*} size 面分辨率
  27865. * @param {*} cubeFace 所在面
  27866. * @param {*} Center 在tile上的目标位置,默认为中心,其他位置就是四个顶点
  27867. * @param {*} c 似乎是在tile的缩进百分比,根据所在面的不同,分别向不同方向缩进,但都是向tile的中心
  27868. * @param {*} dir 所求方向
  27869. */
  27870. TileUtils.getTileVector = function () {
  27871. //获取某tile在cube中的方向 direction (向量起点在cube中心,终点在tile图的中心)
  27872. return function (size, tileSize, cubeFace, tileX, tileY, Center, c, dir) {
  27873. //c似乎是缩进百分比
  27874. Center = Center || TileUtils.LocationOnTile.Center;
  27875. //假设该cube边长为2:
  27876. var u = size / tileSize,
  27877. d = tileX / u;
  27878. tileY = -tileY + (u - 1);
  27879. var p = tileY / u,
  27880. f = tileSize / size,
  27881. g = 2 * f //一个tile的宽度 (乘以2是因为cube边长是2)
  27882. ,
  27883. m = g / 2,
  27884. v = 2 * d - 1 + m,
  27885. A = 2 * p - 1 + m;
  27886. switch (Center) {
  27887. //计算在tile中指定位置带来的偏移
  27888. case TileUtils.LocationOnTile.UpperLeft:
  27889. //1
  27890. v -= m, A += m, v += c * g; //似乎是向内缩进
  27891. break;
  27892. case TileUtils.LocationOnTile.UpperRight:
  27893. v += m, A += m, A -= c * g;
  27894. break;
  27895. case TileUtils.LocationOnTile.LowerRight:
  27896. v += m, A -= m, v -= c * g;
  27897. break;
  27898. case TileUtils.LocationOnTile.LowerLeft:
  27899. v -= m, A -= m, A += c * g;
  27900. break;
  27901. case TileUtils.LocationOnTile.Center: //0
  27902. }
  27903. switch (cubeFace) {
  27904. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  27905. MathLight.setVector(dir, -1, A, -v);
  27906. break;
  27907. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  27908. MathLight.setVector(dir, 1, A, v);
  27909. break;
  27910. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  27911. //顶面
  27912. MathLight.setVector(dir, -v, 1, -A);
  27913. break;
  27914. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  27915. MathLight.setVector(dir, -v, -1, A);
  27916. break;
  27917. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  27918. MathLight.setVector(dir, -v, A, 1);
  27919. break;
  27920. case GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  27921. MathLight.setVector(dir, v, A, -1);
  27922. }
  27923. MathLight.normalize(dir);
  27924. };
  27925. }(),
  27926. /*
  27927. * 获取该tile在第几个面(简易装载法)
  27928. */
  27929. TileUtils.getFaceForTile = function (size, index) {
  27930. //获取该tile在第几个面
  27931. var tileSize = TileUtils.TILE_SIZE;
  27932. size < TileUtils.TILE_SIZE && (tileSize = size);
  27933. var n = Math.floor(size / tileSize),
  27934. sum = n * n; //得每个面tile总数
  27935. return Math.floor(index / sum);
  27936. }, TileUtils.getTileLocation = function (size, t, result) {
  27937. var tileSize = TileUtils.TILE_SIZE;
  27938. size < TileUtils.TILE_SIZE && (tileSize = size);
  27939. var r = TileUtils.getFaceForTile(size, t),
  27940. a = Math.floor(size / tileSize),
  27941. s = a * a,
  27942. l = t - r * s;
  27943. result.tileX = l % a;
  27944. result.tileY = Math.floor(l / a);
  27945. result.face = r;
  27946. result.faceTileIndex = l;
  27947. return result;
  27948. },
  27949. /*
  27950. * 求size分辨率需要多少张tile
  27951. */
  27952. TileUtils.getTileCountForSize = function (e) {
  27953. if (e <= TileUtils.TILE_SIZE) return TileUtils.FACES_PER_PANO;
  27954. var t = Math.floor(e / TileUtils.TILE_SIZE),
  27955. i = t * t,
  27956. n = i * TileUtils.FACES_PER_PANO;
  27957. return n;
  27958. }, TileUtils.getRelativeDirection = function () {
  27959. var e = new MathLight.Matrix4(),
  27960. t = new MathLight.Quaternion();
  27961. return function (i, n) {
  27962. //i是pano.quaternion, n是camera的direction
  27963. t.copy(i), t.inverse(), e.makeRotationFromQuaternion(t), e.applyToVector3(n), MathLight.normalize(n);
  27964. };
  27965. }(),
  27966. /*
  27967. * 根据方向寻找合适的tile加载
  27968. */
  27969. TileUtils.matchingTilesInDirection = function () {
  27970. var e = new MathLight.Vector3(),
  27971. t = new MathLight.Vector3(0, 0, -1),
  27972. i = new MathLight.Quaternion(),
  27973. n = function n(e, t) {
  27974. e.push({
  27975. face: t.face,
  27976. faceTileIndex: t.faceTileIndex,
  27977. tileX: t.tileX,
  27978. tileY: t.tileY
  27979. });
  27980. },
  27981. a = function () {
  27982. var e = {
  27983. face: -1,
  27984. faceTileIndex: -1,
  27985. tileX: -1,
  27986. tileY: -1
  27987. };
  27988. return function (size, i, r) {
  27989. for (var a = TileUtils.getTileCountForSize(size), s = 0, l = 0; l < a; l++) TileUtils.getTileLocation(size, l, e), i && !i(e) || (s++, r && n(r, e));
  27990. return s;
  27991. };
  27992. }();
  27993. return function (pano, size, dir, hFov, vFov, result) {
  27994. var d = size < TileUtils.TILE_SIZE ? size : TileUtils.TILE_SIZE;
  27995. //TileUtils.getTileCountForSize(size);
  27996. if (!hFov && !vFov) return a(size, null, result);
  27997. var p = !!vFov;
  27998. vFov = vFov || hFov, vFov = Math.max(0, Math.min(vFov, 360)), hFov = Math.max(0, Math.min(hFov, 360)), MathLight.copyVector(dir, e), TileUtils.getRelativeDirection(pano.quaternion4dkk, e);
  27999. if (p) {
  28000. //如果有vFov hFov
  28001. i.setFromUnitVectors(e, t);
  28002. var f = function f(e) {
  28003. return TileUtils.isTileWithinFrustum(size, d, e.face, e.tileX, e.tileY, i, hFov, vFov); //在视野中的
  28004. };
  28005. return a(size, f, result);
  28006. }
  28007. var g = function g(t) {
  28008. //如果仅有hFov
  28009. return TileUtils.isTileWithinFOV(size, d, t.face, t.tileX, t.tileY, e, hFov);
  28010. };
  28011. return a(size, g, result);
  28012. };
  28013. }(),
  28014. /*
  28015. * 是否在屏幕范围内
  28016. */
  28017. TileUtils.isTileWithinFrustum = function () {
  28018. var e = new MathLight.Vector3(),
  28019. t = 1e-5;
  28020. return function (i, n, a, s, l, c, h, u) {
  28021. for (var d = Math.tan(.5 * u * MathLight.RADIANS_PER_DEGREE), p = -d, f = Math.tan(.5 * h * MathLight.RADIANS_PER_DEGREE), g = -f, m = TileUtils.mapFaceToCubemapFace(a), v = 0, A = 0, y = 0, C = 0, I = 0, E = 0, b = TileUtils.LocationOnTile.Center; b <= TileUtils.LocationOnTile.LowerLeft; b++) {
  28022. TileUtils.getTileVector(i, n, m, s, l, b, 0, e),
  28023. //get e // size, tileSize, cubeFace, tileX, tileY, Center, c, dir
  28024. MathLight.applyQuaternionToVector(c, e);
  28025. if (e.z >= -t)
  28026. //似乎是在相机背面
  28027. I++;else {
  28028. var w = -1 / e.z,
  28029. _ = e.x * w,
  28030. T = e.y * w;
  28031. T > d ? v++ : T < p && A++,
  28032. //这四种似乎代表在这个画框之外,如在左、在上、在下、在右
  28033. _ > f ? y++ : _ < g && C++, E++;
  28034. }
  28035. }
  28036. return A !== E && v !== E && y !== E && C !== E; //如果有一项和E相等代表要么是在相机背面要么是tile的四个顶点都画在画布的同一边,所以肯定不在画布上
  28037. };
  28038. }(),
  28039. /*
  28040. * 是否在FOV范围内
  28041. */
  28042. TileUtils.isTileWithinFOV = function () {
  28043. var e = new MathLight.Vector3(),
  28044. t = new MathLight.Vector3(0, 1, 0),
  28045. i = new MathLight.Vector3(1, 0, 0);
  28046. return function (panoSize, tileSize, face, tileX, tileY, direction, fov) {
  28047. //direction是作用了pano.quaternion的camera.direction
  28048. var d = TileUtils.mapFaceToCubemapFace(face);
  28049. MathLight.cross(direction, t, i); //get i 好像没用到
  28050. TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, TileUtils.LocationOnTile.Center, 0, e);
  28051. if (TileUtils.isWithinFOV(e, direction, fov, null))
  28052. //先判断tile中心在不在FOV内
  28053. return !0;
  28054. for (var p = fov / 360, f = Math.floor(1 / p), g = 0, m = 0; m < f; m++) {
  28055. for (var v = TileUtils.LocationOnTile.UpperLeft; v <= TileUtils.LocationOnTile.LowerLeft; v++) if (TileUtils.getTileVector(panoSize, tileSize, d, tileX, tileY, v, g, e), TileUtils.isWithinFOV(e, direction, fov, null)) return !0;
  28056. g += p; //可能是考虑到有可能tile比fov覆盖了fov(虽然一般不可能,除非fov特别小),所以将tile分成若干段,取tile中的点再检测下
  28057. }
  28058. return !1;
  28059. };
  28060. }(), TileUtils.isWithinFOV = function () {
  28061. var e = new MathLight.Vector3(),
  28062. t = new MathLight.Vector3();
  28063. return function (dir, cameraDir, fov, a) {
  28064. if (MathLight.copyVector(dir, t), a) {
  28065. MathLight.copyVector(a, e), MathLight.normalize(e);
  28066. var s = MathLight.dot(e, dir);
  28067. e.x *= s, e.y *= s, e.z *= s, MathLight.subVector(t, e);
  28068. }
  28069. var l = fov / 2 * MathLight.RADIANS_PER_DEGREE,
  28070. c = Math.cos(l),
  28071. h = MathLight.dot(t, cameraDir);
  28072. return h >= c;
  28073. };
  28074. }(), TileUtils.mapFaceToCubemapFace = function () {
  28075. var e = {
  28076. 0: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  28077. 1: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  28078. 2: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  28079. 3: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
  28080. 4: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  28081. 5: GLCubeFaces$1.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
  28082. };
  28083. return function (t) {
  28084. return e[t];
  28085. };
  28086. }();
  28087. var {
  28088. PanoRendererEvents,
  28089. PanoramaEvents,
  28090. PanoSizeClass
  28091. } = Potree.defines;
  28092. var texLoader$3 = new TextureLoader();
  28093. var markerOpacitys = {
  28094. default: 0.4,
  28095. hovered: 1
  28096. };
  28097. var labelProp = {
  28098. sizeInfo: {
  28099. minSize: 200,
  28100. maxSize: 250,
  28101. nearBound: 0.8,
  28102. farBound: 10
  28103. },
  28104. backgroundColor: {
  28105. r: 255,
  28106. g: 255,
  28107. b: 255,
  28108. a: 0.4
  28109. },
  28110. textColor: {
  28111. r: 0,
  28112. g: 0,
  28113. b: 0,
  28114. a: 1
  28115. },
  28116. borderRadius: 15,
  28117. renderOrder: 10,
  28118. useDepth: true,
  28119. clipDistance: 30,
  28120. maxClipFactor: 0.3,
  28121. occlusionDistance: 3
  28122. };
  28123. var labelProp2 = {
  28124. //sizeInfo: {minSize : 200 , maxSize : 250, nearBound : 0.8, farBound : 10},
  28125. backgroundColor: {
  28126. r: 255,
  28127. g: 255,
  28128. b: 255,
  28129. a: 0
  28130. },
  28131. textColor: {
  28132. r: 255,
  28133. g: 255,
  28134. b: 255,
  28135. a: 1
  28136. },
  28137. textBorderColor: {
  28138. r: 30,
  28139. g: 30,
  28140. b: 30,
  28141. a: 1
  28142. },
  28143. textBorderThick: 3,
  28144. dontFixOrient: true,
  28145. renderOrder: 10,
  28146. fontsize: 30
  28147. };
  28148. var markerTex;
  28149. //显示全景图时marker没有被遮挡,如果需要,要换成depthBasicMaterial 或者直接把skybox的深度修改(拿到深度贴图后更如此)
  28150. var planeGeo = new PlaneBufferGeometry(0.2, 0.2);
  28151. var sg = new SphereGeometry(0.1, 8, 8);
  28152. var smHovered = new MeshBasicMaterial({
  28153. /* side: THREE.BackSide, */color: 0xff0000
  28154. });
  28155. var sm = new MeshBasicMaterial({/* side: THREE.BackSide */});
  28156. var rot90 = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2); //使用的是刚好适合全景图的,给cube贴图需要转90°
  28157. //var rot90 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1,0,0), -Math.PI/2 ); //4dkk->navvis
  28158. //var rot901 = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/2 ); //整张球幕图要旋转下
  28159. //rot90 = new THREE.Quaternion().multiplyQuaternions( rot901, rot90)
  28160. var old = null;
  28161. /*
  28162. 转成四维看看的axis:
  28163. var a = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,0,1), THREE.Math.degToRad(-90)) 因为四维的要绕y转90
  28164. 这里的quaternion.multiply(a);
  28165. 先乘再换顺序 w : q.w, x:q.x , y:-q.z, z:q.y
  28166. */
  28167. //暂时直接用4dkkconsole输出的数据
  28168. class Panorama extends EventDispatcher {
  28169. constructor(o, images360) {
  28170. //file, time, longitude, latitude, altitude, course, pitch, roll
  28171. super();
  28172. this.id = o.id; //唯一标识
  28173. this.images360 = images360;
  28174. this.visible = true; //for updateVisible
  28175. this.enabled = true; //是否可以走
  28176. this.addEventListener('isVisible', e => {
  28177. //是否显示该点的mesh(不显示也能走)
  28178. //console.log('pano isVisible', this.id, e.visible)
  28179. Potree.Utils.updateVisible(this.marker, 'panoVisi', e.visible);
  28180. Potree.settings.showPanoMesh && (this.mesh.visible = e.visible);
  28181. if (e.reason == 'screenshot' || e.visible) {
  28182. this.label && (this.label.visible = e.visible); //截图时隐藏下
  28183. }
  28184. this.label2 && Potree.Utils.updateVisible(this.label2, 'panoVisi', e.visible);
  28185. });
  28186. /*
  28187. 漫游点可见性:旧
  28188. level reason 类型
  28189. 2(最高)buildingChange(不在此楼层) unvisible
  28190. 1 modeIsShowPanos(漫游模式) visible //不记得为什么加这个了,所以重写
  28191. 0 pointcloudVisi(隐藏了数据集) unvisible
  28192. */
  28193. /*
  28194. 漫游点可见性:新
  28195. level reason 类型
  28196. 2(最高)buildingChange(不在此楼层) unvisible
  28197. 1 ifShowMarker(marker显示开关) unvisible
  28198. 0 pointcloudVisi(隐藏了数据集) unvisible
  28199. */
  28200. if (Potree.settings.editType == 'pano') {
  28201. //漫游点拼合编辑
  28202. this.uuid = o.uuid; //因为有多个数据集 所以会重复
  28203. this.index = this.originID = o.index; //下标, 用于visibles
  28204. this.pointcloud = viewer.scene.pointclouds.find(e => e.panoUuid == o.uuid);
  28205. this.pointcloud.panos.push(this);
  28206. this.sid = this.pointcloud.dataset_id + '|' + this.uuid; //不会更改的标记 用于entity.panos里的标记
  28207. this.panosData = o;
  28208. //数据中原本的位置朝向
  28209. this.dataPosition = new Vector3().copy(o.pose.translation);
  28210. this.dataQuaternion = new Quaternion().copy(o.pose.rotation);
  28211. this.dataRotation = new Euler().setFromQuaternion(this.dataQuaternion);
  28212. //因为位置朝向随着点云位置改变,所以直接运用到点云上,这里清零
  28213. this.originPosition = new Vector3(); //{x: 0, y: 0, z: 0}
  28214. this.quaternion = new Quaternion(); //{w: 0, x: 0, y: 0, z: 1}
  28215. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  28216. this.visibles = o.visibles;
  28217. this.rtkState = o.has_rtk ? o.use_rtk : null;
  28218. var height = 1.4; //相机高度
  28219. this.originFloorPosition = this.originPosition.clone();
  28220. this.originFloorPosition.z -= height;
  28221. /* this.originPosition = new THREE.Vector3().copy(o.pose.translation) //{x: 0, y: 0, z: 0}
  28222. this.quaternion = new THREE.Quaternion().copy(o.pose.rotation) //{w: 0, x: 0, y: 0, z: 1}
  28223. //this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion)//4dkk内使用的quaternion
  28224. this.visibles = o.visibles
  28225. this.pointcloud = viewer.scene.pointclouds.find(e=>e.dataset_id == o.uuid)
  28226. this.pointcloud.panos.push(this)
  28227. const height = 1.5; //相机高度
  28228. this.originFloorPosition = this.originPosition.clone()
  28229. this.originFloorPosition.z -= height
  28230. */
  28231. } else {
  28232. this.originPosition = new Vector3().fromArray(o.dataset_location); //完全对应vision.txt的translation
  28233. this.originFloorPosition = new Vector3().fromArray(o.dataset_floor_location);
  28234. this.originID = parseInt(o.file_id); //"file_id":"00022"对应是原本的4dkk的id --来自vision.txt
  28235. this.pointcloud = viewer.scene.pointclouds.find(e => e.dataset_id == o.dataset_id) || viewer.scene.pointclouds[0];
  28236. this.pointcloud.panos.push(this);
  28237. //this.sid = this.pointcloud.sceneCode + '|' + this.originID //不会更改的标记
  28238. this.sid = this.pointcloud.dataset_id + '|' + this.originID; //不会更改的标记
  28239. //全景图和Cube的水平采样起始坐标相差90度
  28240. /* if(from4dkk){
  28241. var qua = o.dataset_orientation
  28242. var quaternion = new THREE.Quaternion().fromArray(qua)
  28243. quaternion = new THREE.Quaternion().multiplyQuaternions(quaternion, rot901);//整张球幕图要旋转下 因为在4dkk里转过,还原。如果是tiles的不用
  28244. this.quaternion = new THREE.Quaternion(quaternion.x, -quaternion.z, quaternion.y, quaternion.w) //转化坐标
  28245. }else{ */
  28246. var qua = o.dataset_orientation; //完全对应vision.txt的rotation
  28247. qua = [qua[1], qua[2], qua[3], qua[0]];
  28248. this.quaternion = new Quaternion().fromArray(qua);
  28249. this.quaternion4dkk = math.convertVisionQuaternion(this.quaternion); //4dkk内使用的quaternion
  28250. this.quaternion2 = this.quaternion.clone();
  28251. this.quaternion = new Quaternion().multiplyQuaternions(this.quaternion, rot90); //全景图和Cube的水平采样起始坐标相差90度,cubeTex转90度
  28252. this.rotation4dkk = new Euler().setFromQuaternion(this.quaternion4dkk);
  28253. //}
  28254. //this.quaternion1 = Potree.Utils.QuaternionFactory.fromArray(o.dataset_orientation)
  28255. //同quaternion
  28256. //let xy = this.transform.forward([this.longitude, this.latitude]);
  28257. //this.file = `https://4dkk.4dage.com/images/images${Potree.settings.number}/pan/high/${this.id}.jpg`
  28258. this.neighbours = [];
  28259. }
  28260. this.rotation = new Euler().setFromQuaternion(this.quaternion);
  28261. this.build();
  28262. this.transformByPointcloud(); //初始化位移
  28263. {
  28264. //tile
  28265. this.minimumTiledPanoLoaded = !1;
  28266. this.highestPartialTileRenderOpCompleted = 0;
  28267. this.highestFullTileRenderOpCompleted = 0;
  28268. this.shouldRedrawOnBaseLoaded = !1;
  28269. this.resolutionPromise = {};
  28270. this.tiledPanoRenderTarget = null;
  28271. this.zoomed = !1;
  28272. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderSuccess, this.onTileRendered.bind(this));
  28273. images360.panoRenderer.addEventListener(PanoRendererEvents.PanoRenderComplete, this.onPanoRendered.bind(this));
  28274. images360.panoRenderer.addEventListener(PanoRendererEvents.TileRenderFailure, this.onTileRenderFail.bind(this));
  28275. images360.panoRenderer.addEventListener(PanoRendererEvents.UploadAttemptedForAllTiles, this.onUploadAttemptedForAllTiles.bind(this));
  28276. }
  28277. this.addEventListener('hoverOn', e => {
  28278. //from Map
  28279. if (!e.byMainView) {
  28280. this.hoverOn(e);
  28281. }
  28282. });
  28283. this.addEventListener('hoverOff', e => {
  28284. if (!e.byMainView) {
  28285. this.hoverOff(e);
  28286. }
  28287. });
  28288. }
  28289. get noNeighbour() {
  28290. //是否绝对到不到的孤立点
  28291. for (var i = 0, j = this.images360.panos.length; i < j; i++) {
  28292. if (this.images360.neighbourMap[this.id][i] !== false) {
  28293. return false;
  28294. }
  28295. }
  28296. return true;
  28297. //return this.neighbours.length == 0
  28298. }
  28299. setEnable(enable) {
  28300. //是否可以走
  28301. Potree.Utils.updateVisible(this, 'isEnabled', enable); //令所有marker不可见
  28302. this.enabled = enable;
  28303. //如果当前在全景模式且在这个点,需要切换显示吗? 目前用不到
  28304. }
  28305. loadDepthImg() {
  28306. if (!this.pointcloud.hasDepthTex || this.depthTex || this.depthTexLoading) return;
  28307. this.depthTexLoading = true;
  28308. var mapping = Potree.settings.isLocal2 ? '' : this.pointcloud.datasetData.mapping; //非离线包的话加mapping
  28309. var src = "".concat(Potree.settings.urls.prefix1, "/").concat(mapping ? mapping + '/' : '').concat(Potree.settings.webSite, "/").concat(this.pointcloud.sceneCode, "/data/").concat(this.pointcloud.sceneCode, "/depthmap/").concat(this.originID, ".png");
  28310. // `${Potree.settings.urls.prefix1}/${Potree.settings.webSite}/${this.pointcloud.sceneCode}/data/${this.pointcloud.sceneCode}/depthmap/${this.originID}.png`
  28311. //console.log('开始下载depthImg', this.id)
  28312. var texture = texLoader$3.load(src, () => {
  28313. this.depthTex = texture;
  28314. this.dispatchEvent({
  28315. type: 'loadedDepthImg',
  28316. loaded: true
  28317. });
  28318. this.images360.dispatchEvent({
  28319. type: 'loadedDepthImg',
  28320. pano: this
  28321. });
  28322. this.depthTexLoading = false;
  28323. this.images360.updateDepthTex(this);
  28324. }, null, e => {
  28325. //error
  28326. console.error('loadDepthImg失败, 数据集sceneCode' + this.pointcloud.sceneCode, this.id);
  28327. this.pointcloud.hasDepthTex = false;
  28328. this.dispatchEvent({
  28329. type: 'loadedDepthImg'
  28330. });
  28331. });
  28332. texture.wrapS = RepeatWrapping;
  28333. texture.flipY = false;
  28334. texture.magFilter = LinearFilter;
  28335. texture.minFilter = LinearFilter;
  28336. texture.generateMipmaps = false;
  28337. }
  28338. build() {
  28339. {
  28340. // orientation
  28341. //add
  28342. //var quaternion = new THREE.Quaternion().multiplyQuaternions(this.quaternion, rot901);//改 为球目全
  28343. //quaternion.premultiply(rot90)
  28344. this.panoMatrix = new Matrix4().makeRotationFromQuaternion(this.quaternion);
  28345. this.oriPanoMatrix = this.panoMatrix.clone();
  28346. if (this.quaternion2) this.oriPanoMatrix2 = new Matrix4().makeRotationFromQuaternion(this.quaternion2);
  28347. //console.log(this.quaternion)
  28348. //this.quaternion = quaternion
  28349. }
  28350. /* let marker = new THREE.Mesh(planeGeo, this.getMarkerMat() )
  28351. //marker.lookAt(marker.up)
  28352. marker.scale.set(2,2,2) */
  28353. var marker = new Mesh(planeGeo, this.getMarkerMat()); //new Sprite({mat:this.getMarkerMat(), dontFixOrient:true })
  28354. marker.scale.set(2, 2, 2); //marker.scale.set(0.4,0.4,0.4)
  28355. marker.name = 'marker_' + this.id;
  28356. marker.up.set(0, 0, 1);
  28357. this.addEventListener('changeMarkerTex', e => {
  28358. marker.material.map = markerTex[e.name];
  28359. });
  28360. this.marker = marker;
  28361. marker.pano = this;
  28362. this.images360.node.add(marker);
  28363. Potree.settings.isTest && this.addLabel();
  28364. //this.addLabel2()
  28365. marker.addEventListener('mouseover', this.hoverOn.bind(this));
  28366. marker.addEventListener('mouseleave', this.hoverOff.bind(this));
  28367. }
  28368. transformByPointcloud() {
  28369. var position = this.originPosition.clone().applyMatrix4(this.pointcloud.transformMatrix); //也可以用datasetPosTransform算
  28370. var floorPosition = this.originFloorPosition.clone().applyMatrix4(this.pointcloud.transformMatrix);
  28371. this.setPosition(position, floorPosition);
  28372. this.panoMatrix = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix);
  28373. //this.panoMatrix2 = Potree.Utils.datasetRotTransform({fromDataset:true, pointcloud:this.pointcloud, matrix:this.oriPanoMatrix, getMatrix:true}) //和上一行结果一样
  28374. //quaternion也变下
  28375. if (this.oriPanoMatrix2) {
  28376. this.panoMatrix2 = new Matrix4().multiplyMatrices(this.pointcloud.rotateMatrix, this.oriPanoMatrix2); //供DepthImageSampler使用
  28377. this.panoMatrix2Inverse = this.panoMatrix2.clone().invert();
  28378. }
  28379. this.dispatchEvent('rePos');
  28380. }
  28381. setPosition(position, floorPosition) {
  28382. this.position = position;
  28383. this.floorPosition = floorPosition;
  28384. //this.mesh.position.copy(this.position)
  28385. this.marker.position.copy(this.floorPosition);
  28386. this.marker.position.z += 0.04; //会被点云遮住
  28387. if (this.label) {
  28388. if (Potree.settings.editType == 'pano') {
  28389. this.label.position.copy(this.position);
  28390. } else {
  28391. this.label.position.copy(this.floorPosition);
  28392. }
  28393. this.label.position.z += 0.14;
  28394. this.label.update();
  28395. }
  28396. /* if(this.label2){
  28397. if(Potree.settings.editType == 'pano'){
  28398. this.label2.position.copy(this.position)
  28399. }else{
  28400. this.label2.position.copy(this.floorPosition)
  28401. }
  28402. this.label2.position.copy(this.marker.position)
  28403. this.label2.update()
  28404. } */
  28405. }
  28406. /* getRealPos(){//当整体移动以后
  28407. return this.position.clone().applyMatrix4(viewer.scene.scene.matrix)
  28408. } */
  28409. getMarkerMat() {
  28410. if (!markerTex) {
  28411. markerTex = {
  28412. default: texLoader$3.load(Potree.resourcePath + '/textures/marker.png'),
  28413. ring: texLoader$3.load(Potree.resourcePath + '/textures/marker2.png')
  28414. };
  28415. markerTex.default.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  28416. markerTex.ring.anisotropy = 4;
  28417. //有可能被点云遮住吗。
  28418. }
  28419. return new DepthBasicMaterial({
  28420. opacity: markerOpacitys.default,
  28421. side: DoubleSide,
  28422. map: markerTex.default,
  28423. transparent: true,
  28424. clipDistance: 2,
  28425. occlusionDistance: 1,
  28426. //不能设置太短,因为过渡时深度不准确
  28427. useDepth: !!(Potree.settings.useDepthTex && this.pointcloud.hasDepthTex),
  28428. autoDepthTest: true
  28429. //改为DepthBasicMaterial是因为原Basic的材质在有深度图时过渡会先隐藏后出现。 注:没有深度图时全景模式的marker无法遮挡
  28430. });
  28431. }
  28432. hoverOn() {
  28433. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  28434. //console.log("hoverOn " + this.id )
  28435. transitions.start(lerp.property(this.marker.material, "opacity", markerOpacitys.hovered, () => {
  28436. viewer.dispatchEvent('content_changed');
  28437. }), this.marker.visible ? 250 : 0);
  28438. if (!e.byMap) this.dispatchEvent({
  28439. type: 'hoverOn',
  28440. byMainView: true
  28441. });
  28442. if (!e.byImages360) this.images360.dispatchEvent({
  28443. type: 'markerHover',
  28444. hovered: true,
  28445. pano: this
  28446. });
  28447. }
  28448. hoverOff() {
  28449. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  28450. //console.log("hoverOff " + this.id )
  28451. transitions.start(lerp.property(this.marker.material, "opacity", markerOpacitys.default, () => {
  28452. viewer.dispatchEvent('content_changed');
  28453. }), this.marker.visible ? 250 : 0);
  28454. if (!e.byMap) this.dispatchEvent({
  28455. type: 'hoverOff',
  28456. byMainView: true
  28457. });
  28458. if (!e.byImages360) this.images360.dispatchEvent({
  28459. type: 'markerHover',
  28460. hovered: false,
  28461. pano: this
  28462. });
  28463. }
  28464. setZoomed(zoomed) {
  28465. this.zoomed = zoomed;
  28466. Potree.settings.displayMode == 'showPanos' && this.updateSkyboxForZoomLevel(); //放大后换成zoomTarget贴图
  28467. viewer.dispatchEvent({
  28468. type: 'panoSetZoom',
  28469. zoomed
  28470. });
  28471. }
  28472. enter() {
  28473. this.entered = true;
  28474. this.setZoomed(!1);
  28475. viewer.dispatchEvent({
  28476. type: PanoramaEvents.Enter,
  28477. oldPano: old,
  28478. newPano: this
  28479. });
  28480. old = this;
  28481. //console.log("enter pano "+ this.id)
  28482. }
  28483. exit() {
  28484. this.clearWaitDeferreds();
  28485. this.minimumTiledPanoLoaded = !1;
  28486. this.tiledPanoRenderTarget = null;
  28487. this.setZoomed(!1);
  28488. this.images360.panoRenderer.deactivateTiledPano(this);
  28489. this.highestPartialTileRenderOpCompleted = 0;
  28490. this.highestFullTileRenderOpCompleted = 0;
  28491. this.depthTex && this.depthTex.dispose(); //贴图不使用后先dispose,下次到该点时会自动还原
  28492. this.entered = false; //add
  28493. //console.log("exit pano "+ this.id)
  28494. viewer.dispatchEvent({
  28495. type: PanoramaEvents.Exit,
  28496. pano: this
  28497. });
  28498. }
  28499. updateSkyboxForZoomLevel() {
  28500. if (this.minimumTiledPanoLoaded) {
  28501. this.images360.updateProjectedPanos();
  28502. }
  28503. }
  28504. getSkyboxTexture() {
  28505. if (this.minimumTiledPanoLoaded) {
  28506. if (this.zoomed && this.images360.qualityManager.maxRenderTargetSize > this.images360.qualityManager.maxNavPanoSize)
  28507. //change 如果放大后和不放大都是2k就不用这个
  28508. {
  28509. return this.images360.panoRenderer.zoomRenderTarget.texture;
  28510. } else {
  28511. this.tiledPanoRenderTarget.texture.mapping = UVMapping; //add
  28512. return this.tiledPanoRenderTarget.texture;
  28513. }
  28514. } else {
  28515. return null;
  28516. }
  28517. }
  28518. isLoaded(e) {
  28519. if (e && "string" == typeof e) console.error("Wrong panoSize given to Panorama.isLoaded(); a tiled pano uses PanoSizeClass");
  28520. return !!this.minimumTiledPanoLoaded && (!e || this.highestFullTileRenderOpCompleted >= e); //改:原本是:this.highestPartialTileRenderOpCompleted >= e, 希望这代表全部加载完
  28521. }
  28522. getWaitDeferred(size) {
  28523. //获取不同size的tile贴图的promiss
  28524. var t = this.resolutionPromise[this.id];
  28525. t || (t = {}, this.resolutionPromise[this.id] = t);
  28526. var i = t[size];
  28527. return i || (i = {
  28528. deferred: $.Deferred(),
  28529. active: !1
  28530. }, t[size] = i), i;
  28531. }
  28532. clearWaitDeferreds() {
  28533. var e = this.resolutionPromise[this.id];
  28534. e || (e = {}, this.resolutionPromise[this.id] = e);
  28535. for (var t in e) if (e.hasOwnProperty(t)) {
  28536. var i = e[t];
  28537. i.active = !1, i.deferred = $.Deferred();
  28538. }
  28539. }
  28540. resetWaitDeferred(e) {
  28541. var t = this.getWaitDeferred(e);
  28542. t.active = !1;
  28543. t.deferred = $.Deferred();
  28544. }
  28545. onTileRendered(ev) {
  28546. ev.id === this.id && this.dispatchEvent({
  28547. type: PanoramaEvents.TileLoaded,
  28548. size: ev.panoSize,
  28549. index: ev.tileIndex,
  28550. count: ev.totalTiles
  28551. });
  28552. }
  28553. onPanoRendered(ev) {
  28554. if (ev.id === this.id) {
  28555. this.minimumTiledPanoLoaded = !0;
  28556. this.updateSkyboxForZoomLevel(); //更新贴图 setProjected
  28557. ev.panoSize > this.highestPartialTileRenderOpCompleted && (this.highestPartialTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Partial size
  28558. ev.updateFullComplete && ev.panoSize > this.highestFullTileRenderOpCompleted && (this.highestFullTileRenderOpCompleted = ev.panoSize); //应该是更新最高获取到的Full size
  28559. //this.dispatchEvent("load", ev.panoSize);
  28560. viewer.ifAllLoaded(this);
  28561. this.dispatchEvent({
  28562. type: PanoramaEvents.LoadComplete,
  28563. size: ev.panoSize,
  28564. count: ev.totalTiles
  28565. });
  28566. }
  28567. }
  28568. onTileRenderFail(ev) {
  28569. ev.id === this.id && this.dispatchEvent({
  28570. type: PanoramaEvents.LoadFailed
  28571. });
  28572. }
  28573. onUploadAttemptedForAllTiles(ev) {
  28574. if (ev.id === this.id) {
  28575. var n = this.images360.qualityManager.getPanoSize(PanoSizeClass.BASE);
  28576. if (ev.panoSize === n && this.shouldRedrawOnBaseLoaded)
  28577. //shouldRedrawOnBaseLoaded一直是false。在4dkk里只有初始点在quickstart后变为true。
  28578. {
  28579. this.shouldRedrawOnBaseLoaded = !1;
  28580. this.panoRenderer.resetRenderStatus(this.id, !0, !1);
  28581. this.panoRenderer.renderPanoTiles(this.id, null, !0, !0);
  28582. }
  28583. }
  28584. }
  28585. addLabel() {
  28586. this.removeTextLabel();
  28587. this.label = new TextSprite$2(Object.assign({}, labelProp, {
  28588. text: this.id + "(" + this.originID + ")"
  28589. }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  28590. );
  28591. this.images360.node.add(this.label);
  28592. this.floorPosition && this.label.position.copy(this.floorPosition);
  28593. }
  28594. addLabel2() {
  28595. if (this.label2) return;
  28596. this.label2 = new TextSprite$2(Object.assign({}, labelProp2, {
  28597. text: /* this.originID */parseInt(this.id) + 1
  28598. }) //{text: `id:${this.id}, dataset:${this.pointcloud.name}, 4dkkId:${this.originID}`}
  28599. );
  28600. //this.images360.node.add(this.label2);
  28601. this.marker.add(this.label2);
  28602. //this.floorPosition && this.label2.position.copy(this.floorPosition)
  28603. var s = 0.2;
  28604. this.label2.scale.set(s, s, s);
  28605. Potree.Utils.updateVisible(this.label2, 'notDisplay', false);
  28606. Potree.Utils.updateVisible(this.label2, 'panoVisi', this.visible);
  28607. //Potree.Utils.setObjectLayers(this.label2, 'bothMapAndScene')
  28608. }
  28609. removeTextLabel() {
  28610. if (this.label) {
  28611. this.label.parent.remove(this.label);
  28612. }
  28613. }
  28614. dispose() {
  28615. var i = viewer.images360.panos.indexOf(this);
  28616. if (i == -1) return;
  28617. this.marker.parent.remove(this.marker);
  28618. this.removeTextLabel();
  28619. if (this.depthTex) this.depthTex.dispose();
  28620. viewer.images360.panos.splice(i, 1);
  28621. this.dispatchEvent('dispose');
  28622. //删除tile贴图、depthTex等以后再写
  28623. }
  28624. getCeilHeight() {
  28625. //天花板高度值 (假设不存在depth为0的点,所有为0的要么是在盲区,要么是无穷远。)
  28626. if (this.ceilZ == void 0) {
  28627. //const depthTiming = Potree.timeCollect.depthSampler.median //pc firefox达到4. chrome为0.01
  28628. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  28629. var rotMat = new Matrix4().makeRotationX((Potree.config.depthTexUVyLimit + 0.01) * Math.PI); // 角度不能小于天花板中空的半径
  28630. var dir0 = new Vector3(0, 0, 1).applyMatrix4(rotMat);
  28631. var dirs = [dir0, dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(Math.PI * 2 / 3)), dir0.clone().applyMatrix4(new Matrix4().makeRotationZ(-Math.PI * 2 / 3))];
  28632. /* if(depthTiming < 1){
  28633. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  28634. dirs.push(dirs[0].clone().applyMatrix4(rotMat1))
  28635. }
  28636. if(depthTiming < 0.3){
  28637. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  28638. dirs.push(dirs[0].clone().applyMatrix4(rotMat2));
  28639. } */
  28640. var zs = dirs.map(dir_ => {
  28641. var dir = dir_.clone().applyMatrix4(this.panoMatrix2); //pano不一定是垂直的, 需要把之前的dirInPano先转成真实的dir,防止超出角度限制
  28642. var intersect = viewer.images360.getIntersect(this, dir);
  28643. var z = intersect ? intersect.location.z : Infinity; /* this.position.z+skyHeight */ //没有intersect代表可能是天空
  28644. return z;
  28645. });
  28646. zs.sort((a, b) => {
  28647. return b - a;
  28648. }); //得最大值 (不用中位数的原因:在屋檐处,如果仅有一个intersect是天空,因到了室外所以也用天空高度)
  28649. this.ceilZ = zs[0];
  28650. var min = this.position.z + 1; // 防止意外太低
  28651. this.ceilZ = Math.max(min, this.ceilZ);
  28652. //console.log(this.id, 'ceilZ:', this.ceilZ )
  28653. }
  28654. return this.ceilZ;
  28655. }
  28656. }
  28657. ;
  28658. Panorama.prototype.loadTiledPano = function () {
  28659. //var downloads = [] , t = [];
  28660. var downloaded = {},
  28661. eventAdded = {},
  28662. latestPartialRequest = {}; //每个pano对应一组这些
  28663. return function (size, dirs, fov, o, a, download) {
  28664. var dir = dirs.datasetsLocal.find(e => e.datasetId == this.pointcloud.dataset_id).direction;
  28665. //var dir = dirs
  28666. null !== o && void 0 !== o || (o = !0), null !== a && void 0 !== a || (a = !0);
  28667. var l = this.getWaitDeferred(size),
  28668. c = l.deferred,
  28669. h = null,
  28670. u = null;
  28671. fov && ("number" == typeof fov ? h = fov : (h = fov.hFov, u = fov.vFov));
  28672. if (!this.isLoaded(size)) {
  28673. //console.log('loadTiledPano', this.id, size, fov)
  28674. if (!l.active) {
  28675. l.active = !0;
  28676. var name = this.id + ":" + size;
  28677. downloaded[name] = downloaded[name] || [];
  28678. /*
  28679. this.downloaded = downloaded
  28680. this.latestPartialRequest = latestPartialRequest
  28681. */
  28682. latestPartialRequest[name] = null;
  28683. if (fov) {
  28684. var tileArr = []; //add
  28685. var d = TileUtils.matchingTilesInDirection(this, size, dir, h, u, tileArr);
  28686. latestPartialRequest[name] = tileArr;
  28687. downloaded[name].forEach(e => {
  28688. var item = latestPartialRequest[name].find(a => e.faceTileIndex == a.faceTileIndex && e.face == a.face);
  28689. if (item) {
  28690. item.loaded = true;
  28691. }
  28692. });
  28693. if (!latestPartialRequest[name].some(e => !e.loaded)) {
  28694. //所需要的全部加载成功
  28695. //let total = TileUtils.getTileCountForSize(size)
  28696. //this.onPanoRendered(this.id, size, total, !0);
  28697. c.resolve(size /* , total */);
  28698. this.resetWaitDeferred(size);
  28699. //console.log('该部分早已经加载好了'+size, this.id)
  28700. latestPartialRequest[name] = null;
  28701. }
  28702. //console.log("Loading partial pano: " + this.id + " with " + d + " tiles")
  28703. }
  28704. if (!eventAdded[this.id]) {
  28705. eventAdded[this.id] = !0;
  28706. this.addEventListener(PanoramaEvents.LoadComplete, function (ev /* e, t */) {
  28707. //本次任务全部加载完毕
  28708. //console.warn('点位(可能部分)下载完成 ', 'id:'+this.id, 'size:'+ev.size )
  28709. var i = this.getWaitDeferred(ev.size).deferred; //"pending"为还未完成
  28710. i && "pending" === i.state() && this.highestPartialTileRenderOpCompleted >= ev.size && (i.resolve(ev.size, ev.count), this.resetWaitDeferred(ev.size)); //恢复active为false
  28711. }.bind(this));
  28712. this.addEventListener(PanoramaEvents.LoadFailed, function (ev) {
  28713. var t = this.getWaitDeferred(e).deferred;
  28714. t && "pending" === t.state() && this.highestPartialTileRenderOpCompleted >= ev.t && (t.reject(ev.t), this.resetWaitDeferred(ev.t)); //恢复active为false
  28715. }.bind(this));
  28716. this.addEventListener(PanoramaEvents.TileLoaded, function (ev /* t, i, n */) {
  28717. //每张加载完时
  28718. //console.log('tileLoaded', 'id:'+this.id, 'size:'+ev.size, 'tileIndex:'+ev.index )
  28719. var tileIndex = ev.index;
  28720. var total = ev.count;
  28721. var size = ev.size;
  28722. var name = this.id + ":" + size;
  28723. downloaded[name] = downloaded[name] || []; //不是所有的加载都是从loadTiledPano获取的所以会有未定义的情况
  28724. var {
  28725. faceTileIndex,
  28726. face
  28727. } = TileUtils.getTileLocation(size, tileIndex, {});
  28728. downloaded[name].push({
  28729. faceTileIndex,
  28730. face
  28731. });
  28732. var r = this.getWaitDeferred(size).deferred;
  28733. if (r && "pending" === r.state()) {
  28734. r.notify(size, tileIndex, total);
  28735. if (latestPartialRequest[name]) {
  28736. var item = latestPartialRequest[name].find(e => e.faceTileIndex == faceTileIndex && e.face == face);
  28737. item && (item.loaded = true);
  28738. if (!latestPartialRequest[name].some(e => !e.loaded)) {
  28739. //所需要的局部tiles全部加载成功
  28740. this.onPanoRendered(this.id, size, total, !0); //onPanoRendered还会触发 PanoramaEvents.LoadComplete
  28741. r.resolve(size, total);
  28742. this.resetWaitDeferred(size);
  28743. //console.log('该部分加载好了'+size, this.id)
  28744. latestPartialRequest[name] = null;
  28745. }
  28746. }
  28747. }
  28748. viewer.dispatchEvent('content_changed');
  28749. /* var r = this.getWaitDeferred(ev.size).deferred;
  28750. if (r && "pending" === r.state()) {
  28751. r.notify(ev.size, ev.index, ev.count);
  28752. var o = downloads[this.id + ":" + ev.size];
  28753. if(o){//如果有规定下载哪些tile,只需要下载这些tile则LoadComplete
  28754. o.tileCount++
  28755. if(o.tileCount === o.targetTileCount){//达到下载目标数
  28756. this.onPanoRendered(this.id, ev.size, ev.count, !0);
  28757. r.resolve(ev.size, ev.count);
  28758. this.resetWaitDeferred(ev.size)
  28759. }
  28760. }
  28761. } */
  28762. }.bind(this));
  28763. }
  28764. }
  28765. this.images360.tileDownloader.clearForceQueue();
  28766. this.images360.tileDownloader.forceQueueTilesForPano(this, size, dir, h, u, download);
  28767. this.tiledPanoRenderTarget = this.images360.panoRenderer.activateTiledPano(this, this.images360.qualityManager.getMaxNavPanoSize(), o);
  28768. this.images360.panoRenderer.renderPanoTiles(this.id, dirs, a);
  28769. } else {
  28770. //console.log('早已经全加载好了' +size, this.id)
  28771. c.resolve(size);
  28772. }
  28773. return c.promise();
  28774. };
  28775. }();
  28776. var {
  28777. ModelManagerEvents,
  28778. PanoSizeClass: PanoSizeClass$1
  28779. } = Potree.defines;
  28780. class QualityManager {
  28781. constructor(e, t, i) {
  28782. this.maxNavPanoSize = -1;
  28783. this.maxZoomPanoSize = -1;
  28784. this.devicePixelDensity = e;
  28785. this.deviceScreenSize = t;
  28786. this.clientBandwidth = i;
  28787. this.panoSizeClassMap = {};
  28788. this.useHighResolutionPanos = !0; //是否能够使用2k及以上图
  28789. this.useUltraHighResolutionPanos = !1;
  28790. this.modelHasUltraHighPanos = !1;
  28791. this.qualityManager = this;
  28792. this.maxRenderTargetSize = browser.isMobile() ? 2048 : 4096; //add
  28793. this.init();
  28794. }
  28795. init(e) {
  28796. //var metadata = store.getters['scene/metadata'] ;//有时候请求不到
  28797. //if(metadata.sceneSource == 11 || metadata.sceneScheme == 12){
  28798. /* if(config.tileClass == '1k'){
  28799. this.useHighResolutionPanos = false //xzw add 只加载1k
  28800. } */
  28801. this.buildPanoSizeClassMap(this.devicePixelDensity, this.deviceScreenSize, this.clientBandwidth);
  28802. this.ultraHighSize = this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  28803. this.highSize = this.getPanoSize(PanoSizeClass$1.HIGH);
  28804. this.standardSize = this.getPanoSize(PanoSizeClass$1.STANDARD);
  28805. this.baseSize = this.getPanoSize(PanoSizeClass$1.BASE);
  28806. config$1.tiling.maxZoomPanoQuality && this.ultraHighSize <= config$1.tiling.maxZoomPanoQuality && (config$1.tiling.allowUltraHighResolution = !0);
  28807. this.highQualityThreshold = browser.valueFromHash("threshold2k", config$1.windowHeightHighQualityThreshold);
  28808. this.updateMaximums();
  28809. //e.on(ModelManagerEvents.ActiveModelChanged, this.onModelChanged.bind(this));
  28810. }
  28811. updateFromModel(e) {
  28812. //this.updateHighResolutionSettings(e)
  28813. this.updateUltraHighResolutionSettings(e);
  28814. }
  28815. /* updateHighResolutionSettings(e) {
  28816. this.useHighResolutionPanos = !0
  28817. this.updateMaximums()
  28818. } */
  28819. updateUltraHighResolutionSettings(e) {
  28820. if (config$1.tiling.allowUltraHighResolution && this.modelHasUltraHighPanos) {
  28821. this.useUltraHighResolutionPanos = !0;
  28822. } else {
  28823. this.useUltraHighResolutionPanos = !1;
  28824. }
  28825. this.updateMaximums();
  28826. }
  28827. enableUltraHighQualityMode() {
  28828. this.modelHasUltraHighPanos = !0;
  28829. this.updateUltraHighResolutionSettings(null);
  28830. }
  28831. ultraHighQualityModeEnabled() {
  28832. return this.modelHasUltraHighPanos;
  28833. }
  28834. onModelChanged(e) {
  28835. this.updateFromModel(e.model), this.updateMaximums();
  28836. }
  28837. updateMaximums() {
  28838. this.maxNavPanoSize = config$1.tiling.maxNavPanoQuality || this.detectMaxNavPanoSize(), this.maxZoomPanoSize = config$1.tiling.maxZoomPanoQuality || this.detectMaxZoomPanoSize(), this.maxZoomPanoSize < this.maxNavPanoSize && (this.maxNavPanoSize = this.maxZoomPanoSize);
  28839. }
  28840. buildPanoSizeClassMap() {
  28841. this.panoSizeClassMap[PanoSizeClass$1.BASE] = 512, this.panoSizeClassMap[PanoSizeClass$1.STANDARD] = 1024, this.panoSizeClassMap[PanoSizeClass$1.HIGH] = 2048, this.panoSizeClassMap[PanoSizeClass$1.ULTRAHIGH] = 4096;
  28842. }
  28843. getPanoSize(e) {
  28844. return this.panoSizeClassMap[e];
  28845. }
  28846. getMaxPossiblePanoSize() {
  28847. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  28848. }
  28849. getMaxPanoSize() {
  28850. return this.maxZoomPanoSize;
  28851. }
  28852. getMaxNavPanoSize() {
  28853. return this.maxNavPanoSize;
  28854. }
  28855. getMaxZoomPanoSize() {
  28856. return this.maxZoomPanoSize;
  28857. }
  28858. detectMaxNavPanoSizeClass() {
  28859. //return this.useHighResolutionPanos ? browser.isMobile() ? PanoSizeClass.STANDARD : window.innerHeight < this.highQualityThreshold ? PanoSizeClass.STANDARD : PanoSizeClass.HIGH : PanoSizeClass.STANDARD
  28860. /* if(config.name == 'decor'){
  28861. return PanoSizeClass.STANDARD
  28862. }
  28863. return PanoSizeClass.HIGH */
  28864. switch (Potree.settings.navTileClass) {
  28865. case '1k':
  28866. return PanoSizeClass$1.STANDARD;
  28867. break;
  28868. case '2k':
  28869. default:
  28870. return PanoSizeClass$1.HIGH;
  28871. }
  28872. }
  28873. detectMaxNavPanoSize() {
  28874. var e = this.detectMaxNavPanoSizeClass();
  28875. return this.getPanoSize(e);
  28876. }
  28877. detectMaxZoomPanoSize() {
  28878. //获取当前zoomRenderTarget应下载的最高级别
  28879. //若是有三个级别,每次只需要加载到当前的zoomLevel;而两级时因为有zoomed来判断是使用基本贴图还是zoomRenderTarget,所以只需要返回最大的即可
  28880. if (this.zoomLevelResolution) {
  28881. //有三个级别
  28882. if (this.zoomLevelResolution == '4k' && this.useUltraHighResolutionPanos) {
  28883. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  28884. } else if (this.zoomLevelResolution == '1k' || !this.useHighResolutionPanos) {
  28885. return this.getPanoSize(PanoSizeClass$1.STANDARD);
  28886. } else {
  28887. return this.getPanoSize(PanoSizeClass$1.HIGH);
  28888. }
  28889. } else {
  28890. if (this.useHighResolutionPanos) {
  28891. /* if (browser.isMobile()) {//手机版如果要2k的将这里去掉
  28892. if (settings.tiling.mobileHighQualityOverride) {
  28893. return this.getPanoSize(PanoSizeClass.HIGH);
  28894. } else {
  28895. return this.getPanoSize(PanoSizeClass.STANDARD);
  28896. }
  28897. } else */
  28898. if (this.useUltraHighResolutionPanos) {
  28899. return this.getPanoSize(PanoSizeClass$1.ULTRAHIGH);
  28900. } else {
  28901. return this.getPanoSize(PanoSizeClass$1.HIGH);
  28902. }
  28903. } else {
  28904. return this.getPanoSize(PanoSizeClass$1.STANDARD);
  28905. }
  28906. }
  28907. }
  28908. }
  28909. var {
  28910. DownloadStatus
  28911. } = Potree.defines;
  28912. var h = Object.freeze({
  28913. None: 0,
  28914. DirectionalFOV: 1
  28915. });
  28916. var u = function () {
  28917. var e = function e(t, i) {
  28918. var n = e._panoSpaceDir,
  28919. r = e._fovThreshold,
  28920. o = e._fovThresholdNarrow,
  28921. a = Math.max(Math.min(n.dot(t.direction), 1), -1),
  28922. s = Math.max(Math.min(n.dot(i.direction), 1), -1);
  28923. return t._dot = a, i._dot = s, a >= r && s < r ? -1 : a < r && s >= r ? 1 : a >= o && s < o ? -1 : a < o && s >= o ? 1 : t.panoSize > i.panoSize ? 1 : i.panoSize > t.panoSize ? -1 : -(a - s);
  28924. };
  28925. return e._panoSpaceDir = new Vector3(), e._fovThreshold = -1, e._fovThresholdNarrow = -1, e;
  28926. }();
  28927. class TilePrioritizer {
  28928. //优先级处理序列
  28929. constructor(e, t, i, o, a) {
  28930. this.qualityManager = e;
  28931. this.maxNavQuality = this.qualityManager.getMaxNavPanoSize();
  28932. this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  28933. this.baseSize = t;
  28934. this.standardSize = i;
  28935. this.highSize = o;
  28936. this.ultraHighSize = a;
  28937. this.priorityCriteria = new TilePrioritizer.PriorityCriteria(null, new Vector3(0, 0, 0), new Vector3(0, 0, -1), new Vector3(0, 0, -1));
  28938. }
  28939. updateCriteria(e, t, i, n) {
  28940. //由player更新
  28941. this.priorityCriteria.pano = e, this.priorityCriteria.cameraPosition.copy(t),
  28942. //this.priorityCriteria.cameraDir.copy(i),
  28943. this.priorityCriteria.cameraDirs = i;
  28944. this.priorityCriteria.upcomingPanos = n, this.maxNavQuality = this.qualityManager.getMaxNavPanoSize(), this.maxZoomQuality = this.qualityManager.getMaxZoomPanoSize();
  28945. }
  28946. canDownloadSize(e) {
  28947. return this.maxNavQuality >= e || this.maxZoomQuality >= e && this.zoomingActive;
  28948. }
  28949. /* populateNeighborPanos(e, t, i) {
  28950. i = i || [],
  28951. i.length = 0;
  28952. var n = t.getNeighbours(e);
  28953. for (var r in n)
  28954. if (n.hasOwnProperty(r)) {
  28955. var o = t.get(r);
  28956. if(!o){
  28957. console.log(1)
  28958. }
  28959. i.push(o)
  28960. }
  28961. return i
  28962. } */
  28963. populateScoredPanos(e, t, i, dirs, a, dontFilterDir) {
  28964. i = i || [], i.length = 0;
  28965. var s = [Images360.filters.not(e)],
  28966. l = [Images360.scoreFunctions.distanceSquared(e), Images360.scoreFunctions.direction(e.position, dirs)],
  28967. c = Common.sortByScore(t, s, l);
  28968. if (!dontFilterDir) {
  28969. s.push(Images360.filters.inPanoDirection(e.position, dirs, TilePrioritizer.DIRECTION_SCORE_STRICTNESS));
  28970. }
  28971. if (c) for (var h = 0; h < c.length && h < a; h++) {
  28972. var u = c[h].item;
  28973. i.push(u);
  28974. }
  28975. return i;
  28976. }
  28977. queueTilesForPanos(e, t, i, n, r) {
  28978. for (var o = 0, a = 0; a < t.length; a++) {
  28979. var s = t[a],
  28980. l = this.queueTilesForPano(e, i, s, n);
  28981. if (o += l > 0 ? 1 : 0, r && o >= r) break;
  28982. }
  28983. return o;
  28984. }
  28985. /* queueTilesInDirectionForPanos(e, t, i, n, r, o, a, s) {//没用到
  28986. for (var l = 0, c = 0; c < i.length; c++) {
  28987. var h = i[c],
  28988. u = this.queueTilesInDirectionForPano(e, t, h, n, o, a);
  28989. if (l += u > 0 ? 1 : 0,
  28990. s && l >= s)
  28991. break
  28992. }
  28993. return l
  28994. }
  28995. */
  28996. canIncludeDescriptor(e) {
  28997. return e.status !== DownloadStatus.Downloading && e.status !== DownloadStatus.Downloaded;
  28998. }
  28999. canIncludePano(e, t) {
  29000. return !e.isLoaded(t);
  29001. }
  29002. getFOVDotThreshold(e) {
  29003. return Math.cos(MathUtils.degToRad(e / 2));
  29004. }
  29005. setZoomingActive(e) {
  29006. e !== this.zoomingActive && (this.zoomingActive = e);
  29007. }
  29008. }
  29009. TilePrioritizer.PriorityCriteria = function (e, t, i, n, o) {
  29010. this.pano = e, this.cameraPosition = new Vector3().copy(t),
  29011. //this.cameraDir = (new THREE.Vector3).copy(i),
  29012. this.cameraDirs = [],
  29013. //
  29014. this.panoSpaceDir = new Vector3().copy(n), this.upcomingPanos = o, this.copy = function (e) {
  29015. this.pano = e.pano, this.cameraPosition.copy(e.cameraPosition),
  29016. //this.cameraDir.copy(e.cameraDir),
  29017. this.cameraDirs = e.cameraDirs;
  29018. this.panoSpaceDir.copy(e.panoSpaceDir), this.upcomingPanos = o;
  29019. }, this.zoomingActive = !1;
  29020. };
  29021. TilePrioritizer.DIRECTIONAL_FOV = 180;
  29022. TilePrioritizer.DIRECTIONAL_FOV_NARROW = 120;
  29023. TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER = 6;
  29024. TilePrioritizer.MAX_SCORED_PANOS_TOADD = 2;
  29025. TilePrioritizer.MAX_UPCOMING_PANOS_TOADD = 3;
  29026. TilePrioritizer.DIRECTION_SCORE_STRICTNESS = .75;
  29027. TilePrioritizer.appendQueue = function (e, t) {
  29028. if (e && t) for (var i = 0; i < t.length; i++) {
  29029. e.push(t[i]);
  29030. //console.log(t[i])
  29031. }
  29032. };
  29033. TilePrioritizer.sortPanoTiles = function (descriptors, pano, dir) {
  29034. if (dir.datasetsLocal) dir = dir.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add
  29035. u._panoSpaceDir.copy(dir);
  29036. TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir); //应该是将dir根据quaternion转化下
  29037. u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  29038. u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  29039. descriptors.sort(u);
  29040. };
  29041. TilePrioritizer.insertSortedPanoTile = function (e, t, pano, dir) {
  29042. if (dir.datasetsLocal) dir = dir.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add
  29043. u._panoSpaceDir.copy(dir), TileUtils.getRelativeDirection(pano.quaternion4dkk, u._panoSpaceDir), u._fovThresholdNarrow = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV_NARROW), u._fovThreshold = math.getFOVDotThreshold(TilePrioritizer.DIRECTIONAL_FOV);
  29044. for (var o = -1, a = 0; a < e.length; a++) {
  29045. var s = u(t, e[a]);
  29046. if (s <= 0) {
  29047. o = a;
  29048. break;
  29049. }
  29050. }
  29051. if (o === -1) e[e.length] = t;else {
  29052. for (var h = e.length; h > o; h--) e[h] = e[h - 1];
  29053. e[o] = t;
  29054. }
  29055. };
  29056. TilePrioritizer.prototype.filterDepthTex = function (panos) {
  29057. // 下载depthTex
  29058. if (!Potree.settings.useDepthTex || !this.priorityCriteria.pano || viewer.mainViewport.view.isFlying()) return;
  29059. var cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  29060. var nearPanos = []; //用于获得邻近点位序列
  29061. this.populateScoredPanos(this.priorityCriteria.pano, panos, nearPanos, cameraDirLocals, Infinity, true);
  29062. var dlCount = browser.isMobile() ? 1 : 2;
  29063. var loadingCount = panos.filter(p => p.depthTexLoading).length;
  29064. if (viewer.mapViewer) {
  29065. var mapLayer = viewer.mapViewer.mapLayer;
  29066. loadingCount += mapLayer.loadingInProgress * 1.5 + mapLayer.waitQueue.length;
  29067. }
  29068. if (loadingCount < dlCount) {
  29069. nearPanos.filter(p => !p.depthTex).slice(0, dlCount - loadingCount).forEach(p => p.loadDepthImg());
  29070. }
  29071. this.nearPanos = nearPanos;
  29072. };
  29073. TilePrioritizer.prototype.filterAndPrioritize = function () {
  29074. //挑选出优先加载的 pano和tile (有点复杂,没看很懂)
  29075. var e = [],
  29076. t = [],
  29077. i = [];
  29078. return function (queue, panos, tileDownloader) {
  29079. //this.populateNeighborPanos(this.priorityCriteria.pano, panos, e);
  29080. /* let cameraDirLocals = this.priorityCriteria.cameraDirs.map(e=>{ //add
  29081. var dataset = viewer.scene.pointclouds.find(u=>u.dataset_id == e.datasetId)
  29082. var matrix = new THREE.Matrix4().copy(dataset.rotateMatrix)
  29083. var direction = math.convertVector.YupToZup(e.direction)
  29084. return {
  29085. datasetId:e.datasetId,
  29086. direction: direction.clone().applyMatrix4(matrix)
  29087. }
  29088. }) */
  29089. var cameraDirLocals = this.priorityCriteria.cameraDirs.vectorForward;
  29090. //获得视野范围内的邻近点位序列t
  29091. this.populateScoredPanos(this.priorityCriteria.pano, panos, t, cameraDirLocals, TilePrioritizer.MAX_SCORED_PANOS_TOCONSIDER);
  29092. //t.filter(p=>!p.depthTex).slice(0, Potree.config.depTexDlCount).forEach(p=>p.loadDepthImg()) //add
  29093. var s = this.baseSize //512
  29094. ,
  29095. l = this.standardSize //1024
  29096. ,
  29097. c = this.highSize //2048
  29098. ,
  29099. h = this.ultraHighSize; //4096
  29100. this.queueTilesForPano(queue, tileDownloader, this.priorityCriteria.pano, s); //把当前pano的512下载了
  29101. if (this.priorityCriteria.upcomingPanos) {
  29102. // 添加即将走到的点(之前用于导览路线)512 tiles
  29103. this.queueTilesForPanos(queue, this.priorityCriteria.upcomingPanos, tileDownloader, s, TilePrioritizer.MAX_UPCOMING_PANOS_TOADD);
  29104. }
  29105. i.length = 0;
  29106. //把当前pano角度范围内的tile按照分辨率从低到高加入队列
  29107. if (this.canDownloadSize(l)) {
  29108. //1024如果在限制范围内的话
  29109. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  29110. }
  29111. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  29112. TilePrioritizer.appendQueue(queue, i);
  29113. //添加邻近点t 512的tiles
  29114. this.queueTilesForPanos(queue, t, tileDownloader, s, TilePrioritizer.MAX_SCORED_PANOS_TOADD);
  29115. i.length = 0;
  29116. //NARROW :
  29117. if (this.canDownloadSize(c)) {
  29118. //2048
  29119. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  29120. }
  29121. if (this.canDownloadSize(h)) {
  29122. //4096
  29123. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV_NARROW);
  29124. }
  29125. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  29126. TilePrioritizer.appendQueue(queue, i);
  29127. i.length = 0;
  29128. if (this.canDownloadSize(l)) {
  29129. //1024
  29130. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, l, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  29131. }
  29132. if (this.canDownloadSize(c)) {
  29133. //2048
  29134. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, c, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  29135. }
  29136. if (this.canDownloadSize(h)) {
  29137. //4096
  29138. this.queueTilesInDirectionForPano(i, tileDownloader, this.priorityCriteria.pano, h, this.priorityCriteria.cameraPosition, this.priorityCriteria.cameraDirs, TilePrioritizer.DIRECTIONAL_FOV);
  29139. }
  29140. TilePrioritizer.sortPanoTiles(i, this.priorityCriteria.pano, this.priorityCriteria.cameraDirs); //排序
  29141. TilePrioritizer.appendQueue(queue, i);
  29142. this.queueTilesForPanos(queue, e, tileDownloader, s); // 如果前面有populateNeighborPanos的话,这步就是加neibour
  29143. };
  29144. }();
  29145. TilePrioritizer.prototype.queueTilesInDirectionForPano = function () {
  29146. var e = {
  29147. filter: h.DirectionalFOV,
  29148. direction: new Vector3(),
  29149. fov: 60
  29150. },
  29151. t = new Vector3();
  29152. return function (i, n, pano, o, a, dirs, c) {
  29153. var dir = dirs.datasetsLocal.find(e => e.datasetId == pano.pointcloud.dataset_id).direction; //add
  29154. //var dir = dirs
  29155. t.copy(dir);
  29156. TileUtils.getRelativeDirection(pano.quaternion4dkk, t);
  29157. e.direction.copy(t);
  29158. e.fov = c;
  29159. return this.filterAndQueueTileDownloadDescriptors(i, n, pano, o, e);
  29160. };
  29161. }();
  29162. TilePrioritizer.prototype.filterAndQueueTileDownloadDescriptors = function () {
  29163. var e = [];
  29164. return function (t, i, n, r, o) {
  29165. var a = i.getTileDownloadDescriptors(n, r);
  29166. e.length = 0, this.filterTileDownloadDescriptors(n, a, e, o);
  29167. for (var s = 0, l = 0; l < e.length; l++) {
  29168. var c = e[l];
  29169. if (c) {
  29170. t.push(c);
  29171. s++;
  29172. }
  29173. }
  29174. return s;
  29175. };
  29176. }();
  29177. TilePrioritizer.prototype.filterTileDownloadDescriptors = function () {
  29178. new Vector3();
  29179. return function (e, t, i, n) {
  29180. var r, o;
  29181. switch (n.filter) {
  29182. case h.DirectionalFOV:
  29183. for (r = 0; r < t.length; r++) o = t[r], TileUtils.isTileWithinFOV(o.panoSize, o.tileSize, o.face, o.tileX, o.tileY, n.direction, n.fov) && i.push(o);
  29184. break;
  29185. default:
  29186. for (r = 0; r < t.length; r++) o = t[r], i.push(o);
  29187. }
  29188. for (r = 0; r < i.length; r++) o = i[r], this.canIncludeDescriptor(o) || (i[r] = null);
  29189. };
  29190. }();
  29191. TilePrioritizer.prototype.queueTilesForPano = function () {
  29192. var e = {
  29193. filter: h.None
  29194. };
  29195. return function (t, i, n, r) {
  29196. return this.filterAndQueueTileDownloadDescriptors(t, i, n, r, e);
  29197. };
  29198. }();
  29199. /* TilePrioritizer.prototype.queueTilesForPanosInDirection = function () { //没用到
  29200. var e = new THREE.Vector3;
  29201. return function (t, i, n, r, o, a, s, l) {
  29202. for (var h = 0, u = 0; u < n.length; u++) {
  29203. var d = n[u];
  29204. e.copy(d.position),
  29205. e.sub(o),
  29206. e.normalize();
  29207. var p = Math.max(Math.min(a.dot(e), 1), -1),
  29208. f = c.getFOVDotThreshold(s);
  29209. if (p >= f) {
  29210. var g = this.queueTilesInDirectionForPano(t, i, d, r, o, a, s);
  29211. if (h += g > 0 ? 1 : 0,
  29212. l && h >= l)
  29213. break
  29214. }
  29215. }
  29216. return h
  29217. }
  29218. }() */
  29219. //import { i18n } from "@/lang/index"
  29220. // 媒体名称
  29221. /* export const mediaTypes = {
  29222. image: i18n.t("common.photo"),
  29223. video: i18n.t("common.video"),
  29224. audio: i18n.t("common.voice"),
  29225. } */
  29226. // 媒体扩展类型
  29227. var mediaMimes = {
  29228. image: ["jpg", "png", "jpeg", "bmp", "gif"],
  29229. audio: ["mp3", "aac", "ogg", "wav" /* , "m4a" */],
  29230. video: ["mp4", "mov", "quicktime", "webm" /* "rmvb", "wmv" */] //ios:mov
  29231. };
  29232. // 媒体大小显示(MB)
  29233. var mediaMaxSize = {
  29234. image: 10,
  29235. video: 20,
  29236. audio: 5
  29237. };
  29238. /**
  29239. * 获取媒体扩展类型
  29240. * @param {Stirng} filename 文件名称
  29241. */
  29242. var getMime = filename => {
  29243. if (!filename || filename.indexOf(".") === -1) {
  29244. return "";
  29245. }
  29246. return filename.split(".").pop().toLowerCase();
  29247. };
  29248. /**
  29249. * 在路径中获取文件名
  29250. * @param {*} path
  29251. */
  29252. var getFilename = path => {
  29253. var segment = (path || "").split("/");
  29254. return segment[segment.length - 1];
  29255. };
  29256. /**
  29257. * 检测媒体文件是否超过预设限制
  29258. * @param {String} type 媒体类型
  29259. * @param {Number} size 文件大小
  29260. */
  29261. var checkSizeLimit = (type, size) => {
  29262. size = size / 1024 / 1024;
  29263. return size <= mediaMaxSize[type];
  29264. };
  29265. var checkSizeLimitFree = (size, limit) => {
  29266. size = size / 1024 / 1024;
  29267. return size <= limit;
  29268. };
  29269. /**
  29270. * 检测媒体类型
  29271. * @param {String} type 媒体类型
  29272. * @param {String} filename 文件名称
  29273. */
  29274. var checkMediaMime = (type, filename) => {
  29275. var mime = getMime(filename);
  29276. var find = mediaMimes[type];
  29277. if (!find) {
  29278. return false;
  29279. }
  29280. return find.indexOf(mime) !== -1;
  29281. };
  29282. var checkMediaMimeByAccept = (accept, filename) => {
  29283. var mime = getMime(filename);
  29284. var type = accept;
  29285. if (type && type.indexOf("jpg") == -1 && type.indexOf("jpeg") != -1) {
  29286. type += ",image/jpg";
  29287. }
  29288. return (type || "").indexOf(mime) != -1;
  29289. };
  29290. var base64ToBlob = base64 => {
  29291. var arr = base64.split(","),
  29292. mime = arr[0].match(/:(.*?);/)[1],
  29293. bstr = atob(arr[1]),
  29294. n = bstr.length,
  29295. u8arr = new Uint8Array(n);
  29296. while (n--) {
  29297. u8arr[n] = bstr.charCodeAt(n);
  29298. }
  29299. return new Blob([u8arr], {
  29300. type: mime
  29301. });
  29302. };
  29303. var base64ToDataURL = base64 => {
  29304. return window.URL.createObjectURL(base64ToBlob(base64));
  29305. };
  29306. var blobToBase64 = function blobToBase64(blob) {
  29307. return new Promise(resolve => {
  29308. var reader = new FileReader();
  29309. reader.onload = function () {
  29310. resolve(reader.result);
  29311. };
  29312. reader.readAsDataURL(blob);
  29313. });
  29314. };
  29315. /*
  29316. * @Author: Rindy
  29317. * @Date: 2019-08-06 16:25:08
  29318. * @LastEditors: Rindy
  29319. * @LastEditTime: 2021-08-27 12:33:49
  29320. * @Description: Request
  29321. */
  29322. //import { $alert, $confirm, $loginTips } from "@/components/shared/message"
  29323. //import { $waiting } from "@/components/shared/loading"
  29324. //import { checkLogin } from "@/api"
  29325. //import { LoginDetector } from "@/core/starter"
  29326. //import { i18n } from "@/lang"
  29327. //import { password } from "@/utils/string"
  29328. //import store from "../Store"
  29329. // 空函数
  29330. var noop = function noop() {};
  29331. // 请求回调队列
  29332. var postQueue = [];
  29333. /**
  29334. * @property {number} NEXT - 继续执行
  29335. * @property {number} SUCCESS - 成功
  29336. * @property {number} EXCEPTION - 异常错误
  29337. * @property {number} FAILURE_CODE_3001 - 缺少必要参数
  29338. * @property {number} FAILURE_CODE_3002 - 访问异常
  29339. * @property {number} FAILURE_CODE_3003 - 非法访问
  29340. * @property {number} FAILURE_CODE_3004 - 用户未登录
  29341. * @property {number} FAILURE_CODE_3005 - 验证码已过期
  29342. * @property {number} FAILURE_CODE_3006 - 验证码错误
  29343. * @property {number} FAILURE_CODE_3007 - 昵称已存在
  29344. * @property {number} FAILURE_CODE_3008 - 该手机已被注册
  29345. * @property {number} FAILURE_CODE_3009 - 两次输入的密码不一致
  29346. * @property {number} FAILURE_CODE_3010 - 昵称长度错误
  29347. * @property {number} FAILURE_CODE_3011 - 密码长度错误
  29348. * @property {number} FAILURE_CODE_3012 - 昵称包含敏感词
  29349. * @property {number} FAILURE_CODE_3013 - 手机号码格式错误
  29350. * @property {number} FAILURE_CODE_3014 - 账号或密码不正确
  29351. * @property {number} FAILURE_CODE_3015 - 用户不存在
  29352. * @property {number} FAILURE_CODE_3016 - 您没有权限,请联系管理员
  29353. * @property {number} FAILURE_CODE_3017 - 空文件
  29354. * @property {number} FAILURE_CODE_3018 - 需要上传或使用的文件不存在
  29355. * @property {number} FAILURE_CODE_5010 - 找不到该场景对应的相机
  29356. * @property {number} FAILURE_CODE_5012 - 数据不正常
  29357. * @property {number} FAILURE_CODE_5014 - 无权操作该场景
  29358. * @property {number} FAILURE_CODE_5005 - 场景不存在
  29359. */
  29360. var statusCode = {
  29361. NEXT: -999,
  29362. SUCCESS: 0,
  29363. EXCEPTION: -1,
  29364. FAILURE_CODE_3001: 3001,
  29365. FAILURE_CODE_3002: 3002,
  29366. FAILURE_CODE_3003: 3003,
  29367. FAILURE_CODE_3004: 3004,
  29368. FAILURE_CODE_3005: 3005,
  29369. FAILURE_CODE_3006: 3006,
  29370. FAILURE_CODE_3007: 3007,
  29371. FAILURE_CODE_3008: 3008,
  29372. FAILURE_CODE_3009: 3009,
  29373. FAILURE_CODE_3010: 3010,
  29374. FAILURE_CODE_3011: 3011,
  29375. FAILURE_CODE_3012: 3012,
  29376. FAILURE_CODE_3013: 3013,
  29377. FAILURE_CODE_3014: 3014,
  29378. FAILURE_CODE_3015: 3015,
  29379. FAILURE_CODE_3016: 3016,
  29380. FAILURE_CODE_3017: 3017,
  29381. FAILURE_CODE_3018: 3018,
  29382. FAILURE_CODE_5010: 5010,
  29383. FAILURE_CODE_5012: 5012,
  29384. FAILURE_CODE_5014: 5014,
  29385. FAILURE_CODE_5005: 5005
  29386. };
  29387. /**
  29388. * 获取Token
  29389. * @function
  29390. */
  29391. function getToken() {
  29392. var urlToken = browser.urlHasValue("token", true);
  29393. if (urlToken) {
  29394. // 设置token共享给用户中心
  29395. localStorage.setItem("token", urlToken);
  29396. }
  29397. return urlToken || localStorage.getItem("token") || "";
  29398. }
  29399. /**
  29400. * 根据状态码的结果处理后续操作
  29401. * @function
  29402. * @param {number} code - 状态码
  29403. * @param {function} callback - 回调
  29404. */
  29405. function statusCodesHandler(code, callback) {
  29406. if (code == statusCode.EXCEPTION) {
  29407. return $alert({
  29408. content: i18n.t("tips.exception")
  29409. });
  29410. }
  29411. if (code == statusCode.FAILURE_CODE_3002 || code == statusCode.FAILURE_CODE_3003 || code == statusCode.FAILURE_CODE_3004) {
  29412. callback(code);
  29413. return showLoginTips();
  29414. }
  29415. if (code == statusCode.FAILURE_CODE_3001) {
  29416. callback(code);
  29417. return $alert({
  29418. content: i18n.t("tips.params_notfound")
  29419. });
  29420. }
  29421. if (code == statusCode.FAILURE_CODE_3017) {
  29422. callback(code);
  29423. return $alert({
  29424. content: i18n.t("tips.file_notfound")
  29425. });
  29426. }
  29427. if (code == statusCode.FAILURE_CODE_5005) {
  29428. /* if (!config.isEdit) {
  29429. return (location.href = config.pages.NotFound)
  29430. } */
  29431. callback(code);
  29432. return $alert({
  29433. content: i18n.t("tips.scene_notfound")
  29434. });
  29435. }
  29436. if (code == statusCode.FAILURE_CODE_5010) {
  29437. callback(code);
  29438. return $alert({
  29439. content: i18n.t("tips.camera_notfound")
  29440. });
  29441. }
  29442. if (code == statusCode.FAILURE_CODE_5012) {
  29443. callback(code);
  29444. return $alert({
  29445. content: i18n.t("tips.data_error")
  29446. });
  29447. }
  29448. if (code == statusCode.FAILURE_CODE_5014) {
  29449. callback(code);
  29450. return $alert({
  29451. content: i18n.t("tips.auth_deny")
  29452. });
  29453. }
  29454. return statusCode.NEXT;
  29455. }
  29456. $.ajaxSetup({
  29457. headers: {},
  29458. beforeSend: function beforeSend(xhr) {
  29459. var token = getToken();
  29460. if (token) {
  29461. xhr.setRequestHeader("token", token);
  29462. } else if (!token && this.url.indexOf("isLogin") != -1) {
  29463. showLoginTips();
  29464. }
  29465. /* if (config.oem == "localshow") {
  29466. // 本地版本兼容当前目录
  29467. if (this.url.indexOf("http") == -1 && this.url.indexOf("/") == 0) {
  29468. this.url = this.url.substr(1)
  29469. }
  29470. } */
  29471. // if(this.url.indexOf('http')==-1 && this.url.indexOf('/') !=0){
  29472. // this.url = '/'+this.url
  29473. // }
  29474. },
  29475. error: function error(xhr, status, _error) {
  29476. // 出错时默认的处理函数
  29477. if (this.url.indexOf("/scene.json") != -1 && xhr.status == 404) {
  29478. return $alert({
  29479. content: i18n.t("tips.scene_notfound")
  29480. });
  29481. } else if (this.type === "POST") {
  29482. return $alert({
  29483. content: i18n.t("tips.network_error")
  29484. });
  29485. }
  29486. },
  29487. success: function success(result) {},
  29488. complete: function complete() {
  29489. // Post类型请求无论成功或失败都关闭等待提示
  29490. if (this.type === "POST") {
  29491. http.__loading && $waiting.hide();
  29492. }
  29493. http.__loading = true;
  29494. }
  29495. });
  29496. /**
  29497. * @namespace http
  29498. * @type {Object}
  29499. */
  29500. var http = {
  29501. statusCode,
  29502. __loading: true,
  29503. __request(xhr, method, url, data, done, fail) {
  29504. if (typeof done != "function") {
  29505. done = noop;
  29506. }
  29507. if (typeof fail != "function") {
  29508. fail = noop;
  29509. }
  29510. xhr.done(result => {
  29511. if (typeof result.code !== "undefined") {
  29512. var flag = statusCodesHandler(result.code, function (code) {
  29513. // 需要登录的状态
  29514. if (code == statusCode.FAILURE_CODE_3001 || code == statusCode.FAILURE_CODE_3002 || code == statusCode.FAILURE_CODE_3003 || code == statusCode.FAILURE_CODE_3004) {
  29515. if (url.indexOf("isLogin") == -1 && url.indexOf("openSceneBykey") == -1) {
  29516. postQueue.push(function () {
  29517. http[method](url, data, done, fail);
  29518. });
  29519. }
  29520. }
  29521. fail();
  29522. });
  29523. if (flag === statusCode.NEXT) {
  29524. done(result, result.code == 0);
  29525. }
  29526. } else {
  29527. done(result);
  29528. }
  29529. });
  29530. xhr.fail(fail);
  29531. xhr.always(() => xhr = null);
  29532. return xhr;
  29533. },
  29534. /**
  29535. * Get请求
  29536. * @param {String} url 请求地址
  29537. * @param {Object?} data 请求参数
  29538. * @param {Function?} done 成功回调
  29539. * @param {Function?} fail 失败回调
  29540. */
  29541. get(url) {
  29542. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29543. var done = arguments.length > 2 ? arguments[2] : undefined;
  29544. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29545. if (/\.json/.test(url)) {
  29546. // json文件格式自动调用getJson方法
  29547. return this.getJson(url, data, done, fail);
  29548. }
  29549. return this.__request($.get(url, data), "get", url, data, done, fail);
  29550. },
  29551. /**
  29552. * Get Blob请求
  29553. * @param {String} url 请求地址
  29554. * @param {Object?} data 请求参数
  29555. * @param {Function?} done 成功回调
  29556. * @param {Function?} fail 失败回调
  29557. */
  29558. getText(url) {
  29559. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29560. var done = arguments.length > 2 ? arguments[2] : undefined;
  29561. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29562. return this.__request($.ajax({
  29563. url: url,
  29564. dataType: "text"
  29565. }), "getText", url, data, done, fail);
  29566. },
  29567. /**
  29568. * GetJson请求 读取json文件数据
  29569. * @param {String} url 请求地址
  29570. * @param {Object?} data 请求参数
  29571. * @param {Function?} done 成功回调
  29572. * @param {Function?} fail 失败回调
  29573. */
  29574. getJson(url) {
  29575. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29576. var done = arguments.length > 2 ? arguments[2] : undefined;
  29577. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29578. return this.__request($.getJSON(url, data), "get", url, data, done, fail);
  29579. },
  29580. /**
  29581. * Get Blob请求
  29582. * @param {String} url 请求地址
  29583. * @param {Object?} data 请求参数
  29584. * @param {Function?} done 成功回调
  29585. * @param {Function?} fail 失败回调
  29586. */
  29587. getBlob(url) {
  29588. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29589. var done = arguments.length > 2 ? arguments[2] : undefined;
  29590. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29591. return this.__request($.ajax({
  29592. url: url,
  29593. dataType: "blob"
  29594. }), "getBlob", url, data, done, fail);
  29595. },
  29596. /**
  29597. * Get Arraybuffer请求
  29598. * @param {String} url 请求地址
  29599. * @param {Object?} data 请求参数
  29600. * @param {Function?} done 成功回调
  29601. * @param {Function?} fail 失败回调
  29602. */
  29603. getArraybuffer(url) {
  29604. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29605. var done = arguments.length > 2 ? arguments[2] : undefined;
  29606. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29607. return this.__request($.ajax({
  29608. url: url,
  29609. dataType: "arraybuffer"
  29610. }), "getArraybuffer", url, data, done, fail);
  29611. },
  29612. /**
  29613. * Post 请求
  29614. * @param {String} url 请求地址
  29615. * @param {Object?} data 请求参数
  29616. * @param {Function?} done 成功回调
  29617. * @param {Function?} fail 失败回调
  29618. */
  29619. post(url) {
  29620. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29621. var done = arguments.length > 2 ? arguments[2] : undefined;
  29622. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29623. if (url.indexOf("isLogin") == -1) {
  29624. http.__loading && $waiting.show();
  29625. }
  29626. return this.__request($.post(url, data), "post", url, data, done, fail);
  29627. },
  29628. /**
  29629. * PostJson 请求
  29630. * @param {String} url 请求地址
  29631. * @param {Object?} data 请求参数
  29632. * @param {Function?} done 成功回调
  29633. * @param {Function?} fail 失败回调
  29634. */
  29635. postJson(url) {
  29636. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29637. var done = arguments.length > 2 ? arguments[2] : undefined;
  29638. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29639. http.__loading && $waiting.show();
  29640. return this.__request($.ajax({
  29641. type: "POST",
  29642. url: url,
  29643. contentType: "application/json",
  29644. data: JSON.stringify(data)
  29645. }), "postJson", url, data, done, fail);
  29646. },
  29647. /**
  29648. * Post 表单 支持文件上传
  29649. * @param {String} url 请求地址
  29650. * @param {FormData?} formData 请求参数
  29651. * @param {Function?} done 成功回调
  29652. * @param {Function?} fail 失败回调
  29653. */
  29654. postForm(url, formData, done, fail, onProgress) {
  29655. if (typeof onProgress === "function") {
  29656. return this.__request($.ajax({
  29657. type: "POST",
  29658. url: url,
  29659. processData: false,
  29660. contentType: false,
  29661. data: formData,
  29662. xhr: function xhr() {
  29663. var xhr = new XMLHttpRequest();
  29664. xhr.upload.addEventListener("progress", function (e) {
  29665. onProgress(e.loaded / e.total * 100 + "%");
  29666. });
  29667. return xhr;
  29668. }
  29669. }), "postForm", url, formData, done, fail);
  29670. } else {
  29671. http.__loading && $waiting.show();
  29672. return this.__request($.ajax({
  29673. type: "POST",
  29674. url: url,
  29675. processData: false,
  29676. contentType: false,
  29677. data: formData
  29678. }), "postForm", url, formData, done, fail);
  29679. }
  29680. },
  29681. /**
  29682. * 加载图片
  29683. * @param {String} url 请求地址
  29684. * @param {Number?} retry 重试次数,默认为3
  29685. */
  29686. loadImage(url) {
  29687. var retry = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
  29688. var def = $.Deferred();
  29689. var img = new Image();
  29690. /* if (process.env.VUE_APP_REGION == "AWS" && url.indexOf("x-oss-process=image") != -1) {
  29691. var arr = url.split("?")
  29692. url = arr[0] + encodeURIComponent("?" + arr[1].replace(/\//g, "@"))
  29693. } */
  29694. var load = () => {
  29695. console.warn("Retrying load image: " + url);
  29696. this.loadImage(url, retry - 1).done(def.resolve.bind(def)).progress(def.notify.bind(def)).fail(def.reject.bind(def));
  29697. };
  29698. img.onerror = function () {
  29699. retry > 0 ? setTimeout(() => load(), 1e3) : def.reject("[".concat(url, "]\u52A0\u8F7D\u5931\u8D25"));
  29700. };
  29701. img.onload = function () {
  29702. def.resolve(img);
  29703. };
  29704. img.crossOrigin = "anonymous";
  29705. img.src = url;
  29706. return def;
  29707. },
  29708. /**
  29709. * 上传文件
  29710. * @param {String} url 请求地址
  29711. * @param {Object?} data 请求参数
  29712. * @param {Function?} done 成功回调
  29713. * @param {Function?} fail 失败回调
  29714. */
  29715. uploadFile(url) {
  29716. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29717. var done = arguments.length > 2 ? arguments[2] : undefined;
  29718. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29719. var onProgress = arguments.length > 4 ? arguments[4] : undefined;
  29720. var form = new FormData();
  29721. // if (file.needTransfer) { //ie和苹果都不支持dataURLtoFile得传送,所以只能用blob
  29722. // form.append("file", common.dataURLtoBlob(file.file), file.name || file.file.name);
  29723. // } else {
  29724. // form.append("file", file.file, file.name || file.file.name);
  29725. // }
  29726. for (var key in data) {
  29727. if (key == "file") {
  29728. form.append("file", data[key], data.filename || data[key].name);
  29729. } else if (key != "filename") {
  29730. form.append(key, data[key]);
  29731. }
  29732. }
  29733. return this.postForm(url, form, done, fail, onProgress);
  29734. },
  29735. /**
  29736. * 上传文件
  29737. * @param {String} url 请求地址
  29738. * @param {Object?} data 请求参数 {file:'base64 string',filename:'image.jpg',...}
  29739. * @param {Function?} done 成功回调
  29740. * @param {Function?} fail 失败回调
  29741. */
  29742. uploadBlobFile(url) {
  29743. var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  29744. var done = arguments.length > 2 ? arguments[2] : undefined;
  29745. var fail = arguments.length > 3 ? arguments[3] : undefined;
  29746. var form = new FormData();
  29747. for (var key in data) {
  29748. if (key === "file") {
  29749. form.append("file", base64ToBlob(data.file), data.filename);
  29750. } else if (key != "filename") {
  29751. form.append(key, data[key]);
  29752. }
  29753. }
  29754. return this.postForm(url, form, done, fail);
  29755. }
  29756. };
  29757. var {
  29758. TileDownloaderEvents,
  29759. DownloadStatus: DownloadStatus$1
  29760. } = Potree.defines;
  29761. window.downloaded = {};
  29762. window.startdownloads = [];
  29763. class TileDownloader extends EventDispatcher {
  29764. constructor() {
  29765. super();
  29766. this.panos = null;
  29767. this.retryMinimumTime = 1e4;
  29768. this.panoLoadCallbacks = {};
  29769. this.downloadDescriptors = {};
  29770. this.priorityQueue = [];
  29771. this.forceQueue = [];
  29772. this.activeDownloads = [];
  29773. this.tilePrioritizer = null;
  29774. this.refreshInterval = null;
  29775. this.processPriorityQueue = !1;
  29776. this.concurrentDownloads = 6; //e.concurrentDownloads || 1;
  29777. this.downloadTestResults = {};
  29778. this.freeze = Object.freeze({
  29779. Testing: 1,
  29780. Success: 2,
  29781. Fail: 3
  29782. });
  29783. /* viewer.addEventListener('pageVisible', (e)=>{//不可见时不refreshUpdateInterval
  29784. //console.log('visibilitychange:', state)
  29785. Potree.Utils.updateVisible(this, 'pageVisible', e.v)
  29786. this.judgeStart()
  29787. })
  29788. this.visible = true //add 借用Potree.Utils.updateVisible来判断是否start
  29789. if(Potree.settings.useDepthTex){
  29790. this.judgeStart() //开始下载depthTex
  29791. }else{
  29792. Potree.Utils.updateVisible(this,'showPanos', false ) //默认visible = false
  29793. } */
  29794. }
  29795. setPanoData(e, t /* , i */) {
  29796. this.panos = e, this.imagePanos = t;
  29797. // this.panoGroupId = i
  29798. }
  29799. start() {
  29800. this.downloadCubeTex = true;
  29801. /* if(!Potree.settings.useDepthTex){
  29802. Potree.Utils.updateVisible(this,'showPanos', true )
  29803. this.judgeStart()
  29804. }else{
  29805. //this.refreshInterval || this.judgeStart()
  29806. } */
  29807. }
  29808. stop() {
  29809. this.downloadCubeTex = false;
  29810. /* if(!Potree.settings.useDepthTex){
  29811. Potree.Utils.updateVisible(this,'showPanos', false )
  29812. this.judgeStart()
  29813. } */
  29814. }
  29815. /* judgeStart(){//add
  29816. if(this.visible){
  29817. //console.log('judgeStart true')
  29818. this.started = true
  29819. //this.refreshUpdateInterval(0)
  29820. }else{
  29821. //console.log('judgeStart false')
  29822. this.started = false
  29823. //window.clearTimeout(this.refreshInterval)
  29824. }
  29825. } */
  29826. /* refreshUpdateInterval(e) {
  29827. e || (e = 0),
  29828. this.refreshInterval = window.setTimeout(function() {
  29829. var e = this.update();
  29830. e ? this.refreshUpdateInterval(TileDownloader.ACTIVE_REFRESH_DELAY) : this.refreshUpdateInterval(TileDownloader.IDLE_REFRESH_DELAY)
  29831. }
  29832. .bind(this), e)
  29833. } */
  29834. update() {
  29835. if (this.downloadCubeTex) {
  29836. //可以下载贴图
  29837. var e = this.forceQueue.length > 0;
  29838. this.processQueueForDownloading(this.forceQueue);
  29839. if (this.processPriorityQueue) {
  29840. Potree.Common.intervalTool.isWaiting('processPriorityQueue', () => {
  29841. //延时update,防止崩溃 , 未到时间就拦截(第一次直接执行)
  29842. this.queuePrioritizedTilesForPanos(this.panos); //这句比较耗时 降四倍时大概1-2毫秒
  29843. }, 66);
  29844. this.priorityQueue.length > 0 && (e = !0);
  29845. this.processQueueForDownloading(this.priorityQueue);
  29846. }
  29847. //return e
  29848. }
  29849. Potree.Common.intervalTool.isWaiting('filterDepthTex', () => {
  29850. this.tilePrioritizer.filterDepthTex(this.panos); //下载深度图
  29851. }, 77);
  29852. }
  29853. queuePrioritizedTilesForPanos(e) {
  29854. this.tilePrioritizer && (this.clearQueue(this.priorityQueue), this.tilePrioritizer.filterAndPrioritize(this.priorityQueue, e, this), this.clearFromQueue(this.priorityQueue, DownloadStatus$1.None, !0),
  29855. //去除state为DownloadStatus.None的(可能是去除已经在下载的)
  29856. this.setStatusOrRemoveForAllDescriptors(this.priorityQueue, DownloadStatus$1.Queued));
  29857. }
  29858. clearQueue(e) {
  29859. //停止下载并清空
  29860. this.setStatusForAllDescriptors(e, DownloadStatus$1.None), e.length = 0;
  29861. }
  29862. clearForceQueue() {
  29863. this.clearQueue(this.forceQueue);
  29864. }
  29865. clearFromQueue(e, t, i) {
  29866. for (var n = 0; n < e.length; n++) {
  29867. var r = e[n];
  29868. r && (t === r.status && !i || t !== r.status && i) && (e[n] = null);
  29869. }
  29870. }
  29871. setStatusForAllDescriptors(e, t) {
  29872. for (var i = 0; i < e.length; i++) {
  29873. var n = e[i];
  29874. n && (n.status = t);
  29875. }
  29876. }
  29877. setStatusOrRemoveForAllDescriptors(e, t) {
  29878. for (var i = 0; i < e.length; i++) {
  29879. var n = e[i];
  29880. n && (n.status !== t ? n.status = t : e[i] = null);
  29881. }
  29882. }
  29883. getTileDownloadDescriptors(pano, size) {
  29884. //获取该pano的该size的全部的tile的descriptor
  29885. var i = this.getAllTileDownloadDescriptorsForPano(pano),
  29886. n = i[size];
  29887. return n || (n = this.buildDownloadDescriptorArray(size),
  29888. //创建的全部是空的
  29889. i[size] = n, this.initTileDownloadDescriptors(n, pano, size)),
  29890. //绑定到该pano size
  29891. n;
  29892. }
  29893. getAllTileDownloadDescriptorsForPano(pano) {
  29894. //新建空Descriptors
  29895. var t = this.downloadDescriptors[pano.id];
  29896. return t || (t = {}, this.downloadDescriptors[pano.id] = t), t;
  29897. }
  29898. processQueueForDownloading(e, t) {
  29899. //执行下载任务
  29900. this.cleanupActiveDownloads();
  29901. if (e.length) {
  29902. var concurrentDownloads = Potree.Common.getBestCount('concurrentDownloads', 1, 6, 1.8, 14 /* ,true */); //flying ? (isMobile ? 2 : 3) : 6
  29903. if (this.activeDownloads.length < concurrentDownloads || t) {
  29904. var i = t ? e.length : concurrentDownloads - this.activeDownloads.length;
  29905. for (var n = 0, r = 0; n < i && e.length > 0; r++) {
  29906. var o = e.shift();
  29907. if (o) {
  29908. //add 为了防止1024的在512前下载完,这里强行等待512下载完毕再开始下载
  29909. if (o.panoSize > 512 && !this.isPanoDownloaded(o.pano, 512)) {
  29910. //console.log('512的还没下载好呢!')
  29911. e.push(o);
  29912. break; //一般512的都是连续下载的,所以后面就都不是512了直接中断
  29913. }
  29914. this.startDownload(o);
  29915. n++;
  29916. }
  29917. }
  29918. }
  29919. }
  29920. }
  29921. testDownload(panoSize, tileSize, callback) {
  29922. var n = this.downloadTestResults[panoSize];
  29923. if (n) return void (n === this.freeze.Success ? callback(!0) : n === this.freeze.Fail && callback(!1));
  29924. this.downloadTestResults[panoSize] = this.freeze.Testing;
  29925. var r = this.panos[0],
  29926. o = this.getTileUrl({
  29927. pano: r,
  29928. panoSize,
  29929. tileSize,
  29930. tileIndex: 0
  29931. } /* r.id, panoSize, tileSize, 0 */),
  29932. a = function (t) {
  29933. this.downloadTestResults[panoSize] = this.freeze.Success, callback(!0);
  29934. }.bind(this),
  29935. s = function () {
  29936. this.downloadTestResults[panoSize] = this.freeze.Fail, callback(!1);
  29937. }.bind(this);
  29938. this.loadImage(o, 0, a, s);
  29939. }
  29940. startDownload(e) {
  29941. //开始下载啦
  29942. //console.log('startDownload')
  29943. startdownloads.push(e);
  29944. e.local2SrcFailed = this.local2SrcFailed;
  29945. e.status = DownloadStatus$1.Downloading;
  29946. var t = this.getTileUrl(e /* e.pano.id, e.panoSize, e.tileSize, e.tileIndex, e.pano.alignmentType */); //xzw add alignmentType
  29947. if (!t) return;
  29948. this.activeDownloads.push(e);
  29949. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  29950. }
  29951. downloadFailed(e, t) {
  29952. //add
  29953. if (Potree.settings.isLocal2 && !e.local2SrcFailed) {
  29954. //为了兼容旧的数据src,如果新src没加载成功,就加载旧的
  29955. e.local2SrcFailed = this.local2SrcFailed = true;
  29956. //this.startDownload(e)//重新下载
  29957. var t = this.getTileUrl(e);
  29958. this.loadImage(t, TileDownloader.DOWNLOAD_RETRIES, this.downloadComplete.bind(this, e), this.downloadFailed.bind(this, e));
  29959. }
  29960. }
  29961. downloadComplete(e, t) {
  29962. //下载成功时
  29963. //if (e.panoGroupId === this.panoGroupId) {
  29964. var i = this.getPanoLoadCallbacks(e.pano, e.panoSize);
  29965. e.status = DownloadStatus$1.Downloaded, i && i.onProgress && i.onProgress(e.pano, e.panoSize);
  29966. var n = {
  29967. panoId: e.pano.id,
  29968. image: t,
  29969. tileSize: e.tileSize,
  29970. panoSize: e.panoSize,
  29971. tileIndex: e.tileIndex,
  29972. faceTileIndex: e.faceTileIndex,
  29973. totalTiles: e.totalTiles,
  29974. face: e.face,
  29975. tileX: e.tileX,
  29976. tileY: e.tileY,
  29977. direction: e.direction
  29978. };
  29979. downloaded[e.pano.id] || (downloaded[e.pano.id] = {
  29980. 512: [],
  29981. 1024: [],
  29982. 2048: []
  29983. });
  29984. downloaded[e.pano.id][e.panoSize] || (downloaded[e.pano.id][e.panoSize] = []);
  29985. downloaded[e.pano.id][e.panoSize].push(e);
  29986. if (e.panoSize != 512 && downloaded[e.pano.id][512].length < 6) {
  29987. console.warn('没下完');
  29988. }
  29989. e.image = t, this.dispatchEvent({
  29990. type: TileDownloaderEvents.TileDownloadSuccess,
  29991. desc: n
  29992. });
  29993. this.isPanoDownloaded(e.pano, e.panoSize) && (n = {
  29994. panoId: e.pano.id,
  29995. tileSize: e.tileSize,
  29996. panoSize: e.panoSize
  29997. }, this.dispatchEvent({
  29998. type: TileDownloaderEvents.PanoDownloadComplete,
  29999. desc: n
  30000. }), i && i.onLoad && i.onLoad(e.pano, e.panoSize));
  30001. //}
  30002. }
  30003. isPanoDownloaded(e, t) {
  30004. var i = this.getTileDownloadDescriptors(e, t);
  30005. if (i.length <= 0) return !1;
  30006. for (var n = 0; n < i.length; n++) {
  30007. var r = i[n];
  30008. if (r.status !== DownloadStatus$1.Downloaded) return !1;
  30009. }
  30010. return !0;
  30011. }
  30012. setPanoLoadCallbacks(e, t, i, n, r) {
  30013. var o = e.id + ":" + this.qualityManager.getPanoSize(t);
  30014. this.panoLoadCallbacks[o] = {
  30015. onLoad: i,
  30016. onFail: n,
  30017. onProgress: r
  30018. };
  30019. }
  30020. getPanoLoadCallbacks(e, t) {
  30021. var i = e.id + ":" + t;
  30022. return this.panoLoadCallbacks[i];
  30023. }
  30024. buildDownloadDescriptorArray(e) {
  30025. for (var t = TileUtils.getTileCountForSize(e), i = [], n = 0; n < t; n++) {
  30026. var r = this.buildDownloadDescriptor();
  30027. i.push(r);
  30028. }
  30029. return i;
  30030. }
  30031. buildDownloadDescriptor() {
  30032. //Descriptor!
  30033. var e = {
  30034. panoGroupId: null,
  30035. pano: null,
  30036. panoSize: -1,
  30037. tileSize: -1,
  30038. tileIndex: -1,
  30039. totalTiles: -1,
  30040. faceTileIndex: -1,
  30041. status: DownloadStatus$1.None,
  30042. url: null,
  30043. image: null,
  30044. direction: new Vector3(),
  30045. //该tile在cube中的方向
  30046. face: -1,
  30047. cubeFace: -1,
  30048. tileX: -1,
  30049. tileY: -1
  30050. };
  30051. return e;
  30052. }
  30053. initTileDownloadDescriptors(e, t, i) {
  30054. for (var n = 0; n < e.length; n++) {
  30055. var r = e[n];
  30056. this.initTileDownloadDescriptor(r, t, i, n);
  30057. }
  30058. }
  30059. initTileDownloadDescriptor(desc, pano, size, index) {
  30060. var r = size >= TileUtils.TILE_SIZE ? TileUtils.TILE_SIZE : size;
  30061. desc.face = TileUtils.getFaceForTile(size, index); //根据顺序得到的face的index
  30062. desc.cubeFace = TileUtils.mapFaceToCubemapFace(desc.face); //为了贴图而转化的face index
  30063. //desc.panoGroupId = this.panoGroupId;//就是场景号
  30064. desc.pano = pano;
  30065. desc.panoSize = size;
  30066. desc.tileSize = r; //瓦片图size 512
  30067. desc.tileIndex = index;
  30068. desc.totalTiles = TileUtils.getTileCountForSize(size);
  30069. desc.status = DownloadStatus$1.None;
  30070. desc.image = null;
  30071. TileUtils.getTileLocation(desc.panoSize, desc.tileIndex, desc); //得到该tile在这个face中的具体位置(tileX等)
  30072. TileUtils.getTileVector(desc.panoSize, desc.tileSize, desc.cubeFace, desc.tileX, desc.tileY, TileUtils.LocationOnTile.Center, 0, desc.direction);
  30073. }
  30074. getTiles(d, sceneNum, useV4url, pointcloud) {
  30075. var v3OrV4Str = useV4url ? "/scene_view_data/".concat(sceneNum, "/images/") : "/images/images".concat(sceneNum, "/");
  30076. if (Potree.settings.isLocal && !this.local2SrcFailed && pointcloud.datasetData.mapping && !Potree.settings.isLocal2) {
  30077. //非离线包的话加mapping
  30078. return "".concat(Potree.settings.urls.prefix3, "/").concat(pointcloud.datasetData.mapping).concat(v3OrV4Str).concat(d);
  30079. }
  30080. return "".concat(Potree.settings.urls.prefix3).concat(v3OrV4Str).concat(d);
  30081. /*
  30082. if(Potree.settings.isLocal && !this.local2SrcFailed || useV4url){//新的地址 scene_view_data/场景码/images/tiles
  30083. if(pointcloud.datasetData.mapping && !Potree.settings.isLocal2){//非离线包的话加mapping
  30084. return `${Potree.settings.urls.prefix3}/${pointcloud.datasetData.mapping}/scene_view_data/${sceneNum}/images/${d}`
  30085. }else{
  30086. return `${Potree.settings.urls.prefix3}/scene_view_data/${sceneNum}/images/${d}`
  30087. }
  30088. }
  30089. return `${Potree.settings.urls.prefix3}/images/images${sceneNum}/${d}`
  30090. */
  30091. }
  30092. loadImage(e, t, i, n) {
  30093. //自己修改了ajax,把getImage改成了loadImg
  30094. http.loadImage(e, t).then(function (e) {
  30095. i(e);
  30096. }).fail(n);
  30097. }
  30098. }
  30099. TileDownloader.prototype.forceQueueTilesForPano = function () {
  30100. //根据条件开始加载tile
  30101. var e = [],
  30102. t = [];
  30103. return function (pano, size, dir, hFov, vFov, download) {
  30104. e.length = 0;
  30105. for (var u = this.getTileDownloadDescriptors(pano, size), d = 0; d < u.length; d++) {
  30106. var p = u[d];
  30107. p.status !== DownloadStatus$1.None && p.status !== DownloadStatus$1.Queued || e.push(p);
  30108. }
  30109. if (dir && e.length > 0) {
  30110. TilePrioritizer.sortPanoTiles(e, pano, dir); //按最佳方向排序e
  30111. t.length = 0;
  30112. TileUtils.matchingTilesInDirection(pano, size, dir, hFov, vFov, t); //得到在符合视野标准的集合t
  30113. for (var f = 0, g = function g(e) {
  30114. return e.face === m.face && e.faceTileIndex === m.faceTileIndex;
  30115. }; f < e.length;) {
  30116. //过滤掉不符合角度要求的
  30117. var m = e[f],
  30118. v = t.findIndex(g);
  30119. v < 0 ? e.splice(f, 1) : f++;
  30120. }
  30121. }
  30122. for (var A = 0; A < e.length; A++) {
  30123. this.forceQueue.push(e[A]); //装载
  30124. }
  30125. /* if(e.length){
  30126. console.log(e)
  30127. } */
  30128. this.setStatusForAllDescriptors(this.forceQueue, DownloadStatus$1.ForceQueued);
  30129. this.clearFromQueue(this.priorityQueue, DownloadStatus$1.ForceQueued, !1);
  30130. download && this.processQueueForDownloading(this.forceQueue, !0);
  30131. };
  30132. }();
  30133. TileDownloader.prototype.cleanupActiveDownloads = function () {
  30134. var e = [];
  30135. return function () {
  30136. e.length = 0;
  30137. for (var t = 0; t < this.activeDownloads.length; t++) {
  30138. var i = this.activeDownloads[t];
  30139. i.status !== DownloadStatus$1.Downloaded && i.status !== DownloadStatus$1.Failed && e.push(i);
  30140. }
  30141. this.activeDownloads.length = 0, this.activeDownloads.push.apply(this.activeDownloads, e);
  30142. };
  30143. }();
  30144. TileDownloader.prototype.getTileUrl = function () {
  30145. var e = {
  30146. 256: "256",
  30147. 512: "512",
  30148. 1024: "1k",
  30149. 2048: "2k",
  30150. 4096: "4k"
  30151. },
  30152. t = {
  30153. face: -1,
  30154. faceTileIndex: -1,
  30155. tileX: -1,
  30156. tileY: -1
  30157. };
  30158. return function () {
  30159. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  30160. var id = o.pano.originID,
  30161. ////////
  30162. panoSize = o.panoSize,
  30163. tileSize = o.tileSize,
  30164. tileIndex = o.tileIndex,
  30165. sceneCode = o.pano.pointcloud.sceneCode,
  30166. useV4url = Potree.settings.useV4url && o.pano.pointcloud.datasetData.sceneVersion == 'V4'; //v4的全景图等路径不一样
  30167. var metadata = {
  30168. sceneScheme: 10
  30169. };
  30170. TileUtils.getTileLocation(panoSize, tileIndex, t);
  30171. var s = Math.floor(panoSize / tileSize),
  30172. l = s * s,
  30173. h = Math.floor(tileIndex / l),
  30174. u = "",
  30175. d = '',
  30176. g = '';
  30177. if (Potree.settings.tileOriginUrl) {
  30178. //原始规则
  30179. //1 === config.tiling.customCompression && (u = "_" + config.tiling["q" + e[panoSize]]);
  30180. //1 === o.tiling.customCompression && (u = "_" + o.tiling["q" + e[n]]);
  30181. d = "tiles/" + id + "/" + e[panoSize] + u + "_face" + h + "_" + t.tileX + "_" + t.tileY + ".jpg";
  30182. d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud);
  30183. g = "?";
  30184. } else {
  30185. //阿里云oss的规则 if (metadata.sceneScheme == 10)
  30186. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=';
  30187. if (e[panoSize] == '512') {
  30188. d += 'image/resize,h_512';
  30189. } else {
  30190. //4k的图,移动端是1k,pc端是2k,放大才是4k
  30191. if (e[panoSize] == '1k' || e[panoSize] == '2k') {
  30192. //https://4dkk.4dage.com/images/imagesx4iqYDG3/tiles/4k/122_skybox0.jpg?x-oss-process=image/resize,m_lfit,w_1024/crop,w_512,h_512,x_511,y_0
  30193. d += 'image/resize,m_lfit,w_' + panoSize + '/crop,w_512,h_512,';
  30194. } else {
  30195. d = 'tiles/4k/' + id + '_skybox' + h + '.jpg?x-oss-process=image/crop,w_512,h_512,';
  30196. }
  30197. //起始位置
  30198. if (t.tileX == 0) {
  30199. d += 'x_0,';
  30200. } else {
  30201. d += 'x_' + 512 * t.tileX /* - 1 */ + ',';
  30202. }
  30203. if (t.tileY == 0) {
  30204. d += 'y_0';
  30205. } else {
  30206. d += 'y_' + 512 * t.tileY /* - 1 */;
  30207. }
  30208. }
  30209. d = this.getTiles(d, sceneCode, useV4url, o.pano.pointcloud);
  30210. g = "&";
  30211. }
  30212. //Potree.settings.panoVersion = 4
  30213. d += g + (Potree.settings.panoVersion ? 'version=' + Potree.settings.panoVersion : 'time=' + o.pano.pointcloud.timeStamp); //加后缀
  30214. return d;
  30215. /* 4dkk
  30216. getViewImagesURL(url) {
  30217. if (url.indexOf('&_=') !== -1) {
  30218. return url
  30219. }
  30220. let version = url.indexOf('/panorama/') !== -1 ? this.linkVersion : this.imageVersion
  30221. if (url.indexOf('?') !== -1) {
  30222. return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}&_=${version}`
  30223. }
  30224. return this.$app.config.resource + `scene_view_data/${this.num}/images/${url}?_=${version}`
  30225. }
  30226. /**
  30227. */
  30228. };
  30229. }();
  30230. TileDownloader.tilegen = true;
  30231. TileDownloader.IDLE_REFRESH_DELAY = 500;
  30232. TileDownloader.ACTIVE_REFRESH_DELAY = 16;
  30233. TileDownloader.DOWNLOAD_RETRIES = 4;
  30234. function Node$1(e, t) {
  30235. this.tree = e,
  30236. //所属树(TileTree)
  30237. this.parent = t, this.children = [], this.id = ++u$1;
  30238. }
  30239. function o(e, t, i, r, a, s, l, h) {
  30240. if (e) {
  30241. l = l || TileTree.TraversalType.PreOrder;
  30242. var u = r * c + i;
  30243. if (l === TileTree.TraversalType.PreOrder && (a && a(e, t, u, i, r), s && s.push(e)), e.children && 0 !== e.children.length) {
  30244. for (var d = r * c, p = i * c, f = 0; f < c; f++) for (var g = 0; g < c; g++) o(e.children[g * c + f], t + 1, p + f, d + g, a, s, l, h);
  30245. l === TileTree.TraversalType.PostOrder && (a && a(e, t, u, i, r), s && s.push(e));
  30246. }
  30247. }
  30248. }
  30249. function Plant(seed) {
  30250. seed.root = Branch(seed, null, 0);
  30251. }
  30252. function Branch(seed, parent, level) {
  30253. if (level > seed.levels) return null;
  30254. var node = new Node$1(seed, parent);
  30255. seed.allNodes.push(node);
  30256. for (var o = 0; o < h$1; o++) node.children[o] = Branch(seed, node, level + 1);
  30257. return node;
  30258. }
  30259. function l(parent, t, level, n, r) {
  30260. if (!parent) return null;
  30261. if (0 === level) return parent;
  30262. if (!parent.children || 0 === parent.children.length) return null;
  30263. var o = Math.pow(c, level),
  30264. a = o / c,
  30265. s = n % a,
  30266. h = r % a,
  30267. u = Math.floor(r / a),
  30268. d = Math.floor(n / a),
  30269. p = u * c + d,
  30270. f = parent.children[p];
  30271. return l(f, t + 1, level - 1, s, h);
  30272. }
  30273. /* cube每个面都有一个分层树 用于代表瓦片图的细分?
  30274. 树4096的分为三层,每层有4个子节点。(最后一层的四个子节点都是null)
  30275. */
  30276. var c = 2,
  30277. h$1 = c * c; //4个子节点
  30278. var u$1 = 0;
  30279. class TileTree {
  30280. constructor(e, t) {
  30281. this.levels = t, this.tileSize = e, this.root = null, this.allNodes = [], Plant(this);
  30282. }
  30283. getSubNode(e, t, i) {
  30284. (!t || e < this.tileSize) && (t = 0), (!i || e < this.tileSize) && (i = 0), e < this.tileSize && (e = this.tileSize);
  30285. var level = TileTree.getLevelCountForSize(this.tileSize, e),
  30286. o = l(this.root, 0, level, t, i);
  30287. return o;
  30288. }
  30289. breadthFirst(e) {
  30290. //广度优先搜索
  30291. e = e || {};
  30292. var t = !!e.nullLevelEnd,
  30293. i = e.maxLevel,
  30294. n = e.minLevel,
  30295. r = e.callback,
  30296. o = e.saveVisited,
  30297. a = [],
  30298. s = {},
  30299. l = 0,
  30300. c = 0;
  30301. for (a.push(this.root), a.push(s); a.length > 0 && !(i && l > i);) {
  30302. var h = a.shift();
  30303. if (h === s) (!n || l >= n) && (r && t && r(null), o && t && o.push(null)), a.length > 0 && a.push(s), l++, c = 0;else {
  30304. if (h.children) for (var u = 0; u < h.children.length; u++) {
  30305. var d = h.children[u];
  30306. d && a.push(h.children[u]);
  30307. }
  30308. var p = this.getFaceIndexFromNode(h);
  30309. (!n || l >= n) && (r && r(h, l, p), o && o.push(h)), c++;
  30310. }
  30311. }
  30312. }
  30313. getFaceIndexFromNode(e) {
  30314. if (!e) return -1;
  30315. for (var t = 1, i = e, n = 0, r = 0;;) {
  30316. var o = i.parent;
  30317. if (!o) break;
  30318. for (var a = -1, s = 0; s < o.children.length; s++) o.children[s] === i && (a = s);
  30319. var l = a % c,
  30320. h = Math.floor(a / c);
  30321. n = l * t + n, r = h * t + r, t *= c, i = o;
  30322. }
  30323. return r * t + n;
  30324. }
  30325. depthFirst(e, t, i) {
  30326. o(this.root, 0, 0, 0, e, t, i, this.tileSize);
  30327. }
  30328. }
  30329. TileTree.TraversalType = Object.freeze({
  30330. PreOrder: 0,
  30331. PostOrder: 1
  30332. });
  30333. TileTree.getLevelCountForSize = function (tileSize, size) {
  30334. //512->0 2024->1
  30335. var i = 0;
  30336. for (size < tileSize && (size = tileSize);;) {
  30337. if (size /= c, size < tileSize) break;
  30338. i++;
  30339. }
  30340. return i;
  30341. };
  30342. TileTree.getSizeForLevel = function (e, t) {
  30343. return Math.pow(c, t) * e;
  30344. };
  30345. /* let sid = 0
  30346. let getName = ()=>{
  30347. return sid ++
  30348. } */
  30349. class BasicMaterial extends ShaderMaterial {
  30350. constructor() {
  30351. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  30352. super(Object.assign({}, {
  30353. uniforms: {
  30354. color: {
  30355. type: 'v3',
  30356. value: o.color || new Color("#FFF")
  30357. },
  30358. map: {
  30359. type: 't',
  30360. value: o.map
  30361. },
  30362. opacity: {
  30363. type: 'f',
  30364. value: o.opacity == void 0 ? 1 : o.opacity
  30365. }
  30366. },
  30367. vertexShader: Shaders['basicTextured.vs'],
  30368. fragmentShader: Shaders['basicTextured.fs'],
  30369. defines: {
  30370. HasColor: ''
  30371. }
  30372. }, o));
  30373. //this.name111 = getName()
  30374. }
  30375. copy(source) {
  30376. super.copy(source);
  30377. //console.log('copy', source.name111, this.name111, !!source.map )
  30378. this.map = source.map;
  30379. return this;
  30380. }
  30381. set opacity(o) {
  30382. this.uniforms && (this.uniforms.opacity.value = o);
  30383. }
  30384. get opacity() {
  30385. return this.uniforms.opacity.value;
  30386. }
  30387. set map(o) {
  30388. this.uniforms.map.value = o;
  30389. if (o) {
  30390. this.defines.HasMap = '';
  30391. } else {
  30392. delete this.defines.HasMap;
  30393. }
  30394. //可能需要needsUpdate
  30395. //console.log('hasMap', !!o, this.name111 )
  30396. }
  30397. get map() {
  30398. return this.uniforms.map.value;
  30399. }
  30400. }
  30401. var {
  30402. PanoSizeClass: PanoSizeClass$2,
  30403. PanoRendererEvents: PanoRendererEvents$1,
  30404. Vectors,
  30405. SceneRendererEvents,
  30406. TileDownloaderEvents: TileDownloaderEvents$1,
  30407. GLCubeFaces: GLCubeFaces$2
  30408. } = Potree.defines;
  30409. function createDescriptor() {
  30410. var e = {
  30411. renderTarget: null,
  30412. inUse: !1,
  30413. size: -1,
  30414. pano: null
  30415. };
  30416. return e;
  30417. }
  30418. /* function upload() {
  30419. if (!this.uploadIntervalCancelled) {
  30420. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  30421. b = !0
  30422. let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡)
  30423. this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame)
  30424. let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔
  30425. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新
  30426. } else {
  30427. this.refreshUploadInterval(this.uploadIntervalDelay)
  30428. }
  30429. }
  30430. } */
  30431. var b = !1,
  30432. w = config$1.tiling.uploadIntervalDelay,
  30433. _ = config$1.tiling.initialIntervalDelay,
  30434. T = config$1.tiling.maxNonBaseUploadsPerFrame,
  30435. //2 size>512的每次只upload这么多个
  30436. x$1 = config$1.tiling.maxBaseUploadsPerFrame,
  30437. //6
  30438. S = {
  30439. Base: 0,
  30440. Remaining: 1
  30441. }; /* ,
  30442. M = []; */
  30443. class PanoRenderer extends EventDispatcher {
  30444. constructor(viewer, tileDownloader, qualityManager) {
  30445. super();
  30446. this.tileDirectory = {};
  30447. this.activeRenderTargetDescriptors = {};
  30448. this.activePanos = [];
  30449. this.panoLODDescriptors = {};
  30450. this.panoDescriptors = {};
  30451. this.tileTrees = {};
  30452. this.forceQueue = [];
  30453. this.uploadQueues = {};
  30454. this.uploadInterval = null;
  30455. this.uploadIntervalCancelled = true; //!1;
  30456. this.usingTileOverlay = !1;
  30457. this.overlayTilesLoaded = !1;
  30458. this.overlayTileBase = null;
  30459. this.overlayTilesBasic = {};
  30460. this.overlayTilesEnhanced = {};
  30461. this.zoomRenderTarget = null; //用于缩放的rendertarget
  30462. this.zoomPano = null;
  30463. this.zoomingActive = !1;
  30464. this.zoomPanoId = null;
  30465. this.zoomPanoRenderingDisabled = !1;
  30466. this.direction = []; //new THREE.Vector3;
  30467. this.maxBaseUploadsPerFrame = x$1;
  30468. this.maxNonBaseUploadsPerFrame = T;
  30469. this.M = []; //move M to here 似乎列表里会有两个
  30470. this.viewer = viewer;
  30471. this.tileDownloader = tileDownloader;
  30472. this.qualityManager = qualityManager;
  30473. this.initTime = performance.now();
  30474. this.bindEvents();
  30475. }
  30476. getActivePanoTextures(e) {
  30477. e = e || [];
  30478. for (var t = 0; t < M.length; t++) {
  30479. var i = M[t];
  30480. i.renderTarget && i.renderTarget.texture && e.push(i.renderTarget.texture);
  30481. }
  30482. }
  30483. hasQueuedTiles() {
  30484. var e = this.peekNextFromUploadQueue();
  30485. return null !== e && void 0 !== e;
  30486. }
  30487. getActiveRenderTargetDescriptor(e) {
  30488. return this.activeRenderTargetDescriptors[e];
  30489. }
  30490. setActiveRenderTargetDescriptor(e, t) {
  30491. this.activeRenderTargetDescriptors[e] = t;
  30492. }
  30493. bindEvents() {
  30494. this.tileDownloader.addEventListener(TileDownloaderEvents$1.TileDownloadSuccess, this.onTileDownloaded.bind(this));
  30495. }
  30496. enableUltraHighQualityMode(e) {
  30497. if (config$1.tileClass == "2k" || config$1.tileClass == "1k") return this.enableHighQuality(e); //xzw add 濡傛灉鏈€澶氬彧瑕?k鐨勮瘽
  30498. if (!this.qualityManager.ultraHighQualityModeEnabled()) {
  30499. var t = this.qualityManager.getPanoSize(PanoSizeClass$2.ULTRAHIGH);
  30500. this.tileDownloader.testDownload(t, TileUtils.TILE_SIZE, function (t) {
  30501. t && (this.qualityManager.enableUltraHighQualityMode(), this.setupZoomRenderTarget(), e());
  30502. }.bind(this));
  30503. }
  30504. }
  30505. activateTiledPano(pano, size, i) {
  30506. i && this.clearAllQueuedUploads();
  30507. for (var n = 0; n < TileUtils.FACES_PER_PANO; n++) this.initTileTree(pano.id, n, this.qualityManager.getMaxPossiblePanoSize()); //得到this.tileTrees[pano.id],arr[6]
  30508. this.linkAllTilesAndNodes(pano);
  30509. var r = this.getActiveRenderTargetDescriptor(pano.id),
  30510. l = size;
  30511. l > this.qualityManager.getMaxNavPanoSize() && (l = this.qualityManager.getMaxNavPanoSize());
  30512. if (!r || l !== r.size) {
  30513. r && this.deactiveDescripor(r.renderTarget);
  30514. r = this.activeDescripor(l);
  30515. if (!r) {
  30516. var ren = this.initTiledPano(l, Potree.settings.disableAATarget ? false : !browser.isMobile()); //有的老设备如果抗锯齿打开场景时要多花五秒
  30517. r = this.initDescriptor(ren.width);
  30518. r.renderTarget = ren;
  30519. }
  30520. r.pano = pano;
  30521. this.resetPanoDescriptor(pano.id);
  30522. this.resetPanoLODDescriptors(pano.id);
  30523. this.resetRenderStatus(pano.id, !0, !0);
  30524. }
  30525. this.setActiveRenderTargetDescriptor(pano.id, r);
  30526. var h = i ? 0 : 1;
  30527. this.updateActivePanos(pano, h);
  30528. //console.log(`index:${this.viewer.index} ${r.renderTarget.texture.id} ${pano.id}`)
  30529. return r.renderTarget;
  30530. }
  30531. deactivateTiledPano(pano) {
  30532. var t = this.getActiveRenderTargetDescriptor(pano.id);
  30533. if (this.isRenderTargetDescriptorValid(t)) {
  30534. this.deactiveDescripor(t.renderTarget);
  30535. this.setActiveRenderTargetDescriptor(pano.id, null);
  30536. }
  30537. var i = this.getUploadQueueForPano(pano.id);
  30538. this.clearUploadQueue(i);
  30539. this.updateActivePanos();
  30540. viewer.cancelLoad(pano); //add
  30541. }
  30542. getActivePanoCount() {
  30543. return this.activePanos.length;
  30544. }
  30545. resetRenderStatus(e, t, i, n) {
  30546. var r = null;
  30547. n && (r = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, n) + 1);
  30548. for (var o = function o(e, n, r, _o) {
  30549. i && (n.tile.zoomUploaded = !1), t && (n.tile.uploaded = !1);
  30550. }, a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  30551. var s = this.getTileTree(e, a);
  30552. s.breadthFirst({
  30553. callback: o.bind(this, a),
  30554. minLevel: r
  30555. });
  30556. }
  30557. }
  30558. copyBaseRenderStatusToZoomed(e) {
  30559. for (var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, this.qualityManager.getMaxNavPanoSize()), i = function i(e, t, _i, n) {
  30560. t.tile.zoomUploaded = t.tile.uploaded, t.zoomCovered = t.covered;
  30561. }, n = 0; n < TileUtils.FACES_PER_PANO; n++) {
  30562. var r = this.getTileTree(e, n);
  30563. r.breadthFirst({
  30564. callback: i.bind(this, n),
  30565. maxLevel: t
  30566. });
  30567. }
  30568. }
  30569. isRenderTargetDescriptorValid(e) {
  30570. return e && e.renderTarget;
  30571. }
  30572. isPanoActive(e) {
  30573. var t = this.getActiveRenderTargetDescriptor(e);
  30574. return this.isRenderTargetDescriptorValid(t);
  30575. }
  30576. isPanoZoomed(e) {
  30577. return this.zoomingActive && this.zoomPanoId === e;
  30578. }
  30579. initTileTree(e, t, i) {
  30580. var n = this.tileTrees[e];
  30581. n || (n = [], this.tileTrees[e] = n);
  30582. var r = n[t];
  30583. if (!r) {
  30584. var o = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i);
  30585. r = new TileTree(TileUtils.TILE_SIZE, o), n[t] = r;
  30586. }
  30587. }
  30588. getTileTree(e, t) {
  30589. var i = this.tileTrees[e];
  30590. if (!i) console.error("PanoRenderer.getTileTree() -> Tree array not yet initialized!");
  30591. var n = i[t];
  30592. if (!n) console.error("PanoRenderer.getTileTree() -> Tree not yet initialized!");
  30593. return n;
  30594. }
  30595. /*
  30596. * 创建tile的renderTarget, 包括pano.tiledPanoRenderTarget和zoomRenderTarget
  30597. * @param {number} size 当前的panoSize,每个面的分辨率
  30598. */
  30599. initTiledPano(size, ifNormalFilter) {
  30600. //创建 RenderTargetCube
  30601. var renderer = this.viewer.renderer;
  30602. var renderTarget, texture;
  30603. renderTarget = new WebGLCubeRenderTarget(size, {
  30604. //THREE.WebGLRenderTargetCube(size, size, {
  30605. stencilBuffer: !1
  30606. });
  30607. texture = new CubeTexture([]);
  30608. texture.image = [null, null, null, null, null, null];
  30609. texture.flipY = !0, texture.format = RGBAFormat;
  30610. ifNormalFilter ? (texture.generateMipmaps = !0, texture.magFilter = LinearFilter, texture.minFilter = LinearMipMapLinearFilter) : (texture.generateMipmaps = !1, texture.magFilter = LinearFilter,
  30611. //LinearFilter更清晰,但锯齿噪点严重,相当于锐化,其实失真了。对于条纹状的画面移动镜头时锯齿明显 眩晕
  30612. texture.minFilter = LinearFilter);
  30613. //平时还是直接用LinearMipMapLinearFilter,其实并非不清晰,只是没有加锐化,像加了层柔光和抗锯齿,观感更好。放大后使用LinearFilter
  30614. // 如果抗锯齿的话,采用mipmap,会增加一倍的存储消耗。原版本都是不抗锯齿的。但是抗锯齿效果更柔和
  30615. renderTarget.texture = texture; //居然漏了一句,2022.10.9补
  30616. renderer.setRenderTarget(renderTarget);
  30617. renderer.setRenderTarget(null);
  30618. var o = renderer.properties.get(texture);
  30619. o.__image__webglTextureCube = o.__webglTexture;
  30620. //window.tex[r.id] = {texture:r, index:this.viewer.index }
  30621. return renderTarget;
  30622. }
  30623. getUploadQueueForPano(e) {
  30624. var t = this.uploadQueues[e];
  30625. return t || (t = [], this.uploadQueues[e] = t), t;
  30626. }
  30627. isTileUploaded(e) {
  30628. return this.isPanoZoomed(e.panoId) ? e.zoomUploaded : e.uploaded;
  30629. }
  30630. setUploaded(e, t) {
  30631. this.isPanoZoomed(e.panoId) ? e.zoomUploaded = t : e.uploaded = t;
  30632. }
  30633. queueTileUpload(e, t, i) {
  30634. var n = this.getActiveRenderTargetDescriptor(e.panoId);
  30635. if (this.isRenderTargetDescriptorValid(n) && e.downloaded && !this.isTileUploaded(e) && (!e.uploadQueued || i) && (!(e.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive)) {
  30636. var r = this.getUploadQueueForPano(e.panoId);
  30637. //console.log(window.sceneName, 'queueTileUpload: ', e.panoId, e.tileIndex, i)
  30638. if (i) {
  30639. //console.log('512下载好了直接uploadTile')
  30640. this.uploadTile(e, !1); //提交后该tile直接loaded了,无需等待
  30641. } else {
  30642. if (this.shoulPushToFrontOfQueue(e)) {
  30643. //如果是512的优先
  30644. this.forceQueue.push(e);
  30645. } else {
  30646. if (t && this.direction) {
  30647. TilePrioritizer.insertSortedPanoTile(r, e, n.pano, this.direction);
  30648. } else r.push(e);
  30649. }
  30650. e.uploadQueued = !0;
  30651. this.uploadInterval || this.uploadIntervalCancelled || this.refreshUploadInterval(0);
  30652. }
  30653. }
  30654. }
  30655. shoulPushToFrontOfQueue(e) {
  30656. return 0 === TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize);
  30657. }
  30658. getTopUploadQueue() {
  30659. for (var e = null, t = null, i = S.Base; i <= S.Remaining; i++) for (var n = 0; n < this.activePanos.length; n++) if (e = this.activePanos[n], t = this.getUploadQueueForPano(e.id), t.length > 0) switch (i) {
  30660. case S.Base:
  30661. if (0 === t[0].level) return t;
  30662. break;
  30663. case S.Remaining:
  30664. return t;
  30665. }
  30666. return null;
  30667. }
  30668. peekNextFromUploadQueue() {
  30669. if (this.forceQueue.length > 0) return this.forceQueue[0];
  30670. var e = this.getTopUploadQueue();
  30671. return e && e.length > 0 ? e[0] : null;
  30672. }
  30673. clearAllQueuedUploads() {
  30674. this.clearAllUploadQueues(null, 0);
  30675. }
  30676. clearAllQueuedUploadsForPano(e) {
  30677. this.clearAllUploadQueues(e, 0);
  30678. }
  30679. clearAllUploadQueues(e, t) {
  30680. if (e) this.clearUploadQueue(this.getUploadQueueForPano(e), t), this.clearUploadQueue(this.forceQueue, t, e);else {
  30681. for (var i = 0; i < this.activePanos.length; i++) {
  30682. var n = this.activePanos[i];
  30683. this.clearUploadQueue(this.getUploadQueueForPano(n.id), t);
  30684. }
  30685. this.clearUploadQueue(this.forceQueue, t);
  30686. }
  30687. }
  30688. clearUploadQueue(e, t, i) {
  30689. void 0 !== t && null !== t || (t = 0);
  30690. for (var n = 0; n < e.length;) {
  30691. var r = e[n];
  30692. (!i || i && i === r.tile.panoId) && r.level >= t ? (r.uploadQueued = !1, e.splice(n, 1)) : n++;
  30693. }
  30694. //若报错, r.tile.panoId改为 r.panoId
  30695. }
  30696. updateUploadQueue(maxNPF, maxPF /* e, t */) {
  30697. //参数是 maxNonBaseUploadsPerFrame and maxBaseUploadsPerFrame, 优先上传512
  30698. //maxNPF || (maxNPF = 1);
  30699. for (var i = 0, n = 0;;) {
  30700. //let old = this.forceQueue.slice(0)
  30701. if (n >= maxPF || i >= maxNPF) break;
  30702. var r = this.getNextFromUploadQueue();
  30703. if (!r) break;
  30704. //r.panoSize <2048 && console.log('panoId', r.panoId, 'panoSize', r.panoSize , old)
  30705. 0 !== r.level ? i++ : n++;
  30706. if (!(r.panoSize > this.qualityManager.getMaxNavPanoSize()) || this.zoomingActive) {
  30707. var o = this.getActiveRenderTargetDescriptor(r.panoId);
  30708. this.isRenderTargetDescriptorValid(o) && this.uploadTile(r, r.forceUpload);
  30709. }
  30710. }
  30711. }
  30712. updateDirection(e) {
  30713. if (e = e || this.direction) {
  30714. this.direction = e;
  30715. for (var t = 0; t < this.activePanos.length; t++) {
  30716. var i = this.activePanos[t],
  30717. n = this.getUploadQueueForPano(i.id);
  30718. TilePrioritizer.sortPanoTiles(n, i, this.direction);
  30719. }
  30720. }
  30721. }
  30722. anyUploaded(e) {
  30723. if (!e) return !1;
  30724. if (e.tile && this.isTileUploaded(e.tile)) return !0;
  30725. if (e.children) for (var t = 0; t < e.children.length; t++) {
  30726. var i = e.children[t];
  30727. if (this.anyUploaded(i)) return !0;
  30728. }
  30729. return !1;
  30730. }
  30731. setNodeCovered(e, t) {
  30732. this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered = t : e.covered = t;
  30733. }
  30734. isNodeCovered(e) {
  30735. return !!e && (this.isPanoZoomed(e.tile.panoId) ? e.zoomCovered : e.covered);
  30736. }
  30737. addCoverageForNode(e) {
  30738. if (this.setNodeCovered(e, !0), e.parent && e.covered) {
  30739. var t = e.parent;
  30740. this.nodeSubcovered(t) && this.addCoverageForNode(t, !0);
  30741. }
  30742. }
  30743. calcFullCoverage(e) {
  30744. var t = !1;
  30745. if (e.children) for (var i = 0; i < e.children.length; i++) {
  30746. var n = e.children[i];
  30747. t = t || this.calcFullCoverage(n);
  30748. }
  30749. e.covered = e.tile.uploaded || t;
  30750. }
  30751. nodeSubcovered(e) {
  30752. if (!e.children) return !1;
  30753. for (var t = 0; t < e.children.length; t++) if (!e.children[t] || !this.isNodeCovered(e.children[t])) return !1;
  30754. return !0;
  30755. }
  30756. resetPanoDescriptor(e) {
  30757. this.getPanoDescriptor(e);
  30758. }
  30759. getPanoDescriptor(e) {
  30760. var t = this.panoDescriptors[e];
  30761. return t || (t = {}, this.panoDescriptors[e] = t), t;
  30762. }
  30763. resetPanoLODDescriptors(e) {
  30764. var t = this.getPanoLODDescriptors(e);
  30765. for (var i in t) if (t.hasOwnProperty(i)) {
  30766. var n = t[i];
  30767. n.uploadCount = 0, n.uploadAttempts = 0;
  30768. n.uploaded = [];
  30769. }
  30770. }
  30771. getPanoLODDescriptor(e, t) {
  30772. var i = this.getPanoLODDescriptors(e),
  30773. n = i[t];
  30774. return n || (n = {
  30775. uploadCount: 0,
  30776. uploadAttempts: 0,
  30777. uploaded: [] //add
  30778. }, i[t] = n), n;
  30779. }
  30780. getPanoLODDescriptors(e) {
  30781. var t = this.panoLODDescriptors[e];
  30782. return t || (t = {}, this.panoLODDescriptors[e] = t), t;
  30783. }
  30784. onTileDownloaded(o) {
  30785. var e = o.desc;
  30786. var t = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, e.panoSize),
  30787. i = this.getTileDirectoryEntry(e.panoId, e.face, t, e.faceTileIndex);
  30788. i.downloaded = !0;
  30789. i.image = e.image;
  30790. i.panoSize = e.panoSize;
  30791. i.tileX = e.tileX;
  30792. i.tileY = e.tileY;
  30793. i.totalTiles = e.totalTiles;
  30794. i.tileIndex = e.tileIndex;
  30795. i.faceTileIndex = e.faceTileIndex;
  30796. i.face = e.face;
  30797. i.cubeFace = TileUtils.mapFaceToCubemapFace(e.face);
  30798. i.panoId = e.panoId;
  30799. i.tileSize = e.tileSize;
  30800. i.direction = new Vector3().copy(e.direction);
  30801. i.node = null;
  30802. i.level = TileTree.getLevelCountForSize(TileUtils.TILE_SIZE, i.panoSize);
  30803. if (this.isPanoActive(i.panoId)) {
  30804. var n = this.getTileTree(i.panoId, i.face);
  30805. var r = n.getSubNode(i.panoSize, i.tileX, i.tileY);
  30806. this.linkTileAndNode(i, r);
  30807. this.queueTileUpload(i, !0);
  30808. }
  30809. }
  30810. getTileDirectoryEntry(panoId, t, i, n) {
  30811. var r = this.tileDirectory[panoId];
  30812. r || (r = {}, this.tileDirectory[panoId] = r);
  30813. var o = 16384 * t + 1024 * i + n,
  30814. //t:4096级别
  30815. a = r[o];
  30816. return a || (a = {
  30817. downloaded: !1,
  30818. uploaded: !1,
  30819. zoomUploaded: !1
  30820. }, r[o] = a), a._key = panoId + ":" + t + ":" + i + ":" + n,
  30821. //panoId : face : level : faceTileIndex
  30822. a._tileKey = o, a;
  30823. }
  30824. setZoomingActive(active, pano, i) {
  30825. //设置当前正在zoom的pano
  30826. this.zoomPanoRenderingDisabled || active === this.zoomingActive && this.zoomPanoId === pano.id || (this.zoomingActive = active, this.zoomPanoId = pano.id, this.zoomingActive && (this.zoomPanoId !== pano.id || i) && this.updateZoomedPanoFromBase(pano));
  30827. }
  30828. updateZoomedPanoFromBase(pano) {
  30829. //因更换pano所以将pano的rendertarget渲染到panoRenderer的zoomRenderTarget上
  30830. if (!this.zoomPanoRenderingDisabled) {
  30831. var t = this.getActiveRenderTargetDescriptor(pano.id);
  30832. if (t && t.renderTarget) {
  30833. if (this.zoomRenderTarget) {
  30834. var i = Math.min(this.qualityManager.maxRenderTargetSize, this.qualityManager.getMaxZoomPanoSize()),
  30835. //change
  30836. n = t.renderTarget,
  30837. r = t.size;
  30838. this.copyCubeMap(n.texture, this.zoomRenderTarget, r, r, i, i);
  30839. }
  30840. this.copyBaseRenderStatusToZoomed(pano.id);
  30841. }
  30842. }
  30843. }
  30844. add(e) {
  30845. this.M.push(e);
  30846. }
  30847. initDescriptor(size) {
  30848. var t = createDescriptor();
  30849. t.inUse = !0;
  30850. t.size = size;
  30851. this.add(t);
  30852. return t;
  30853. }
  30854. activeDescripor(e) {
  30855. for (var t = 0; t < this.M.length; t++) {
  30856. var i = this.M[t];
  30857. if (!i.inUse && i.size === e) {
  30858. i.inUse = !0;
  30859. return i;
  30860. }
  30861. }
  30862. return null;
  30863. }
  30864. deactiveDescripor(e) {
  30865. for (var t = 0; t < this.M.length; t++) {
  30866. var i = this.M[t];
  30867. if (i.renderTarget === e) {
  30868. i.inUse = !1;
  30869. return !0;
  30870. }
  30871. }
  30872. return !1;
  30873. }
  30874. enableHighQuality(e) {
  30875. //xzw add 如果最多只要2k图的话enableUltraHighQualityMode替换成这个
  30876. if (!this.qualityManager.highQualityModeStarted) {
  30877. this.setupZoomRenderTarget();
  30878. e();
  30879. //this.qualityManager.updateHighResolutionSettings(e)////////?
  30880. this.qualityManager.highQualityModeStarted = true;
  30881. }
  30882. }
  30883. linkTileAndNode(e, t) {
  30884. t.tile = e, e.node = t;
  30885. }
  30886. linkAllTilesAndNodes(e) {
  30887. var t = function t(_t, i, n, r, o) {
  30888. var a = this.getTileDirectoryEntry(e.id, i, r, o);
  30889. this.linkTileAndNode(a, n);
  30890. };
  30891. for (var i = 0; i < TileUtils.FACES_PER_PANO; i++) {
  30892. var n = this.getTileTree(e.id, i);
  30893. n.breadthFirst({
  30894. callback: t.bind(this, n, i)
  30895. });
  30896. }
  30897. }
  30898. //--------------sceneRenderer
  30899. initSizedTexture2D(e, t, i) {
  30900. var renderer = this.viewer.renderer,
  30901. o = renderer.getContext(),
  30902. a = renderer.state,
  30903. s = new Texture(null);
  30904. s.flipY = !1, i !== !0 && (i = !1), s.generateMipmaps = i;
  30905. var l = renderer.paramThreeToGL(s.format),
  30906. c = renderer.paramThreeToGL(s.type),
  30907. h = renderer.properties.get(s),
  30908. u = o.createTexture();
  30909. a.bindTexture(o.TEXTURE_2D, u), o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL, s.flipY), o.texImage2D(o.TEXTURE_2D, 0, l, e, e, 0, l, c, null), s.wrapS = t, s.wrapT = t;
  30910. var d = renderer.paramThreeToGL(t);
  30911. return o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_S, d), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_WRAP_T, d), i ? (s.magFilter = LinearFilter, s.minFilter = LinearMipMapLinearFilter, o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR_MIPMAP_NEAREST), o.generateMipmap(o.TEXTURE_2D)) : (s.magFilter = LinearFilter, s.minFilter = LinearFilter, o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MAG_FILTER, o.LINEAR), o.texParameteri(o.TEXTURE_2D, o.TEXTURE_MIN_FILTER, o.LINEAR)), a.bindTexture(o.TEXTURE_2D, null), h.__webglTexture = u, s;
  30912. }
  30913. deallocateCubeTexture(e) {
  30914. var t = this.viewer.renderer,
  30915. i = t.getContext(),
  30916. renderer = t.properties.get(e);
  30917. i.deleteTexture(renderer.__image__webglTextureCube);
  30918. }
  30919. uploadTexture2D(img, tex, startX, startY, width, height) {
  30920. var renderer = this.viewer.renderer,
  30921. gl = renderer.getContext(),
  30922. webglState = renderer.state,
  30923. c = renderer.properties.get(tex);
  30924. webglState.bindTexture(gl.TEXTURE_2D, c.__webglTexture), gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, tex.flipY), gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, tex.premultiplyAlpha), gl.pixelStorei(gl.UNPACK_ALIGNMENT, tex.unpackAlignment), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, renderer.paramThreeToGL(tex.wrapS)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, renderer.paramThreeToGL(tex.wrapT)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, renderer.paramThreeToGL(tex.magFilter)), gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, renderer.paramThreeToGL(tex.minFilter)), gl.texSubImage2D(gl.TEXTURE_2D, 0, startX, startY, gl.RGBA, gl.UNSIGNED_BYTE, img), tex.generateMipmaps && gl.generateMipmap(gl.TEXTURE_2D), webglState.bindTexture(gl.TEXTURE_2D, null);
  30925. }
  30926. getCubeOrientationForCubeFace(e, t) {
  30927. switch (e) {
  30928. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  30929. t.set(0, -Math.PI / 2, 0);
  30930. break;
  30931. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  30932. t.set(0, Math.PI / 2, 0);
  30933. break;
  30934. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  30935. t.set(Math.PI / 2, Math.PI, 0);
  30936. break;
  30937. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  30938. t.set(-Math.PI / 2, Math.PI, 0);
  30939. break;
  30940. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  30941. t.set(0, -Math.PI, 0);
  30942. break;
  30943. case GLCubeFaces$2.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  30944. t.set(0, 0, 0);
  30945. }
  30946. }
  30947. //dispose所有cubeRenderTarget
  30948. disposeIdelTargets() {
  30949. var disposeCount = 0;
  30950. for (var t = 0; t < this.M.length; t++) {
  30951. var i = this.M[t];
  30952. if (!i.inUse) {
  30953. disposeCount++;
  30954. i.renderTarget.dispose();
  30955. }
  30956. }
  30957. //console.log('disposeIdelTargets ', disposeCount, 'of', this.M.length)
  30958. }
  30959. }
  30960. PanoRenderer.prototype.setupZoomRenderTarget = function () {
  30961. var targets = {};
  30962. return function () {
  30963. if (this.qualityManager.maxRenderTargetSize == 2048 && this.qualityManager.getMaxNavPanoSize() == 2048) return; //不使用zoomTarget 直接用pano的tiledPanoRenderTarget,防崩溃
  30964. if (this.qualityManager.getMaxZoomPanoSize() >= this.qualityManager.getMaxNavPanoSize()) {
  30965. //部分手机2k时copyCubeMap会重载 , 所以如果没有超出当前分辨率,就不使用zoomRenderTarget。但在微信依旧会重载,只是优化了些,safari几乎不会。
  30966. if (this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize()) return;
  30967. var e = this.zoomRenderTarget;
  30968. var size = this.qualityManager.getMaxZoomPanoSize();
  30969. if (size > this.qualityManager.maxRenderTargetSize) {
  30970. return;
  30971. }
  30972. if (targets[size]) {
  30973. this.zoomRenderTarget = targets[size];
  30974. } else {
  30975. this.zoomRenderTarget = this.initTiledPano(size, false); //放大后不使用抗锯齿,否则消
  30976. targets[size] = this.zoomRenderTarget;
  30977. }
  30978. if (e) {
  30979. //将旧的zoomRenderTarget渲染到新zoomRenderTarget上
  30980. var t = e.width,
  30981. i = this.zoomRenderTarget.width;
  30982. this.copyCubeMap(e.texture, this.zoomRenderTarget, t, t, i, i), e.texture.dispose(), e.texture.loaded = !1, e.texture.version = 0, this.deallocateCubeTexture(e.texture), e.texture = null;
  30983. }
  30984. this.zoomPanoRenderingDisabled = !1;
  30985. } else this.zoomPanoRenderingDisabled = !0;
  30986. };
  30987. }();
  30988. PanoRenderer.prototype.updateActivePanos = function () {
  30989. var e = [];
  30990. return function (t, i) {
  30991. e.length = 0;
  30992. for (var n = 0; n < this.activePanos.length; n++) {
  30993. t && e.length === i && e.push(t);
  30994. var r = this.activePanos[n],
  30995. o = this.getActiveRenderTargetDescriptor(r.id);
  30996. t && r.id === t.id || !this.isRenderTargetDescriptorValid(o) || e.push(r);
  30997. }
  30998. t && i >= e.length && e.push(t), this.activePanos.length = 0, this.activePanos.push.apply(this.activePanos, e);
  30999. };
  31000. }();
  31001. PanoRenderer.prototype.renderPanoTiles = function () {
  31002. var e = [];
  31003. return function (panoId, i, n, r) {
  31004. this.zoomRenderTarget && this.zoomRenderTarget.width === this.qualityManager.getMaxZoomPanoSize() || this.zoomPanoRenderingDisabled || this.setupZoomRenderTarget(),
  31005. //如果ZoomRenderTarget大小需要变动就重新创建
  31006. i = i || this.direction || Vectors.FORWARD; // [{1:Vectors.FORWARD}]?
  31007. var o = this.getActiveRenderTargetDescriptor(panoId);
  31008. if (!this.isRenderTargetDescriptorValid(o)) console.error("PanoRenderer.renderPanoTiles() -> Cannot render to a pano that is not activated.");
  31009. for (var a = 0; a < TileUtils.FACES_PER_PANO; a++) {
  31010. var s = this.getTileTree(panoId, a);
  31011. e.length = 0;
  31012. s.breadthFirst({
  31013. //获取该面所有node 85个 = 1+4+16+64
  31014. saveVisited: e
  31015. });
  31016. for (var l = 0; l < e.length; l++) {
  31017. var c = e[l];
  31018. this.queueTileUpload(c.tile, !1, r || 0 === l && n); // 第0个是512的,会直接uploadTile
  31019. }
  31020. }
  31021. this.updateDirection(i);
  31022. };
  31023. }();
  31024. PanoRenderer.prototype.getNextFromUploadQueue = function () {
  31025. var e = function e(_e) {
  31026. var t = _e.shift();
  31027. return t.uploadQueued = !1, t;
  31028. };
  31029. return function () {
  31030. if (this.forceQueue.length > 0) return e(this.forceQueue);
  31031. var t = this.getTopUploadQueue();
  31032. return t && t.length > 0 ? e(t) : null;
  31033. };
  31034. }();
  31035. /* PanoRenderer.prototype.refreshUploadInterval = function () {
  31036. var e = null;
  31037. return function (t) {
  31038. this.uploadIntervalCancelled || (e || (e = upload.bind(this)),
  31039. null !== t && void 0 !== t || (t = w),
  31040. b || (t = _),
  31041. this.uploadInterval = window.setTimeout(e, t),
  31042. this.uploadIntervalDelay = t)
  31043. }
  31044. }()
  31045. PanoRenderer.prototype.update = function () {
  31046. var e = performance.now(),
  31047. t = 0;
  31048. return function () {
  31049. this.uploadIntervalCancelled = !0;
  31050. window.clearTimeout(this.uploadInterval);
  31051. this.uploadInterval = null;
  31052. var i = performance.now() - e;
  31053. //!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay || (this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame),
  31054. //e = performance.now()),
  31055. if (!(i > w || 0 === t) || !this.overlayTilesLoaded && this.usingTileOverlay) {} else {
  31056. this.updateUploadQueue(this.maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame);
  31057. e = performance.now();
  31058. }
  31059. t++;
  31060. }
  31061. }() */
  31062. PanoRenderer.prototype.update = function () {
  31063. //this.uploadIntervalCancelled = true ; //不使用setTimeout,而是在sceneRenderer每帧都update
  31064. if (viewer.images360.latestRequestMode == 'showPanos') {
  31065. var maxNonBaseUploadsPerFrame = viewer.lastFrameChanged ? Common.getBestCount('maxStandard', 0, 2, 1, 10 /* ,true */) : 2; // 这是每帧uploadTile非512的瓦片tex的数量。 手机在前进时可能会总是0,直到到漫游点后为2
  31066. var maxBaseUploadsPerFrame = viewer.lastFrameChanged ? Common.getBestCount('maxBase', 1, 6, 1, 14 /* ,true */) : 6; //this.maxBaseUploadsPerFrame //原先6. 但持续前进过程中会请求加载下一个漫游图,一次加6张会卡的。
  31067. this.updateUploadQueue(maxNonBaseUploadsPerFrame, maxBaseUploadsPerFrame);
  31068. //注:静止时看不出卡顿所以全速加载
  31069. }
  31070. };
  31071. /* function upload() {
  31072. if (!this.uploadIntervalCancelled) {
  31073. if (this.overlayTilesLoaded || !this.usingTileOverlay) {
  31074. b = !0
  31075. let maxNonBaseUploadsPerFrame = viewer.mainViewport.view.isFlying() ? 1 : this.maxNonBaseUploadsPerFrame //原先2。这是每帧uploadTile非512的瓦片tex的数量。之前的2太卡了,降为1。(检测卡顿方法:在一个pano点旋转至所有2048的tile都加载完,然后之后到这个点看看卡不卡。因为该点tiles都下载完了所以会在飞过来时陆续都加载,所以容易卡)
  31076. this.updateUploadQueue(maxNonBaseUploadsPerFrame, this.maxBaseUploadsPerFrame)
  31077. let time = viewer.mainViewport.view.isFlying() ? 60 : w //add 飞行有时候会卡,增长间隔
  31078. this.peekNextFromUploadQueue() ? this.refreshUploadInterval(time) : this.uploadInterval = null //定时下一次更新
  31079. } else {
  31080. this.refreshUploadInterval(this.uploadIntervalDelay)
  31081. }
  31082. }
  31083. } */
  31084. PanoRenderer.prototype.uploadTile = function () {
  31085. //重写
  31086. var collection = {},
  31087. overlayStyle = config$1.tiling.overlayStyle;
  31088. var failHistory = {};
  31089. return function (info, n) {
  31090. var id = info.panoId,
  31091. img = info.image,
  31092. tileSize = info.tileSize,
  31093. panoSize = info.panoSize,
  31094. tileIndex = info.tileIndex,
  31095. totalTiles = info.totalTiles,
  31096. tileX = info.tileX,
  31097. tileY = info.tileY,
  31098. p = !0,
  31099. g = !1,
  31100. ignore = false,
  31101. //add
  31102. LodDescripor = (this.getPanoDescriptor(id), this.getPanoLODDescriptor(id, panoSize)),
  31103. activeDescripor = this.getActiveRenderTargetDescriptor(id),
  31104. renderTarget = activeDescripor.renderTarget,
  31105. size = activeDescripor.size; //当前要渲染的面的分辨率,也就是MaxNavPanoSize
  31106. if (this.isPanoZoomed(id) && this.zoomRenderTarget) {
  31107. renderTarget = this.zoomRenderTarget;
  31108. size = this.zoomRenderTarget.width; //this.qualityManager.getMaxZoomPanoSize(); //放大后可能2048或4096
  31109. }
  31110. //console.log(window.sceneName, 'uploadTile ', id, tileIndex)
  31111. var done = () => {
  31112. if (!LodDescripor.uploaded.includes(tileIndex)) {
  31113. //已经upload过(本来这时候直接返回,但发现缩放后这不会归零,导致清晰度不更新,所以还是redraw且emit吧)
  31114. //console.log('try to reupload and return',tileIndex)
  31115. LodDescripor.uploaded.push(tileIndex);
  31116. LodDescripor.uploadCount++;
  31117. }
  31118. this.dispatchEvent({
  31119. type: PanoRendererEvents$1.TileRenderSuccess,
  31120. id,
  31121. panoSize,
  31122. tileIndex,
  31123. totalTiles
  31124. });
  31125. LodDescripor.uploadCount === totalTiles && this.dispatchEvent({
  31126. type: PanoRendererEvents$1.PanoRenderComplete,
  31127. id,
  31128. panoSize,
  31129. totalTiles,
  31130. updateFullComplete: true
  31131. });
  31132. this.setUploaded(info, !0);
  31133. this.addCoverageForNode(info.node);
  31134. };
  31135. {
  31136. //已经uploadTile过了不再uploadTile
  31137. if (!this.isRenderTargetDescriptorValid(activeDescripor)) {
  31138. p = !1;
  31139. g = !1;
  31140. }
  31141. if (!n) {
  31142. this.anyUploaded(info.node) && (p = !1, g = !0, ignore = true); //包括子集也uploadTile了
  31143. this.isTileUploaded(info) && (p = !1, g = !1, ignore = true); //当前tile uploadTile了
  31144. }
  31145. }
  31146. if (p) {
  31147. /*if(failHistory[id+':'+ panoSize+ ':' +tileIndex]){
  31148. console.log('uploadTile retry',id, panoSize, tileIndex)
  31149. }
  31150. console.log('uploadTile 成功', id, panoSize, tileIndex) */
  31151. var C = tileX * tileSize,
  31152. I = tileY * tileSize,
  31153. E = tileSize / panoSize * size,
  31154. // tile在renderTarget上渲染出的宽度
  31155. b = C / panoSize * size,
  31156. // tile在renderTarget上渲染的startX
  31157. w = I / panoSize * size; // tile在renderTarget上渲染的startY
  31158. if (panoSize > this.qualityManager.maxRenderTargetSize) {
  31159. //4096 改
  31160. /* var tex = this.initSizedTexture2D(tileSize, THREE.ClampToEdgeWrapping);
  31161. var loaded = this.viewer.images360.isHighMapLoaded(info.cubeFace, tileX,tileY) */
  31162. this.viewer.images360.getHighImage(img, info.cubeFace, tileX, tileY);
  31163. } else {
  31164. collection[tileSize] || (collection[tileSize] = this.initSizedTexture2D(tileSize, ClampToEdgeWrapping));
  31165. var tex = collection[tileSize];
  31166. this.uploadTexture2D(img, tex, 0, 0, tileSize, tileSize); //只替换tex对应的img,不新建
  31167. if (panoSize > this.qualityManager.maxRenderTargetSize) {
  31168. loaded || this.viewer.images360.updateHighMap(tex, info.cubeFace, tileX, tileY);
  31169. } else {
  31170. if (1 === overlayStyle || 2 === overlayStyle) {
  31171. var T = 1 === overlayStyle ? this.overlayTilesBasic : this.overlayTilesEnhanced;
  31172. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  31173. this.renderToCubeMap(T[panoSize], renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace, NormalBlending, !0, .5);
  31174. } else {
  31175. this.renderToCubeMap(tex, renderTarget, tileSize, tileSize, 0, 0, tileSize, tileSize, b, w, E, E, info.cubeFace);
  31176. }
  31177. }
  31178. }
  31179. done();
  31180. } else if (ignore) {
  31181. //console.log('finish because anyUploaded',id,panoSize,tileIndex)
  31182. done(); //改: 如果因为这部分更高清的贴图已加载所以才不绘制的话,直接完成
  31183. } else {
  31184. //console.log('uploadTile 失败', id, panoSize, tileIndex)
  31185. if (panoSize == 512) {
  31186. //console.log("!!!!!!!!!!!!!")
  31187. }
  31188. failHistory[id + ':' + panoSize + ':' + tileIndex] = true;
  31189. this.setUploaded(info, !1);
  31190. }
  31191. info.uploadAttempted || (LodDescripor.uploadAttempts++, this.dispatchEvent({
  31192. type: PanoRendererEvents$1.TileUploadAttempted,
  31193. id,
  31194. panoSize,
  31195. tileIndex,
  31196. totalTiles
  31197. })), info.uploadAttempted = !0;
  31198. LodDescripor.uploadAttempts === totalTiles && this.dispatchEvent({
  31199. type: PanoRendererEvents$1.UploadAttemptedForAllTiles,
  31200. id,
  31201. panoSize,
  31202. totalTiles
  31203. });
  31204. return g;
  31205. };
  31206. }();
  31207. /*
  31208. 注:tileY的方向同UV,从下到上
  31209. renderToCubeMap里的画布or镜头的xy范围是-0.5到0.5
  31210. */
  31211. PanoRenderer.prototype.renderToCubeMap = function () {
  31212. var inited = !1,
  31213. scene = null,
  31214. camera = null,
  31215. material = null,
  31216. geo = null,
  31217. plane = null,
  31218. l = 1;
  31219. return function (texture, renderTarget, tileWidth, tileHeight, startXinTile, startYinTile, widthinTile, heightinTile, startX, startY, width, height, cubeFace, E, b, w) {
  31220. var renderer = this.viewer.renderer;
  31221. inited || (camera = new OrthographicCamera(l / -2, l / 2, l / 2, l / -2, -200, 200), camera.position.z = 150, scene = new Scene(), scene.add(camera), material = new BasicMaterial({
  31222. depthWrite: !1,
  31223. depthTest: !1,
  31224. side: 0
  31225. }), geo = new PlaneBufferGeometry(l, l), plane = new Mesh(geo, material), plane.position.z = 0, scene.add(plane), inited = !0);
  31226. var uv = geo.getAttribute("uv");
  31227. uv.setDynamic(!0),
  31228. //setUsage
  31229. uv.needsUpdate = !0;
  31230. var uvArr = uv.array,
  31231. S = startXinTile / tileWidth,
  31232. //uv这几个值基本是固定的startXinTile:0,startYinTile:0,widthinTile:512,widthinTile:512,tileWidth:512,tileHeight:512 也就是说uv不会变、每张tile的有效范围是100%
  31233. M = startYinTile / tileHeight,
  31234. R = widthinTile / tileWidth,
  31235. P = heightinTile / tileHeight;
  31236. uvArr[0] = S, uvArr[1] = M + P, uvArr[2] = S + R, uvArr[3] = M + P, uvArr[4] = S, uvArr[5] = M, uvArr[6] = S + R, uvArr[7] = M;
  31237. //修改posistion,使该plane只占据需要绘制的部分。类似拼图。
  31238. //startX startY width height 都是在画布上的大小,比如画布大小为2048*2048,此tile为16分之一,tileX是1,tileY是1,则startX=2048/4,startY=2048/4
  31239. var pos = geo.getAttribute("position");
  31240. pos.setDynamic(!0), pos.needsUpdate = !0;
  31241. var posArr = pos.array,
  31242. D = startX / renderTarget.width - l / 2 // 起始x
  31243. ,
  31244. N = startY / renderTarget.height - l / 2 // 起始y
  31245. ,
  31246. B = width / renderTarget.width // 宽
  31247. ,
  31248. F = height / renderTarget.height; // 高
  31249. posArr[0] = D, posArr[1] = N + F, posArr[3] = D + B, posArr[4] = N + F, posArr[6] = D, posArr[7] = N, posArr[9] = D + B, posArr[10] = N;
  31250. //renderer.properties.get(scene);
  31251. material.map = texture; //material.uniforms.map.value = texture;
  31252. material.blending = E || NoBlending, material.transparent = !!b;
  31253. void 0 !== w && null !== w || (w = 1), material.uniforms.opacity.value = w,
  31254. // material.needUpdate = !0
  31255. //renderTarget.activeCubeFace = cubeFace, //0-5 应该是指定渲染h中的面 失效
  31256. /* renderer.setScissorTest(!0)
  31257. //指定绘制区域,类似遮罩(相对于屏幕)
  31258. renderer.setScissor(startX,startY,width,height) //加上这个会不会快一些,尤其是spherical
  31259. //指定绘制视口位置和大小(相对于屏幕)
  31260. */
  31261. renderTarget.viewport.set(0, 0, renderTarget.width, renderTarget.height);
  31262. var V = renderer.autoClear;
  31263. var oldTarget = renderer.getRenderTarget();
  31264. renderer.autoClear = !1;
  31265. renderer.setRenderTarget(renderTarget, cubeFace);
  31266. renderer.render(scene, camera /* , renderTarget, !1 */);
  31267. renderer.setRenderTarget(oldTarget);
  31268. renderer.autoClear = V;
  31269. //renderer.setScissorTest(!1)
  31270. /* this.renderer.render(scene, camera, this.planeTargets[cubeFace], !1),//针对有的场景app第一个点图加载不成功的问题
  31271. console.log(`图index ${cubeFace} , ${startX}, ${startY}, ${width}, ${height}`)
  31272. this.targetList[cubeFace] || (this.targetList[cubeFace] = [])
  31273. this.targetList[cubeFace].push([startX,startY,width,height])*/
  31274. };
  31275. }();
  31276. /*
  31277. * 将texture渲染到zoomRenderTarget上(目的是复制贴图到zoomRenderTarget)
  31278. */
  31279. PanoRenderer.prototype.copyCubeMap = function () {
  31280. //将texture渲染到zoomRenderTarget上
  31281. var inited = !1,
  31282. scene = null,
  31283. camera = null,
  31284. material = null,
  31285. geo = null,
  31286. mesh = null,
  31287. testCube = null,
  31288. //add
  31289. c = new Euler();
  31290. return function (texture, renderTarget, tWidth, tHeight, rWidth, rHeight, m, v, A) {
  31291. if (rWidth > this.qualityManager.maxRenderTargetSize) return; //add
  31292. if (!inited) {
  31293. var w = 2;
  31294. camera = new OrthographicCamera(w / -2, w / 2, w / 2, w / -2, 0, 200), camera.position.set(0, 0, 0), scene = new Scene(), scene.add(camera);
  31295. material = new ShaderMaterial({
  31296. uniforms: {
  31297. tDiffuse: {
  31298. type: "t",
  31299. value: null
  31300. },
  31301. alpha: {
  31302. type: "f",
  31303. value: 1
  31304. }
  31305. },
  31306. vertexShader: Shaders['copyCubeMap.vs'],
  31307. fragmentShader: Shaders['copyCubeMap.fs'],
  31308. depthWrite: !1,
  31309. depthTest: !1,
  31310. side: DoubleSide
  31311. });
  31312. geo = new BoxGeometry(w, w, w), mesh = new Mesh(geo, material), scene.add(mesh);
  31313. inited = !0;
  31314. /* testCube = mesh.clone();
  31315. viewer.scene.scene.add(testCube);
  31316. Potree.Utils.setObjectLayers(testCube, 'sceneObjects')
  31317. */
  31318. }
  31319. var autoClear = this.viewer.renderer.autoClear;
  31320. var oldTarget = this.viewer.renderer.getRenderTarget();
  31321. this.viewer.renderer.autoClear = false;
  31322. material.uniforms.tDiffuse.value = texture;
  31323. material.blending = m || NoBlending;
  31324. material.transparent = !!v;
  31325. void 0 !== A && null !== A || (A = 1);
  31326. material.uniforms.alpha.value = A;
  31327. material.needUpdate = !0;
  31328. for (var C = 0; C < 6; C++) {
  31329. this.getCubeOrientationForCubeFace(C, c);
  31330. mesh.rotation.copy(c);
  31331. mesh.matrixWorldNeedsUpdate = !0;
  31332. mesh.updateMatrixWorld();
  31333. renderTarget.viewport.set(0, 0, rWidth, rHeight);
  31334. this.viewer.renderer.setRenderTarget(renderTarget, C); //renderTarget.activeCubeFace = C//失效
  31335. this.viewer.renderer.render(scene, camera);
  31336. }
  31337. //console.warn('copyCubeMap' + rWidth)
  31338. this.viewer.renderer.autoClear = autoClear;
  31339. this.viewer.renderer.setRenderTarget(oldTarget);
  31340. };
  31341. }();
  31342. class DepthImageSampler extends EventDispatcher {
  31343. constructor() {
  31344. super();
  31345. var canvas = document.createElement("canvas");
  31346. this.canvas = canvas;
  31347. this.context = canvas.getContext("2d", {
  31348. willReadFrequently: true
  31349. });
  31350. this.imgDatas = [];
  31351. /* document.getElementsByTagName('body')[0].appendChild(canvas);
  31352. canvas.style.position = 'fixed';
  31353. canvas.style.width = '1024px';
  31354. canvas.style.top = canvas.style.left = 0
  31355. canvas.style['z-index'] = 100
  31356. */
  31357. this.maxDataCount = browser.isMobile() ? 6 : 20; //手机会崩溃. 平均每张图为8M数据量(以200个点的园区为例,加载时间久一些后,总内存=700 + 每张图的8M * maxDataCount)
  31358. this.maxNeighCount = browser.isMobile() ? 3 : 14; //包含在maxDataCount内的nearPanos最大个数.至少比maxDataCount少3个,留出空位给最近更新的pano
  31359. this.nearPanos = [];
  31360. }
  31361. updateNearPanos(panos) {
  31362. this.nearPanos = panos.slice(0, this.maxNeighCount);
  31363. }
  31364. changeImg(img, pano) {
  31365. this.pano = pano;
  31366. var item = this.imgDatas.find(p => p.pano == pano);
  31367. if ( /* this.img == img || */item) {
  31368. //最新的在末尾,所以换到末尾
  31369. var index = this.imgDatas.indexOf(item);
  31370. this.imgDatas.splice(index, 1);
  31371. this.imgDatas.push(item);
  31372. //console.log('重复使用',item.pano.id)
  31373. return;
  31374. }
  31375. Potree.timeCollect.depthSamChangeImg.start = true; //不过在刚启动时得到的用时较大
  31376. try {
  31377. viewer.addTimeMark('depthSamChangeImg', 'start');
  31378. this.canvas.width = img.width;
  31379. this.canvas.height = img.height;
  31380. this.context.drawImage(img, 0, 0);
  31381. var o = this.context.getImageData(0, 0, img.width, img.height);
  31382. var data = o && o.data; //getImageData 1px时 : pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十
  31383. //console.log('changeImg',pano.id )
  31384. //this.img = img
  31385. if (!data) {
  31386. console.error('getImageData 得不到?!why!');
  31387. return false;
  31388. }
  31389. if (this.imgDatas.length >= this.maxDataCount) {
  31390. var old = this.imgDatas.find(e => !this.nearPanos.includes(e.pano));
  31391. //console.log('推出',old.pano.id)
  31392. this.imgDatas.splice(this.imgDatas.indexOf(old), 1); //推出使用时间最早的一个非nearPano
  31393. }
  31394. this.imgDatas.push({
  31395. pano,
  31396. data
  31397. });
  31398. this.dispatchEvent({
  31399. type: 'changeImg',
  31400. pano
  31401. });
  31402. viewer.addTimeMark('depthSamChangeImg', 'end'); //耗时chrome 25ms,firefox: 38ms, iphoneX:33ms
  31403. } catch (e) {
  31404. console.error(e); //内存不足 Failed to execute 'getImageData' on 'CanvasRenderingContext2D': Out of memory at ImageData creation
  31405. return false;
  31406. }
  31407. /* pano.depthData = {}
  31408. for(let h=0; h<img.height; h++){
  31409. for(let w=0; w<img.width; w++){
  31410. let blockIndex = img.width * h + w
  31411. let r = data.slice(blockIndex*4, (blockIndex+1)*4)
  31412. let depth = r[1] + r[0] / 256
  31413. if(depth>0) pano.depthData[h+'|'+w] = depth
  31414. }
  31415. } */
  31416. }
  31417. clearTexData() {
  31418. this.imgDatas.length = 0;
  31419. }
  31420. getDepth(UVx, UVy, useNeighIfZero) {
  31421. //根据图片像素获取深度值
  31422. var x = Math.round(UVx * (this.canvas.width - 1)),
  31423. y = Math.round(UVy * (this.canvas.height - 1));
  31424. var imgData = this.imgDatas.find(p => p.pano == this.pano);
  31425. var get = (x, y) => {
  31426. if (!(x < 0 || y < 0 || x >= this.canvas.width || y >= this.canvas.height)) {
  31427. var blockIndex = this.canvas.width * y + x;
  31428. var color = imgData.data.slice(blockIndex * 4, (blockIndex + 1) * 4);
  31429. return color[1] + color[0] / 256; //为什么不是除以255见聊天记录.(验证过比点云的远一点点)
  31430. }
  31431. };
  31432. /* viewer.addTimeMark('depthSampler','start')
  31433. var r = this.context.getImageData(x, y, 1, 1).data; //pc chrome 耗时0.01毫秒左右(排除第一次的50) , 但firefox: 4。但换贴图之后就多达5甚至几十
  31434. viewer.addTimeMark('depthSampler','end')
  31435. */
  31436. var depth = get(x, y);
  31437. if (!depth && useNeighIfZero) {
  31438. //遇到过有的相隔很远且有阻挡的两个漫游点间居然depth为0,没有阻挡?但是周围点有四个非零。所以为了修正会飞到很远的点加个识别周围像素的depth 。 2024.3.19
  31439. var results = [];
  31440. var d = 0,
  31441. sum = 0,
  31442. count = 0,
  31443. maxResDis = 1;
  31444. while (d++ < maxResDis) {
  31445. for (var i = -d; i <= d; i++) {
  31446. for (var j = -d; j <= d; j++) {
  31447. if (i == -d || i == d || j == -d || j == d) {
  31448. //外围
  31449. var depth1 = get(x + i, y + j);
  31450. if (depth1 != 0) {
  31451. results.push(depth1);
  31452. }
  31453. }
  31454. }
  31455. }
  31456. }
  31457. if (results.length) {
  31458. depth = results.reduce((w, c) => {
  31459. return w + c;
  31460. }, 0) / results.length;
  31461. //console.error('useNeighIfZero', results, depth)
  31462. }
  31463. //console.log('useNeighIfZero', results, depth)
  31464. }
  31465. return depth;
  31466. }
  31467. sample(intersect, currentPano, onlyPos, useNeighIfZero) {
  31468. //通过和skybox的intersect得到真实的intersect的位置
  31469. if (!intersect) return;
  31470. var location = new Vector3();
  31471. var normal;
  31472. currentPano = currentPano || viewer.images360.currentPano;
  31473. if (currentPano != this.currentPano || !this.imgDatas.find(p => p.pano == currentPano)) {
  31474. if (!currentPano.depthTex /* || !currentPano.depthTex.image */) return; //未加载
  31475. if (this.changeImg(currentPano.depthTex.image, currentPano) === false) {
  31476. console.log('失败', currentPano.id);
  31477. return false; //失败
  31478. }
  31479. this.currentPano = currentPano;
  31480. }
  31481. var origin = currentPano.position;
  31482. var dir = intersect.dir || new Vector3().subVectors(intersect.point, origin).normalize();
  31483. //var uv = intersect.uv
  31484. //let dirInPano = math.getNormalDir(dir, currentPano)//转化为考虑漫游点旋转的方向
  31485. var dirInPano = dir.clone().applyMatrix4(currentPano.panoMatrix2Inverse).normalize(); //转化为考虑漫游点旋转的方向
  31486. var uv = math.getUVfromDir(dirInPano); //转化为uv
  31487. var distance = this.getDepth(uv.x, uv.y, useNeighIfZero);
  31488. //viewer.addTimeMark(markName,'end')
  31489. if (!distance) {
  31490. var margin = 0.1;
  31491. if (uv.y > 1 - Potree.config.depthTexUVyLimit) {
  31492. //漫游点底部识别不到的区域,给一个地板高度
  31493. distance = (currentPano.floorPosition.z - origin.z - margin) / dir.z;
  31494. location.copy(dir).multiplyScalar(distance).add(origin);
  31495. var _normal = new Vector3(0, 0, 1);
  31496. return {
  31497. location,
  31498. normal: _normal,
  31499. distance
  31500. };
  31501. } else if (uv.y < Potree.config.depthTexUVyLimit) {
  31502. var ceilZ = currentPano.getCeilHeight();
  31503. if (ceilZ == Infinity) return !1;else {
  31504. distance = (ceilZ - origin.z - margin) / dir.z;
  31505. location.copy(dir).multiplyScalar(distance).add(origin);
  31506. var _normal2 = new Vector3(0, 0, -1);
  31507. return {
  31508. location,
  31509. normal: _normal2,
  31510. distance
  31511. };
  31512. }
  31513. }
  31514. //console.log('无穷远')
  31515. return !1; //应该是天空或模型外 , 因为很少有漫游点的地方还拍不到地板
  31516. }
  31517. //console.log('distance', distance, dirInPano.clone().multiplyScalar(distance))
  31518. location.copy(dir).multiplyScalar(distance).add(origin);
  31519. if (!onlyPos) {
  31520. var pL = this.getNearbyPoint(origin, uv, -1, 0),
  31521. pR = this.getNearbyPoint(origin, uv, 1, 0),
  31522. pB = this.getNearbyPoint(origin, uv, 0, -1),
  31523. pT = this.getNearbyPoint(origin, uv, 0, 1);
  31524. normal = this.planeFit(dir, location, pL, pR, pB, pT);
  31525. }
  31526. /* if(normal.x != normal.x ){
  31527. console.log('NAN', normal)
  31528. var pL = this.getNearbyPoint(origin, uv, -1, 0)
  31529. , pR = this.getNearbyPoint(origin, uv, 1, 0)
  31530. , pB = this.getNearbyPoint(origin, uv, 0, -1)
  31531. , pT = this.getNearbyPoint(origin, uv, 0, 1);
  31532. } */
  31533. //console.log(location, normal, distance)
  31534. return {
  31535. location,
  31536. normal,
  31537. distance
  31538. };
  31539. }
  31540. getNearbyPoint(origin, uv, x, y) {
  31541. //获取附近的若干像素距离的点
  31542. var uv2 = uv.clone();
  31543. uv2.x += x / (this.canvas.width - 1);
  31544. uv2.x = this.clampUV(uv2.x);
  31545. uv2.y += y / (this.canvas.height - 1);
  31546. uv2.y = this.clampUV(uv2.y);
  31547. /* if(uv2.x < 0 || uv2.y < 0 || uv2.x > 1 || uv2.y > 1){
  31548. console.log('will nan')
  31549. } */
  31550. var dir = math.getDirFromUV(uv2); //从uv获取到方向
  31551. dir.applyMatrix4(viewer.images360.currentPano.panoMatrix2);
  31552. var depth = this.getDepth(uv2.x, uv2.y);
  31553. /* if(Math.abs(depth - this.mainDepth) > 0.3){
  31554. console.log('Math.abs(depth - this.mainDepth) > 0.3')
  31555. } */
  31556. //let dir = new THREE.Vector3().subVectors(intersect.point, origin).normalize()
  31557. var position = new Vector3().copy(dir).multiplyScalar(depth).add(origin);
  31558. //console.log('getNearbyPoint', uv2, depth, dir, position )
  31559. return position;
  31560. }
  31561. clampUV(v) {
  31562. return (v + 1) % 1; // 使输出在 0-1
  31563. }
  31564. planeFit(dir, position, pL, pR, pB, pT) {
  31565. //求平均法线
  31566. var normal = new Vector3();
  31567. var plane = new Plane();
  31568. function addNormal(p1, p2) {
  31569. //根据临接的四个点,分别求法线,然后法线相加能得到平均法线
  31570. if (!p1 || !p2) return;
  31571. plane.setFromCoplanarPoints(position, p1, p2);
  31572. //console.log('normalSub', plane.normal)
  31573. normal.addScaledVector(plane.normal, dir.dot(plane.normal) < 0 ? 1 : -1); //根据面的朝向判断加还是减
  31574. }
  31575. addNormal(pL, pB);
  31576. addNormal(pL, pT);
  31577. addNormal(pR, pB);
  31578. addNormal(pR, pT);
  31579. if (0 !== normal.x || 0 !== normal.y || 0 !== normal.z) {
  31580. normal.normalize();
  31581. //console.log(normal)
  31582. return normal;
  31583. }
  31584. /* 四个面拼成一个菱形 */
  31585. }
  31586. }
  31587. var {
  31588. PanoSizeClass: PanoSizeClass$3,
  31589. Vectors: Vectors$1,
  31590. GLCubeFaces: GLCubeFaces$3,
  31591. PanoramaEvents: PanoramaEvents$1
  31592. } = Potree.defines;
  31593. var rot90$1 = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI / 2); //使用的是刚好适合全景图的,给cube贴图需要转90°
  31594. var raycaster = new Raycaster();
  31595. //let currentlyHovered = null;
  31596. var texLoader$4 = new TextureLoader();
  31597. var addLine = function addLine(origin, dir, len) {
  31598. var color = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '#fff';
  31599. var line1 = LineDraw.createLine([origin, origin.clone().add(dir.clone().multiplyScalar(len || 1))], {
  31600. color
  31601. });
  31602. //console.log(origin.toArray(), dir.toArray())
  31603. viewer.scene.scene.add(line1);
  31604. return line1;
  31605. };
  31606. var tileArr = [];
  31607. var previousView = {
  31608. controls: null,
  31609. position: null,
  31610. target: null
  31611. };
  31612. var HighMapCubeWidth = 1;
  31613. var directionFactor = 400; //原先10,几乎只往距离近的走了;设置太大容易略过近处漫游点走向下坡,因为鼠标一般在地面,下坡的漫游点更有利
  31614. class Images360 extends EventDispatcher {
  31615. constructor(viewer) {
  31616. super();
  31617. this.viewer = viewer;
  31618. this.panos = [];
  31619. this.neighbourMap = {};
  31620. this.node = new Object3D();
  31621. this.node.name = 'ImagesNode';
  31622. this.cubePanos = [];
  31623. this.fastTranMaskPass = new FastTranPass(viewer.renderer);
  31624. {
  31625. this.cube = new Mesh(new BoxBufferGeometry(1, 1, 1, 1), new ModelTextureMaterial());
  31626. Potree.Utils.updateVisible(this.cube, 'showSkybox', false);
  31627. this.cube.layers.set(Potree.config.renderLayers.skybox);
  31628. this.cube.name = 'skyboxCube';
  31629. viewer.scene.scene.add(this.cube);
  31630. }
  31631. if (Potree.settings.testCube) {
  31632. this.cubeTest = this.cube.clone();
  31633. this.cubeTest.material = new MeshBasicMaterial({
  31634. wireframe: true,
  31635. color: '#FF3377',
  31636. transparent: true,
  31637. opacity: 0.7,
  31638. depthWrite: false,
  31639. depthTest: false
  31640. });
  31641. viewer.scene.scene.add(this.cubeTest);
  31642. this.cubeTest.visible = true;
  31643. }
  31644. this.flying_ = false;
  31645. this.currentPano = null;
  31646. this.mouseLastMoveTime = Date.now();
  31647. this.scrollZoomSpeed = 0.06;
  31648. this.zoomLevel = 1;
  31649. this.tileDownloader = new TileDownloader();
  31650. this.qualityManager = new QualityManager();
  31651. this.panoRenderer = new PanoRenderer(viewer, this.tileDownloader, this.qualityManager);
  31652. this.basePanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.BASE);
  31653. this.standardPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.STANDARD);
  31654. this.highPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.HIGH);
  31655. this.ultraHighPanoSize = this.qualityManager.getPanoSize(PanoSizeClass$3.ULTRAHIGH);
  31656. this.tileDownloader.processPriorityQueue = !1;
  31657. this.tileDownloader.tilePrioritizer = new TilePrioritizer(this.qualityManager, this.basePanoSize, this.standardPanoSize, this.highPanoSize, this.ultraHighPanoSize);
  31658. {
  31659. //高分辨率cube 放大
  31660. this.addHighMapCube();
  31661. viewer.addEventListener(PanoramaEvents$1.Enter, e => {
  31662. this.setHighMap(e.newPano);
  31663. });
  31664. viewer.addEventListener('panoSetZoom', e => {
  31665. if (Potree.settings.displayMode == 'showPanos') {
  31666. e.zoomed ? this.showHighMap() : this.hideHighMap(); //add
  31667. }
  31668. });
  31669. }
  31670. this.depthSampler = new DepthImageSampler();
  31671. viewer.fpControls.addEventListener('dollyStopCauseUnable', e => {
  31672. if ( /* e.hoverViewport != viewer.mainViewport || */!Potree.settings.zoom.enabled) return;
  31673. if (e.scale != void 0) {
  31674. //触屏
  31675. this.zoomBy(e.scale, e.pointer);
  31676. } else {
  31677. //滚轮
  31678. var zoom;
  31679. if (e.delta > 0) {
  31680. zoom = 1 + this.scrollZoomSpeed;
  31681. } else {
  31682. zoom = 1 - this.scrollZoomSpeed;
  31683. }
  31684. e.delta != 0 && this.zoomBy(zoom);
  31685. }
  31686. });
  31687. var click = e => {
  31688. //不用"mouseup" 是因为 mouseup有drag object时也会触发
  31689. if (e.clickElement || Potree.settings.unableNavigate || this.flying || !e.isTouch && e.button != MOUSE.LEFT || e.drag && e.drag.object //拖拽结束时不算
  31690. || Potree.settings.editType == 'pano' && viewer.modules.PanoEditor.activeViewName != 'mainView' || Potree.settings.editType == 'merge' && !e.intersectPoint || viewer.inputHandler.hoveredElements[0] && viewer.inputHandler.hoveredElements[0].isModel && e.intersectPoint.distance > viewer.inputHandler.hoveredElements[0].distance) return;
  31691. if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') {
  31692. if (e.hoverViewport == viewer.mapViewer.viewports[0]) {
  31693. return viewer.mapViewer.dispatchEvent(e /* {type:'global_click',e } */);
  31694. } else if (e.hoverViewport != viewer.mainViewport) {
  31695. //如数据集校准其他viewport
  31696. return;
  31697. }
  31698. }
  31699. if (!Potree.settings.dblToFocusPoint /* && this.currentPano */) {
  31700. //双击不会focus点云 或者 已经focusPano了
  31701. this.flyToPanoClosestToMouse();
  31702. }
  31703. };
  31704. viewer.addEventListener('global_click', click);
  31705. viewer.addEventListener("global_mousemove", e => {
  31706. if (!Potree.settings.unableNavigate && Potree.settings.ifShowMarker && e.hoverViewport == viewer.mainViewport) {
  31707. //如果不显示marker,就在点击时再更新
  31708. this.updateClosestPano(e.intersect);
  31709. }
  31710. });
  31711. this.addEventListener('markerHover', e => {
  31712. this.updateClosestPano(e.pano, e.hovered);
  31713. });
  31714. if (!Potree.settings.isOfficial) {
  31715. this.domRoot = viewer.renderer.domElement.parentElement;
  31716. var elUnfocus = $("<input type='button' value='unfocus'></input>");
  31717. elUnfocus.css({
  31718. position: "absolute",
  31719. right: '25%',
  31720. bottom: '20px',
  31721. zIndex: "10000",
  31722. fontSize: '1em',
  31723. color: "black",
  31724. display: 'none',
  31725. background: 'rgba(255,255,255,0.8)'
  31726. });
  31727. elUnfocus.on("click", () => this.unfocus());
  31728. this.elUnfocus = elUnfocus;
  31729. this.domRoot.appendChild(elUnfocus[0]);
  31730. if (Potree.settings.editType != 'merge') {
  31731. var elHide = $("<input type='button' value='隐藏点云'></input>");
  31732. elHide.css({
  31733. position: "absolute",
  31734. right: '40%',
  31735. bottom: '20px',
  31736. zIndex: "10000",
  31737. fontSize: '1em',
  31738. color: "black",
  31739. width: '100px',
  31740. background: 'rgba(255,255,255,0.8)'
  31741. });
  31742. this.domRoot.appendChild(elHide[0]);
  31743. elHide.on("click", e => {
  31744. var visi = Potree.Utils.getObjVisiByReason(viewer.scene.pointclouds[0], 'force');
  31745. viewer.scene.pointclouds.forEach(e => {
  31746. Potree.Utils.updateVisible(e, 'force', !visi);
  31747. });
  31748. elHide.val(!visi ? "隐藏点云" : "显示点云");
  31749. });
  31750. }
  31751. var elDisplayModel = $("<input type='button' value='>>全景'></input>");
  31752. elDisplayModel.css({
  31753. position: "absolute",
  31754. right: '65%',
  31755. bottom: '20px',
  31756. zIndex: "10000",
  31757. fontSize: '1em',
  31758. color: "black",
  31759. width: '100px',
  31760. background: 'rgba(255,255,255,0.8)'
  31761. });
  31762. this.domRoot.appendChild(elDisplayModel[0]);
  31763. elDisplayModel.on("click", e => {
  31764. if (Potree.settings.displayMode == 'showPointCloud' && this.panos.length == 0) return;
  31765. Potree.settings.displayMode = Potree.settings.displayMode == 'showPointCloud' ? 'showPanos' : 'showPointCloud';
  31766. });
  31767. this.elDisplayModel = elDisplayModel;
  31768. if (viewer.mapViewer) {
  31769. var mapStyleBtn = $("<input type='button' value='普通'></input>");
  31770. mapStyleBtn.css({
  31771. position: "absolute",
  31772. right: '50%',
  31773. bottom: '20px',
  31774. zIndex: "10000",
  31775. fontSize: '1em',
  31776. color: "black",
  31777. width: '100px',
  31778. background: 'rgba(255,255,255,0.8)'
  31779. });
  31780. this.domRoot.appendChild(mapStyleBtn[0]);
  31781. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'map');
  31782. mapStyleBtn.on("click", e => {
  31783. map.switchStyle(map.style == 'satellite' ? 'standard' : 'satellite');
  31784. mapStyleBtn.val(map.style == 'satellite' ? '卫星' : '普通');
  31785. });
  31786. }
  31787. }
  31788. {
  31789. //切换模式
  31790. var displayMode = '';
  31791. this.latestRequestMode = ''; //因为可能延迟,所以记录下每次的请求模式,延迟后判断这个
  31792. Object.defineProperty(Potree.settings, "displayMode", {
  31793. get: function get() {
  31794. return displayMode;
  31795. },
  31796. set: mode => {
  31797. this.latestRequestMode = mode;
  31798. console.warn('Request setMode: ' + mode);
  31799. this.dispatchEvent({
  31800. type: 'requestMode',
  31801. mode
  31802. });
  31803. var config2;
  31804. var config = Potree.config.displayMode[mode];
  31805. if (this.isAtPano() && !this.latestToPano) {
  31806. config2 = config.atPano;
  31807. } else {
  31808. config2 = config.transition;
  31809. }
  31810. var changeTileDownload = () => {
  31811. if (config2.showSkybox || config2.showPoint && config2.pointUsePanoTex) {
  31812. this.tileDownloader.start();
  31813. this.currentPano && this.currentPano.enter();
  31814. } else {
  31815. this.tileDownloader.stop();
  31816. this.currentPano && this.currentPano.exit();
  31817. this.nextPano && viewer.cancelLoad(this.nextPano);
  31818. }
  31819. };
  31820. if (mode != displayMode) {
  31821. var camera = viewer.scene.getActiveCamera();
  31822. if (mode == 'showPanos' && viewer.mainViewport.view.isFlying()) {
  31823. //飞完才能切换全景
  31824. var f = () => {
  31825. if (this.latestRequestMode == mode) {
  31826. //如果ui还是停在这个模式的话
  31827. Potree.settings.displayMode = mode;
  31828. }
  31829. viewer.mainViewport.view.removeEventListener('flyingDone', f);
  31830. };
  31831. viewer.mainViewport.view.addEventListener('flyingDone', f); //once
  31832. return;
  31833. }
  31834. if (this.isAtPano() && !this.latestToPano) {
  31835. config2 = config.atPano;
  31836. } else {
  31837. config2 = config.transition;
  31838. if (mode == 'showPanos') {
  31839. //自动飞入一个pano
  31840. //要改成飞进最近的。。。
  31841. if (this.panos.length == 0) return;
  31842. //this.modeChanging = true //主要是因为到全景图不会立刻成功
  31843. var wait = e => {
  31844. console.log('flyToPanoDone');
  31845. this.removeEventListener('flyToPanoDone', wait);
  31846. setTimeout(() => {
  31847. if (this.latestRequestMode == mode) {
  31848. Potree.settings.displayMode = mode;
  31849. }
  31850. }, e.makeIt ? 1 : 50);
  31851. };
  31852. this.addEventListener('flyToPanoDone', wait); //等待飞行完毕。flyToPano的callback可能不执行所以换这个。但也可能被cancel
  31853. this.flyToPano({
  31854. pano: this.findNearestPano()
  31855. //dealDoneWhenCancel:true,
  31856. /* callback: ()=>{
  31857. setTimeout(()=>{ //防止循环,所以延迟
  31858. if(this.latestRequestMode == mode ){
  31859. Potree.settings.displayMode = mode
  31860. }
  31861. },1)
  31862. } */
  31863. });
  31864. return;
  31865. } else {}
  31866. }
  31867. changeTileDownload();
  31868. if (config2.showSkybox || config2.pointUsePanoTex) {
  31869. var _wait = () => {
  31870. //console.log('waitdone')
  31871. //if(e.pano && e.pano != this.currentPano)return //loadedDepthImg
  31872. setTimeout(() => {
  31873. if (this.latestRequestMode == mode) {
  31874. Potree.settings.displayMode = mode;
  31875. }
  31876. }, 1);
  31877. };
  31878. //this.updateDepthTex()
  31879. if (this.checkAndWaitForPanoLoad(this.currentPano, this.basePanoSize, _wait)) {
  31880. //console.log('等待贴图加载2', this.currentPano.id)
  31881. return;
  31882. }
  31883. }
  31884. viewer.scene.pointclouds.forEach(e => {
  31885. Potree.Utils.updateVisible(e, 'displayMode', config2.showPoint, 2);
  31886. });
  31887. if (config2.pointUsePanoTex) {
  31888. viewer.scene.pointclouds.forEach(e => {
  31889. e.material.setProjectedPanos(this.currentPano, this.currentPano, 1);
  31890. });
  31891. } else {
  31892. viewer.scene.pointclouds.forEach(e => {
  31893. e.material.stopProjectedPanos();
  31894. });
  31895. }
  31896. Potree.Utils.updateVisible(this.cube, 'showSkybox', config2.showSkybox); // this.cube.visible = config2.showSkybox
  31897. //this.cube.visible = config.atPano.showSkybox
  31898. if (this.cube.visible) {
  31899. //this.cube.material.setProjectedPanos(this.currentPano, this.currentPano, 1)
  31900. this.setProjectedPanos({
  31901. progress: 1,
  31902. ifSkybox: true,
  31903. ifPointcloud: false,
  31904. easeInOutRatio: 0,
  31905. pano0: this.currentPano,
  31906. pano1: this.currentPano
  31907. });
  31908. } else {
  31909. this.smoothZoomTo(1);
  31910. this.resetHighMap();
  31911. this.hideHighMap();
  31912. }
  31913. /* viewer.dispatchEvent({
  31914. type: "enableChangePos",
  31915. canLeavePano : config.canLeavePano ,
  31916. viewport:
  31917. }) */
  31918. //viewer.mainViewport.unableChangePos = !config.canLeavePano
  31919. displayMode = mode;
  31920. if (mode == 'showPanos') {
  31921. camera.far = viewer.farWhenShowPano; //修改far
  31922. Potree.settings.pointDensity = 'panorama';
  31923. if (Potree.config.displayMode.showPanos.transition.pointUsePanoTex) {
  31924. viewer.scene.pointclouds.forEach(e => {
  31925. e.material.pointSizeType = 'FIXED';
  31926. });
  31927. }
  31928. this.updateCube(this.currentPano);
  31929. } else {
  31930. if (camera.limitFar) camera.far = Potree.settings.cameraFar; //修改far
  31931. Potree.settings.pointDensity = Potree.settings.UserPointDensity;
  31932. //Potree.sdk && Potree.sdk.scene.changePointOpacity()
  31933. if (Potree.config.displayMode.showPanos.transition.pointUsePanoTex) {
  31934. viewer.scene.pointclouds.forEach(e => {
  31935. e.material.pointSizeType = Potree.config.material.pointSizeType;
  31936. });
  31937. }
  31938. }
  31939. camera.updateProjectionMatrix();
  31940. if (this.elDisplayModel) {
  31941. this.elDisplayModel.val(mode == 'showPointCloud' ? ">>全景" : '>>点云');
  31942. }
  31943. /* this.panos.forEach(e=>{
  31944. Potree.Utils.updateVisible(e, 'modeIsShowPanos', mode == 'showPanos', 1, mode == 'showPanos' ? 'add':'cancel') //
  31945. }) */
  31946. this.dispatchEvent({
  31947. type: 'endChangeMode',
  31948. mode
  31949. });
  31950. console.log('setModeSuccess: ' + mode);
  31951. } else {
  31952. changeTileDownload();
  31953. //this.dispatchEvent({type:'endChangeMode',mode})
  31954. }
  31955. }
  31956. });
  31957. Potree.settings.displayMode = 'showPointCloud';
  31958. } // 切换模式 end
  31959. {
  31960. //
  31961. var currentPano = null;
  31962. Object.defineProperty(this, "currentPano", {
  31963. get: function get() {
  31964. return currentPano;
  31965. },
  31966. set: function set(e) {
  31967. if (e != currentPano) {
  31968. //console.log('set currentPano ', e.id)
  31969. currentPano && currentPano.exit();
  31970. e && e.enter();
  31971. currentPano = e;
  31972. }
  31973. }
  31974. });
  31975. }
  31976. {
  31977. //是否显示marker
  31978. var ifShowMarker = true;
  31979. Object.defineProperty(Potree.settings, "ifShowMarker", {
  31980. get: function get() {
  31981. return ifShowMarker;
  31982. },
  31983. set: show => {
  31984. show = !!show;
  31985. if (show != ifShowMarker) {
  31986. this.panos.forEach(pano => {
  31987. Potree.Utils.updateVisible(pano, 'ifShowMarker', show, 1);
  31988. });
  31989. //this.emit('markersDisplayChange', show)
  31990. ifShowMarker = show;
  31991. viewer.dispatchEvent('showMarkerChanged');
  31992. viewer.dispatchEvent('content_changed');
  31993. }
  31994. }
  31995. });
  31996. }
  31997. viewer.addEventListener("update", () => {
  31998. this.update(viewer);
  31999. });
  32000. //viewer.inputHandler.addInputListener(this);
  32001. var keys = {
  32002. FORWARD: ['W'.charCodeAt(0), 38],
  32003. BACKWARD: ['S'.charCodeAt(0), 40],
  32004. LEFT: ['A'.charCodeAt(0), 37],
  32005. RIGHT: ['D'.charCodeAt(0), 39]
  32006. };
  32007. viewer.inputHandler.addEventListener('keydown', e => {
  32008. if (Potree.settings.displayMode == 'showPanos') {
  32009. for (var i in keys) {
  32010. if (keys[i].some(a => a == e.keyCode)) {
  32011. switch (i) {
  32012. case 'FORWARD':
  32013. this.flyLocalDirection(Vectors$1.FORWARD.clone());
  32014. break;
  32015. case 'BACKWARD':
  32016. this.flyLocalDirection(Vectors$1.BACK.clone());
  32017. break;
  32018. case 'LEFT':
  32019. this.flyLocalDirection(Vectors$1.LEFT.clone());
  32020. break;
  32021. case 'RIGHT':
  32022. this.flyLocalDirection(Vectors$1.RIGHT.clone());
  32023. break;
  32024. }
  32025. break;
  32026. }
  32027. }
  32028. }
  32029. });
  32030. }
  32031. updateDepthTex(pano) {
  32032. if (this.currentPano != pano || !pano.depthTex) return;
  32033. //this.depthSampler.changeImg(pano.depthTex.image); //pick sampler要飞到了才能切换图,而skybox贴图是随着全景图切换而切换的
  32034. this.cube.material.updateDepthTex(pano); //确保一下
  32035. }
  32036. findNearestPano(pos) {
  32037. pos = pos ? new Vector3().copy(pos) : this.position;
  32038. var result = Common.sortByScore(this.panos, [Images360.filters.isEnabled()], [e => -e.position.distanceTo(pos)]);
  32039. var pano = result[0] && result[0].item;
  32040. return pano;
  32041. }
  32042. /* set flying(v){//正在飞向pano
  32043. this.flying_ = !!v
  32044. //console.log('this.flying_ ', !!v )
  32045. //this.emit('flying', this.flying_)
  32046. let config = Potree.config.displayMode[Potree.settings.displayMode]
  32047. viewer.mainViewport.unableChangePos = !config.canLeavePano || !!v
  32048. }
  32049. get flying(){
  32050. return this.flying_
  32051. } */
  32052. flyLocalDirection(dir) {
  32053. var direction = this.getDirection(dir),
  32054. option1 = 1 === dir.y ? .4 : .75,
  32055. option2 = 1 === Math.abs(dir.x);
  32056. return this.flyDirection(direction, option1, option2, true);
  32057. }
  32058. getDirection(e) {
  32059. if (!e) {
  32060. return viewer.scene.view.direction;
  32061. } else {
  32062. return e = e ? e : new Vector3().copy(Vectors$1.FORWARD), e.applyQuaternion(viewer.mainViewport.camera.quaternion);
  32063. }
  32064. }
  32065. get position() {
  32066. return this.viewer.scene.view.position.clone();
  32067. }
  32068. isAtPano(precision) {
  32069. //是否在某个漫游点上
  32070. if (precision) {
  32071. return this.currentPano && math.closeTo(viewer.scene.view.position, this.currentPano.position, precision);
  32072. }
  32073. return this.currentPano && viewer.scene.view.position.equals(this.currentPano.position);
  32074. }
  32075. updateProjectedPanos() {
  32076. //更新材质贴图
  32077. //console.warn('updateProjectedPanos')
  32078. this.projectedPano0 && this.projectedPano1 && this.setProjectedPanos({
  32079. pano0: this.projectedPano0,
  32080. pano1: this.projectedPano1
  32081. });
  32082. }
  32083. setProjectedPanos() {
  32084. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  32085. //设置cube和点云的材质贴图
  32086. this.cube.material.setProjectedPanos(o.pano0, o.pano1, o.progress);
  32087. if (o.ifPointcloud) {
  32088. viewer.scene.pointclouds.forEach(e => {
  32089. e.material.setProjectedPanos(o.pano0, o.pano1, o.progress, o.easeInOutRatio);
  32090. });
  32091. }
  32092. //console.warn('setProjectedPanos ', o.pano0.id , o.pano1.id)
  32093. this.projectedPano0 = o.pano0;
  32094. this.projectedPano1 = o.pano1;
  32095. }
  32096. cancelFlyToPano(toPano) {
  32097. //取消当前已有的飞行准备,前提是相机还未移动
  32098. if (viewer.mainViewport.view.isFlying() || toPano && this.latestToPano != toPano) return;
  32099. //Potree.Log('cancelFlyToPano', this.latestToPano && this.latestToPano.pano.id)
  32100. this.nextPano = null;
  32101. this.latestToPano = null;
  32102. }
  32103. flyToPano(toPano) {
  32104. //飞向漫游点
  32105. if (!toPano) return;
  32106. if (typeof toPano == 'number') toPano = this.panos[toPano];
  32107. if (toPano instanceof Panorama) {
  32108. toPano = {
  32109. pano: toPano
  32110. };
  32111. }
  32112. var done = (makeIt, disturb) => {
  32113. //console.log('flyToPano done ', toPano.pano.id, makeIt, disturb )
  32114. if (makeIt || disturb) {
  32115. // disturb已经开始飞行但中途取消
  32116. toPano.callback && toPano.callback(makeIt);
  32117. //this.flying = false
  32118. this.cancelFlyToPano(toPano);
  32119. this.updateClosestPano(this.closestPano, false); //飞行结束后取消点击漫游点时得到的closestPano
  32120. } else {}
  32121. this.dispatchEvent({
  32122. type: 'flyToPanoDone',
  32123. makeIt,
  32124. disturb
  32125. });
  32126. this.fastTranMaskPass.stop();
  32127. toPano.deferred && toPano.deferred.resolve(makeIt); //测量线截图时发现,resolve需要写在flying=false 后才行。
  32128. };
  32129. if (!toPano.pano.enabled) return done(false, true);
  32130. //Potree.Log('hope flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() )
  32131. if (this.latestToPano && this.latestToPano != toPano && (
  32132. //还在飞
  32133. this.latestToPano.pano != this.currentPano || !this.isAtPano())) {
  32134. //如果旧的toPano只在pano旋转镜头,就直接取消旧的,继续执行
  32135. return done(false);
  32136. }
  32137. if (this.currentPano == toPano.pano && this.isAtPano() && !toPano.target && !toPano.quaternion) {
  32138. //已在该pano
  32139. this.dispatchEvent({
  32140. type: 'flyToPano',
  32141. toPano
  32142. });
  32143. return done(true);
  32144. }
  32145. //Potree.Log('flyToPano: '+toPano.pano.id, toPano.pano.position.toArray() /* this.latestToPano && this.latestToPano.pano.id */ )
  32146. var target = toPano.target;
  32147. var config = Potree.config.displayMode[Potree.settings.displayMode];
  32148. var pano = toPano.pano;
  32149. var dis = pano.position.distanceTo(this.position);
  32150. this.nextPano = pano;
  32151. this.latestToPano = toPano;
  32152. //this.flying = true //防止新的请求
  32153. //Potree.Log('flyToPano:'+pano.id + ' , duration:'+toPano.duration, null, 12)
  32154. {
  32155. //不飞的话是否不要执行这段?
  32156. var wait = e => {
  32157. //console.log('wait done', pano.id)
  32158. if ( /* e.pano && */this.latestToPano && pano != this.latestToPano.pano) return; //loadedDepthImg
  32159. if (this.latestToPano != toPano) return Potree.Log('已经取消', pano.id); //如果取消了
  32160. setTimeout(() => {
  32161. if (this.latestToPano != toPano) return;
  32162. this.flyToPano(toPano);
  32163. }, 1);
  32164. };
  32165. if (!pano.depthTex && pano.pointcloud.hasDepthTex) {
  32166. //点云模式也要加载depthTex,因获取neighbour需要用到
  32167. console.log('等待加载depthtex', pano.id);
  32168. pano.addEventListener('loadedDepthImg', wait, {
  32169. once: true
  32170. });
  32171. return pano.loadDepthImg();
  32172. }
  32173. if (config.atPano.showSkybox || config.atPano.pointUsePanoTex) {
  32174. var a = this.updateCube(this.currentPano, toPano.pano);
  32175. if (a == 'useBound') {
  32176. toPano.useBound = true;
  32177. }
  32178. if (this.checkAndWaitForPanoLoad(pano, toPano.basePanoSize || this.basePanoSize, wait)) {
  32179. //console.log('等待贴图加载',pano.id)
  32180. return;
  32181. }
  32182. }
  32183. }
  32184. config = Potree.config.displayMode[Potree.settings.displayMode]; //可能换了
  32185. var pointcloudVisi = config.atPano.showPoint; //viewer.scene.pointclouds[0].visible
  32186. Potree.Utils.updateVisible(this.cube, 'showSkybox', config.atPano.showSkybox); // this.cube.visible = config.atPano.showSkybox
  32187. //console.log('开始飞1')
  32188. if (config.transition.showPoint) {
  32189. viewer.scene.pointclouds.forEach(e => {
  32190. Potree.Utils.updateVisible(e, 'displayMode', true);
  32191. });
  32192. }
  32193. var endPosition = pano.position.clone();
  32194. var T = Potree.config.transitionsTime;
  32195. /* let maxTime = this.isAtPano() ? T.panoToPanoMax : T.flyIn
  32196. let duration = toPano.duration == void 0 ? (T.flyMinTime+Math.min(T.flytimeDistanceMultiplier * dis, maxTime)) : toPano.duration
  32197. */
  32198. /* let maxDis = this.isAtPano() ? T.maxDistanceThreshold : T.maxDistanceThresholdFlyIn
  32199. let duration = toPano.duration == void 0 ? Math.min(dis, T.maxDistanceThreshold) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration
  32200. */
  32201. var maxDis = 7;
  32202. var duration = toPano.duration == void 0 ? Math.min(dis, maxDis) * T.flytimeDistanceMultiplier + T.flyMinTime : toPano.duration;
  32203. if (config.transition.showSkybox || config.transition.pointUsePanoTex) {
  32204. if (Potree.settings.fastTran) {
  32205. this.fastTranMaskPass.start(); //截图当前画面
  32206. viewer.scene.view.position.copy(endPosition);
  32207. }
  32208. this.setProjectedPanos({
  32209. progress: 0,
  32210. ifSkybox: this.cube.visible,
  32211. ifPointcloud: config.transition.pointUsePanoTex,
  32212. easeInOutRatio: pointcloudVisi ? 0.3 : 0,
  32213. pano0: this.currentPano,
  32214. pano1: pano
  32215. });
  32216. }
  32217. if (toPano.useBound) {
  32218. duration = Math.min(1500, duration);
  32219. toPano.easeName = 'easeInOutQuad';
  32220. } else {
  32221. if (endPosition.equals(this.position)) toPano.easeName = 'easeOutSine';
  32222. }
  32223. {
  32224. toPano.easeName = toPano.easeName || 'linearTween';
  32225. toPano.duration = duration;
  32226. this.beforeFlyToPano(toPano);
  32227. }
  32228. /* let fly = ()=>{
  32229. this.dispatchEvent({type:'flyToPano', toPano})
  32230. viewer.scene.view.setView({position:endPosition, target, quaternion:toPano.quaternion , duration,
  32231. callback:()=>{
  32232. if(!config.atPano.pointUsePanoTex){
  32233. viewer.scene.pointclouds.forEach(e=>{
  32234. e.material.stopProjectedPanos()
  32235. })
  32236. }
  32237. this.currentPano = pano;
  32238. this.nextPano = null;
  32239. if(Potree.settings.displayMode == 'showPanos'){
  32240. viewer.scene.pointclouds.forEach(e=>{
  32241. Potree.Utils.updateVisible(e, 'displayMode',pointcloudVisi)
  32242. })
  32243. }
  32244. done(true);
  32245. this.updateDepthTex(this.currentPano)
  32246. }, onUpdate:(progress)=>{
  32247. //console.log('uniforms progress',progress)
  32248. this.cube.material.uniforms.progress.value = progress
  32249. viewer.scene.pointclouds.forEach(e=>{
  32250. e.material.uniforms.progress.value = progress
  32251. })
  32252. },
  32253. cancelFun:()=>{ done(false, true) },
  32254. Easing:easeName
  32255. })
  32256. //duration > 0 && (this.flying = true) //再写一遍 防止cancel其他项目导致flying为false
  32257. } */
  32258. var _onUpdate = progress => {
  32259. this.cube.material.uniforms.progress.value = progress;
  32260. viewer.scene.pointclouds.forEach(e => {
  32261. e.material.uniforms.progress.value = progress;
  32262. });
  32263. };
  32264. var fly = () => {
  32265. var startProgress = toPano.progress = toPano.progress || 0;
  32266. var loadNextProgress = MathUtils.clamp(1 - 2.5 / dis, 0.3, 0.8);
  32267. //console.log(loadNextProgress, (1-loadNextProgress) * dis )
  32268. this.dispatchEvent({
  32269. type: 'flyToPano',
  32270. toPano
  32271. });
  32272. viewer.scene.view.setView({
  32273. position: endPosition,
  32274. target,
  32275. quaternion: toPano.quaternion,
  32276. duration: toPano.duration,
  32277. onUpdate: (progress_, delta) => {
  32278. var progress = startProgress + progress_ * (1 - startProgress);
  32279. var currentSpeed;
  32280. if (progress_ != 1 && progress_ != 0) {
  32281. // 1的时候不准,往往偏小, 0的时候速度为0,也不记录
  32282. currentSpeed = (progress - toPano.progress) * dis / delta; //记录下当前速度,当变为匀速时可以过渡到flySpeed
  32283. } else {
  32284. currentSpeed = toPano.currentSpeed || 0;
  32285. }
  32286. toPano.currentSpeed = currentSpeed;
  32287. toPano.progress = progress;
  32288. //console.log('progress_', progress_, 'delta',delta , 'progress', progress/*, 'currentSpeed', currentSpeed, */ )
  32289. if (progress > loadNextProgress && toPano.easeName == 'linearTween' && currentSpeed) {
  32290. // 减速. 如果仅旋转就不停止
  32291. //console.log('减速', /* currentSpeed , */progress_ )
  32292. toPano.easeName = 'easeOutSine';
  32293. var restDis = (1 - progress) * dis;
  32294. toPano.duration = Math.PI / 2 * restDis / currentSpeed; // 这样能保证初始速度为currentSpeed
  32295. viewer.scene.view.cancelFlying('all', false); //为了防止执行cancelFun先主动cancel
  32296. toPano.flyCount = 2;
  32297. fly(toPano);
  32298. }
  32299. _onUpdate(progress);
  32300. },
  32301. callback: () => {
  32302. if (!config.atPano.pointUsePanoTex) {
  32303. viewer.scene.pointclouds.forEach(e => {
  32304. e.material.stopProjectedPanos();
  32305. });
  32306. }
  32307. this.lastPano = this.currentPano; //记录,调试
  32308. this.currentPano = pano;
  32309. this.nextPano = null;
  32310. if (Potree.settings.displayMode == 'showPanos') {
  32311. viewer.scene.pointclouds.forEach(e => {
  32312. Potree.Utils.updateVisible(e, 'displayMode', pointcloudVisi);
  32313. });
  32314. }
  32315. done(true);
  32316. this.updateDepthTex(this.currentPano); //删除dispose的depthTex
  32317. },
  32318. cancelFun: () => {
  32319. done(false, true);
  32320. },
  32321. Easing: toPano.easeName,
  32322. ignoreFirstFrame: toPano.flyCount != 2 //变换transition时不停一帧
  32323. });
  32324. };
  32325. if (Potree.settings.displayMode == 'showPanos') {
  32326. setTimeout(fly, 40); //更新geo后缓冲
  32327. } else {
  32328. fly();
  32329. }
  32330. //console.log('flyToPano:', toPano.pano.id)
  32331. }
  32332. beforeFlyToPano(toPano) {
  32333. if (this.currentPano != toPano.pano) {
  32334. if (Potree.settings.displayMode == 'showPanos') {
  32335. this.resetHighMap();
  32336. }
  32337. this.smoothZoomTo(toPano.zoomLevel || 1, toPano.duration / 2);
  32338. }
  32339. }
  32340. /* updateCube(pano0, pano1){
  32341. if(Potree.settings.displayMode != 'showPanos')return
  32342. if(!viewer.scene.pointclouds.some(e=>!e.hasDepthTex)) return this.updateCube2(pano0, pano1) //都hasDepthTex的话
  32343. let useBound = (bound, size)=>{
  32344. size = size || bound.getSize(new THREE.Vector3)
  32345. let center = bound.getCenter(new THREE.Vector3)
  32346. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  32347. this.cube.scale.copy(size)
  32348. this.cube.position.copy(center)
  32349. }
  32350. let getPanoBound = (pano)=>{//因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
  32351. let panoBound = new THREE.Box3
  32352. panoBound.expandByPoint(pano.position)
  32353. panoBound.expandByVector(new THREE.Vector3(10,10,10));//give pano a margin
  32354. return pano.pointcloud.bound.clone().union(panoBound)
  32355. }
  32356. let getDis = (bound1, bound2)=>{ //获取bound1边界到bound2边界距离
  32357. if(bound1.intersectsBox(bound2))return 0
  32358. let center1 = bound1.getCenter(new THREE.Vector3)
  32359. let center2 = bound2.getCenter(new THREE.Vector3)
  32360. let dis = center1.distanceTo(center2)
  32361. let dis1 = bound1.distanceToPoint(center2)
  32362. let dis2 = bound2.distanceToPoint(center1)
  32363. return dis1 + dis2 - dis
  32364. }
  32365. if(pano1){//过渡
  32366. if(pano0.pointcloud == pano1.pointcloud){//同一个数据集内的过渡
  32367. useBound(getPanoBound(pano0))
  32368. }else{//非同一个数据集内的过渡
  32369. let bound = getPanoBound(pano0).union(getPanoBound(pano1))
  32370. if(getDis(pano0.pointcloud.bound, pano1.pointcloud.bound) < 100){
  32371. useBound(bound)
  32372. }else{//如果两个数据集boundingbox距离大于这个距离,扩大一下,防止精度问题导致失真//对很远的数据集似乎没有什么用
  32373. let size = bound.getSize(new THREE.Vector3)
  32374. let max = Math.max(size.x, size.y, size.z)
  32375. size.set(max,max,max)
  32376. useBound(pano0.pointcloud.bound.clone().union(pano1.pointcloud.bound), size)
  32377. }
  32378. }
  32379. }else{
  32380. useBound(getPanoBound(pano0)) //假定一个数据集不会太大,否则会造成失真,且bump时移动距离看起来很小。或者可以考虑用固定大小
  32381. }
  32382. } */
  32383. getIntersect(pano, dir, origin) {
  32384. if (pano && pano.pointcloud.hasDepthTex) {
  32385. return this.depthSampler.sample({
  32386. dir
  32387. }, pano, true);
  32388. } else {
  32389. origin = origin || pano.position;
  32390. return viewer.inputHandler.getIntersect({
  32391. viewport: viewer.inputHandler.hoverViewport,
  32392. onlyGetIntersect: true,
  32393. usePointcloud: true,
  32394. point: origin.clone().add(dir),
  32395. cameraPos: origin
  32396. });
  32397. }
  32398. }
  32399. /* updateCube(pano0, pano1){//增加细分的版本,且垂直方向上也分多个
  32400. if(Potree.settings.displayMode != 'showPanos')return
  32401. console.log('updateCube',pano0.id, pano1&&pano1.id)
  32402. let f = (bound, size)=>{
  32403. size = size || bound.getSize(new THREE.Vector3)
  32404. let center = bound.getCenter(new THREE.Vector3)
  32405. size.max(new THREE.Vector3(HighMapCubeWidth,HighMapCubeWidth,HighMapCubeWidth))
  32406. this.cube.scale.copy(size)
  32407. this.cube.position.copy(center)
  32408. }
  32409. this.cube.geometry.dispose();
  32410. if(pano1){//过渡
  32411. let count1, count2;
  32412. let panoIndex = 0
  32413. let add = (pano, dir )=>{
  32414. let getPI = function(index, panoIndex_){
  32415. if(panoIndex_ == void 0) panoIndex_ = panoIndex
  32416. return (count1 * count2 + 2 ) * panoIndex_ + index + 2
  32417. }
  32418. let minZ, maxZ
  32419. minZ = pano.floorPosition.z
  32420. {//天花板高度值
  32421. //用三个间隔120度散开,和中心垂直线成一定夹角的三个向量去求 最高高度 (不求平均的原因:万一是0不好算)
  32422. let rotMat = new THREE.Matrix4().makeRotationX(THREE.Math.degToRad(40))// 角度不能小于天花板中空的半径,大概就是0.2*Math.PI=36度
  32423. let dir1 = new THREE.Vector3(0,0,1).applyMatrix4(rotMat)
  32424. let rotMat1 = new THREE.Matrix4().makeRotationZ(Math.PI*2 / 3);
  32425. let rotMat2 = new THREE.Matrix4().makeRotationZ(-Math.PI*2 / 3);
  32426. let dir2 = dir1.clone().applyMatrix4(rotMat1)
  32427. let dir3 = dir1.clone().applyMatrix4(rotMat2)
  32428. let zs = [dir1,dir2,dir3].map(dir_=>{
  32429. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  32430. let z = intersect ? intersect.location.z : pano.position.z
  32431. return z
  32432. })
  32433. zs.sort((a,b)=>{return b-a});//得最大值
  32434. maxZ = zs[0]
  32435. let min = pano.position.z + 1
  32436. if(maxZ < pano.position.z + 0.04){//户外
  32437. maxZ = pano.position.z + 50
  32438. }
  32439. maxZ = Math.max(min,maxZ)
  32440. console.log(pano.id, 'maxZ:',maxZ )
  32441. console.log(pano.id, 'minZ:',minZ )
  32442. }
  32443. [maxZ, minZ ].forEach(z=>{
  32444. posArr.push(pano.position.clone().setZ(z))
  32445. })
  32446. const angle = Math.PI/8
  32447. let getDir = (angle_)=>{
  32448. let rotMat = new THREE.Matrix4().makeRotationZ(angle_)
  32449. return dir.clone().applyMatrix4(rotMat)
  32450. }
  32451. let dirs = [ getDir(angle*4), getDir(angle*3), getDir(angle*2), getDir(angle), dir.clone(), getDir(-angle) , getDir(-angle*2), getDir(-angle*3), getDir(-angle*4) ]; // 夹角总和180度
  32452. count1 = dirs.length
  32453. dirs.forEach((dir, index)=>{//获取在这个方向上和墙体intersect的最远距离,使用中、上、下三个方向
  32454. let dirs_ = [
  32455. dir.clone().setZ(Math.tan(THREE.Math.degToRad(30))).normalize(),
  32456. dir.clone().setZ(Math.tan(THREE.Math.degToRad(15))).normalize(),
  32457. dir.clone(), // 水平方向
  32458. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(15))).normalize(),
  32459. dir.clone().setZ(-Math.tan(THREE.Math.degToRad(30))).normalize(),
  32460. ];
  32461. count2 = dirs_.length
  32462. dirs_.forEach((dir_, i) =>{
  32463. let intersect = this.depthSampler.sample( {dir: dir_}, pano, true )
  32464. let location
  32465. if(!intersect){ //超级远
  32466. let distance = 100
  32467. location = dir_.clone().multiplyScalar(distance).add(pano.position)
  32468. intersect = {distance,location}
  32469. }
  32470. //intersect.distance
  32471. location = intersect.location.clone()
  32472. let shouldZ// = THREE.Math.clamp(intersect.location.z, minZ, maxZ);
  32473. let needShrink = false
  32474. if(i == 0){//最上方的点高度直接等于天花板
  32475. shouldZ = maxZ
  32476. if(location.z<maxZ)location.z = maxZ
  32477. else needShrink = true
  32478. }else if(i == count2-1){//最下方的点高度直接等于地板
  32479. shouldZ = minZ
  32480. if(location.z>minZ)location.z = minZ
  32481. else needShrink = true
  32482. }
  32483. if(needShrink ){//需要在保持dir_不变的情况下修改z
  32484. let len = (shouldZ - pano.position.z) / (intersect.location.z - pano.position.z) * intersect.distance
  32485. location = dir_.clone().multiplyScalar(len).add(pano.position)
  32486. }
  32487. posArr.push(location)
  32488. if(index!=0 && i!=0){//加入一块四方面
  32489. let curIndex = getPI(count2 * index + i);
  32490. faceArr.push([curIndex-1, curIndex-count2-1, curIndex-count2],
  32491. [curIndex-1, curIndex, curIndex-count2])
  32492. }
  32493. })
  32494. if(index!=0){
  32495. let top = -2;
  32496. let btm = -1
  32497. faceArr.push([getPI(count2*(index-1) ), getPI(count2*index ), getPI(top) ])//天花板扇形
  32498. faceArr.push([getPI(count2*index-1), getPI(count2*(index+1)-1), getPI(btm) ] )//地板扇形
  32499. }else{
  32500. //加入和另一个pano连接的其中一个侧边
  32501. let panoIndex2 = (panoIndex + 1) % 2;
  32502. for(let i=1;i<count2;i++){
  32503. faceArr.push([getPI(i-1), getPI(i), getPI((count1-1)*count2 +i, panoIndex2)],
  32504. [getPI(i-1), getPI((count1-1)*count2+i , panoIndex2) , getPI((count1-1)*count2+i-1 ,panoIndex2)])
  32505. }
  32506. faceArr.push([getPI(0), getPI((count1-1)*count2), getPI(0, panoIndex2)])//加入顶部的一半
  32507. faceArr.push([getPI(count2-1), getPI(count1*count2-1), getPI(count2-1, panoIndex2)])//加入底部的一半
  32508. }
  32509. });
  32510. panoIndex ++
  32511. }
  32512. let posArr = [];
  32513. let faceArr = []
  32514. //两点连线的水平向量
  32515. let vec = new THREE.Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize()
  32516. add(pano0, vec)
  32517. add(pano1, vec.negate())
  32518. let geo = MeshDraw.createGeometry(posArr, faceArr)
  32519. this.cube.geometry = geo
  32520. this.cube.scale.set(1,1,1);
  32521. this.cube.position.set(0,0,0)
  32522. }else{
  32523. this.cube.geometry = new THREE.BoxBufferGeometry(1,1,1,1)
  32524. f(pano0.pointcloud.bound)
  32525. }
  32526. } */
  32527. isNeighbour(pano0, pano1) {
  32528. var {
  32529. dontCompute,
  32530. onlyUseTex,
  32531. computeDirFirst,
  32532. computeTwoDir
  32533. } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  32534. //是否之间没有遮挡(在加载visibles之前,自己算) 最好pano0是currentPano
  32535. if (!pano0 || !pano1) return;
  32536. var margin = 0.1;
  32537. var map0 = this.neighbourMap[pano0.id]; //主
  32538. var map1 = this.neighbourMap[pano1.id]; //副
  32539. /* if(map0[pano1.id] != void 0){
  32540. ifNeighbour = map0[pano1.id]
  32541. }
  32542. if(!ifNeighbour && map1[pano0.id] != void 0){
  32543. ifNeighbour = map1[pano0.id]
  32544. } */
  32545. var ifNeighbour = map1[pano0.id] == void 0 ? map0[pano1.id] : map0[pano1.id] && map1[pano0.id]; //如果map1没计算就只要返回map0
  32546. var dis = pano0.position.distanceTo(pano1.position);
  32547. if (math.closeTo(dis, 0)) {
  32548. //两个点相同
  32549. ifNeighbour = map1[pano0.id] = map0[pano1.id] = true;
  32550. return true;
  32551. }
  32552. if (dontCompute) return ifNeighbour;
  32553. var logSids = [/* '1739923562316697600|3','1739923562316697600|2' */];
  32554. var ifLog = pano0.sid == logSids[0] && pano1.sid == logSids[1] || pano0.sid == logSids[1] && pano1.sid == logSids[0];
  32555. if (ifLog) {
  32556. console.log(2);
  32557. }
  32558. var ifSheltered = (mainPano, subPano) => {
  32559. //该点前方近处是否都被遮挡 。 为了防止杂点干扰,多个方向探测
  32560. var vec = new Vector3().subVectors(subPano.position, mainPano.position).normalize();
  32561. var getDir = (angle_, upDown) => {
  32562. //基于vec的方向 向左向右旋转
  32563. //if(upDown) vec.clone().applyAxisAngle(new THREE.Vector3(1, 0, 0), upDown);
  32564. return vec.clone().applyAxisAngle(new Vector3(0, 0, 1), angle_);
  32565. };
  32566. var minScore = 0.25;
  32567. var angles = [20, 16, 12.5, 10, 8, 6, 4.5, 3, 1, -1, -3, -4.5, -6, -8, -10, -12.5, -16, -20]; //水平方向角度 3之间有较大概率杂点, 3以外一部分有较大概率有空隙所以紧凑点
  32568. var wellCount = 0;
  32569. var seccess = [];
  32570. for (var i = 0; i < angles.length; i++) {
  32571. var rad = MathUtils.degToRad(angles[i]);
  32572. var dir = getDir(rad);
  32573. var color = void 0;
  32574. var intersectPoint = viewer.images360.depthSampler.sample({
  32575. dir
  32576. }, mainPano, true);
  32577. if (!intersectPoint || intersectPoint.distance * Math.cos(Math.abs(rad)) /* + margin */ > dis) {
  32578. //投影在vec方向的长度不超过漫游点间距
  32579. wellCount++;
  32580. seccess.push(angles[i]);
  32581. color = new Color('#0f8');
  32582. }
  32583. ifLog && addLine(mainPano.position, dir, dis, color);
  32584. }
  32585. //console.log('ifSheltered')
  32586. if (ifLog) {
  32587. console.log('ifSheltered seccess', seccess, 'id:', mainPano.originID, subPano.originID);
  32588. }
  32589. var score = wellCount / angles.length;
  32590. if (score >= minScore) {
  32591. //合格个数
  32592. return score;
  32593. }
  32594. };
  32595. /*
  32596. 识别一定角度范围内是否有遮挡时
  32597. 几种奇葩的情况:
  32598. 1 在墙的两边的但是墙是倾斜的漫游点:
  32599. A /
  32600. /
  32601. / B
  32602. 从B出发和BA成20度的射线和墙面的交点会远于A,导致识别为无遮挡。
  32603. 所以还是改为识别范围内多个深度图像素, 合格像素个数占比 至少要大于50%,因为半边墙壁是50%
  32604. 如SG-9UsbysDufBw&formal&test 的 6、9点。 而SS-GTmFBp1JN8k&formal&test的 2、3两点是人物遮挡
  32605. 2 可以通行,但是右边是墙,右边的都检测失败,左侧的又有一些杂点,导致成功dir个数很低。
  32606. 所以minRatio 要降低于0.5
  32607. */
  32608. //三个方向 : position0到position1, position0到floorPosition1, position1到floorPosition0。 只要有一个满足ifNeighbour就为true。 不过为了不使sampler总换图,先只考虑从主pano到副pano的方向
  32609. var getNeighbour = (mainPano, subPano) => {
  32610. var dirPoints = [[subPano.position, mainPano.position]]; //注: 点A能到B不代表点B能到A,因为拍摄时物体会移动,或点位相对位置不对,无论是否是意外遮挡都且记下来,反正最后只要有一方可行就算相邻。
  32611. if (dis < 20) {
  32612. //在远处去掉对floorPosition的判断
  32613. dirPoints.push([subPano.floorPosition.clone().add(new Vector3(0, 0, 0.1)), mainPano.position]);
  32614. }
  32615. if (dis < 12) {
  32616. //为了防止楼梯拐角、杂点遮挡。 尽量只在穿墙时不可通行
  32617. dirPoints.push([subPano.position.clone().add(new Vector3(0, 0, 0.8)), mainPano.position]);
  32618. var normal = math.getNormal2d({
  32619. p1: subPano.position,
  32620. p2: mainPano.position
  32621. }).multiplyScalar(0.3); //左右方向
  32622. dirPoints.push([subPano.position.clone().add(new Vector3(normal.x, normal.y, 0.1)), mainPano.position]);
  32623. dirPoints.push([subPano.position.clone().add(new Vector3(-normal.x, -normal.y, 0.1)), mainPano.position]);
  32624. }
  32625. //console.warn('getNeighbour', mainPano.id,subPano.id)
  32626. for (var i = 0; i < dirPoints.length; i++) {
  32627. var dir = new Vector3().subVectors(dirPoints[i][0], dirPoints[i][1]).normalize();
  32628. var intersectPoint = viewer.images360.depthSampler.sample({
  32629. dir
  32630. }, mainPano, true, true);
  32631. if (!intersectPoint || intersectPoint.distance + margin > dirPoints[i][0].distanceTo(dirPoints[i][1])) {
  32632. //if(i>2)console.log('haha',i,'id:',mainPano.id,subPano.id)
  32633. return true;
  32634. }
  32635. }
  32636. };
  32637. //if(!ifNeighbour && (map0[pano1.id] == void 0 || computeTwoDir && !map0[pano1.id] && map1[pano0.id] == void 0 )) {//主方向为空且不为邻居
  32638. if (pano0.pointcloud.hasDepthTex || pano1.pointcloud.hasDepthTex) {
  32639. if (computeTwoDir ? map0[pano1.id] == void 0 || map1[pano0.id] == void 0 : map0[pano1.id] == void 0 && map1[pano0.id] !== false) {
  32640. //2024.3.20改为必须两个方向都为true才行。 因为如果两个点分别在两个数据集相距很远,A确定有墙无法到B,B朝A看 没有B所在的数据集点云遮挡,因深度图不会包含别的数据集的点,故深度图探测到A处为无遮挡,就会导致会飞到遥远的A。 即使在同一个数据集,因为点云可以编辑位置,导致AB相对位置错误,也要避免这种情况可以互相乱走。 缺点是更容易被杂点阻挡,所以需要ifShelter降低阈值。
  32641. if (map0[pano1.id] == void 0 && pano0.depthTex) {
  32642. var is = getNeighbour(pano0, pano1);
  32643. map0[pano1.id] = !!is;
  32644. }
  32645. if (computeTwoDir && map0[pano1.id] && pano1.depthTex && map1[pano0.id] == void 0) {
  32646. //computeTwoDir : 允许反向计算,即可以读取另一张的深度图 。 如果map0为false,map1就不用计算,只需要等待计算ifShelter
  32647. var _is = getNeighbour(pano1, pano0);
  32648. map1[pano0.id] = !!_is;
  32649. }
  32650. if (map0[pano1.id] === false || map1[pano0.id] === false) {
  32651. if (dis < 20) {
  32652. //再检查下 只要两方都没有被完全遮挡就算可通行 针对杂点较多的情况
  32653. if (pano0.depthTex && pano1.depthTex) {
  32654. ifNeighbour = false;
  32655. var a = ifSheltered(pano0, pano1);
  32656. if (a) {
  32657. var b = ifSheltered(pano1, pano0);
  32658. if (b && a + b >= 0.6) {
  32659. ifNeighbour = true;
  32660. }
  32661. }
  32662. map0[pano1.id] = map1[pano0.id] = ifNeighbour;
  32663. }
  32664. } else {
  32665. //标记为无需再计算, 因已经失败。 当map0和map1都不为void 0后就无法再计算了。
  32666. if (map0[pano1.id] === void 0) map0[pano1.id] = 0;
  32667. if (map1[pano0.id] === void 0) map1[pano0.id] = 0;
  32668. }
  32669. }
  32670. ifNeighbour = map1[pano0.id] == void 0 ? map0[pano1.id] : map0[pano1.id] && map1[pano0.id]; //如果map1没计算就只要返回map0
  32671. if (ifLog) {
  32672. console.log('isNeighbour', pano0.id + "(" + pano0.originID + ")", pano1.id + "(" + pano1.originID + ")", map0[pano1.id], map1[pano0.id]);
  32673. }
  32674. }
  32675. } else if (!onlyUseTex && !ifNeighbour) {
  32676. //使用点云判断(有深度贴图时不会执行到这)
  32677. var inDirection = () => {
  32678. var dir = new Vector3().subVectors(pano1.position, pano0.position).normalize();
  32679. var dis = pano1.position.distanceTo(pano0.position);
  32680. var fov = MathUtils.degToRad(viewer.mainViewport.camera.fov);
  32681. var hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera, true);
  32682. var hov = Math.min(fov, hfov);
  32683. var max = Math.cos(MathUtils.degToRad(10));
  32684. var min = Math.cos(MathUtils.degToRad(40));
  32685. if (this.getDirection().dot(dir) > MathUtils.clamp(Math.cos(hov / 2) * dis / 10, min, max)) {
  32686. //距离越远要求和视线角度越接近
  32687. return true;
  32688. }
  32689. };
  32690. if (computeDirFirst) {
  32691. //先计算方向,防止重复计算ifBlockedByIntersect
  32692. if (inDirection()) {
  32693. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({
  32694. point: pano1.position,
  32695. margin,
  32696. cameraPos: pano0.position
  32697. });
  32698. }
  32699. } else {
  32700. ifNeighbour = !viewer.inputHandler.ifBlockedByIntersect({
  32701. point: pano1.position,
  32702. margin,
  32703. cameraPos: pano0.position
  32704. });
  32705. if (ifNeighbour && !inDirection()) {
  32706. ifNeighbour = undefined; //不确定
  32707. }
  32708. }
  32709. map0[pano1.id] = map1[pano0.id] = ifNeighbour ? 'byCloud' : ifNeighbour; //写简单点
  32710. }
  32711. if (map0[pano1.id] && map1[pano0.id]) {
  32712. pano0.neighbours.includes(pano1) || pano0.neighbours.push(pano1);
  32713. pano1.neighbours.includes(pano0) || pano1.neighbours.push(pano0);
  32714. }
  32715. return ifNeighbour;
  32716. }
  32717. bump(direction) {
  32718. //撞墙弹回效果
  32719. if (!this.bumping && !this.latestToPano) {
  32720. var distance = Potree.settings.displayMode == 'showPanos' ? 0.15 : 0.12; //感觉点云模式比全景模式更明显,所以降低
  32721. var currentPos = this.position.clone();
  32722. var endPosition = new Vector3().addVectors(this.position, direction.clone().multiplyScalar(distance));
  32723. var duration = 150;
  32724. viewer.scene.view.setView({
  32725. position: endPosition,
  32726. duration,
  32727. callback: () => {
  32728. viewer.scene.view.setView({
  32729. position: currentPos,
  32730. duration: duration * 5,
  32731. callback: () => {
  32732. this.bumping = false;
  32733. //this.dispatchEvent('cameraMoveDone')
  32734. },
  32735. Easing: 'easeInOutSine',
  32736. cancelFun: () => {
  32737. this.bumping = false;
  32738. }
  32739. });
  32740. this.bumping = true;
  32741. },
  32742. cancelFun: () => {
  32743. this.bumping = false;
  32744. },
  32745. Easing: 'easeInOutSine'
  32746. });
  32747. this.bumping = true;
  32748. }
  32749. //备注:将4dkk中的‘前后方向变化fov、左右方向移动镜头’ 都改为移动镜头。 因为这里无法判断左右离壁距离。
  32750. }
  32751. flyToPanoClosestToMouse() {
  32752. /* if (Date.now() - this.mouseLastMoveTime > 50) {
  32753. //this.intersect = this.getMouseIntersect();
  32754. this.intersect && this.updateClosestPano(this.intersect);
  32755. } */
  32756. if (!Potree.settings.ifShowMarker) {
  32757. //不显示marker的时候mousemove没更新鼠标最近点所以更新
  32758. this.updateClosestPano(viewer.inputHandler.intersect);
  32759. }
  32760. //console.log('flyToPanoClosestToMouse',this.closestPano)
  32761. if (this.closestPano) {
  32762. var pano = this.closestPano;
  32763. return this.flyToPano({
  32764. pano,
  32765. easeName: this.isAtPano() ? 'linearTween' : 'easeInOutQuad'
  32766. });
  32767. }
  32768. var direction = this.viewer.inputHandler.getMouseDirection().direction;
  32769. this.flyDirection(direction);
  32770. }
  32771. flyDirection(direction, option1, option2, byKey) {
  32772. if (viewer.mainViewport.view.isFlying()) {
  32773. // closestPanoInDirection函数耗时长,飞行时运行会卡顿(如果以后加无缝过渡再说)
  32774. return;
  32775. }
  32776. var deferred = $.Deferred();
  32777. //this.history.invalidate();
  32778. var panoSet = this.closestPanoInDirection(direction, option1, option2, byKey);
  32779. if (panoSet) {
  32780. this.flyToPano({
  32781. pano: panoSet,
  32782. callback: deferred.resolve.bind(deferred, !0)
  32783. });
  32784. } else {
  32785. //如果离数据集较远,转动也很难找到点云,就飞到就近点:
  32786. if (Potree.settings.displayMode == 'showPointcloud') {
  32787. var po = viewer.scene.pointclouds.find(e => e.visibleNodes.some(a => a.getLevel() > Math.ceil(e.maxLevel * 0.15))); //虽然当点云在前方很远的地方也可能符合
  32788. if (!po) {
  32789. //无可见点云
  32790. //console.log('no visi cloud')
  32791. if (!this.panos.length) {
  32792. //如果场景中没有漫游点,如SG-t-XPf1k9pv3Zg 点击后回到可见区域
  32793. if (viewer.scene.pointclouds.length == 0) return;
  32794. var map = new Map();
  32795. var clouds = viewer.scene.pointclouds.filter(e => e.root.geometryNode);
  32796. clouds.forEach(e => map.set(e, e.bound.distanceToPoint(this.position)));
  32797. clouds.sort((a, b) => map.get(a) - map.get(b));
  32798. viewer.flyToDataset({
  32799. focusOnPoint: true,
  32800. pointcloud: clouds[0],
  32801. duration: 500
  32802. }); //飞最近的一个点云
  32803. return deferred.promise();
  32804. }
  32805. this.flyToPano({
  32806. pano: this.findNearestPano(),
  32807. duration: 500,
  32808. callback: deferred.resolve.bind(deferred, !0)
  32809. });
  32810. return deferred.promise();
  32811. }
  32812. }
  32813. this.bump(direction);
  32814. deferred.resolve(!1);
  32815. }
  32816. return deferred.promise();
  32817. }
  32818. closestPanoInDirection(direction, option1, option2, byKey) {
  32819. return this.rankedPanoInDirection(0, direction, option1, option2, byKey);
  32820. }
  32821. rankedPanoInDirection(t, direction, option1, option2, byKey) {
  32822. //此direction为mouseDirection,是否需要加上相机角度的权重
  32823. var startTime = Date.now();
  32824. var panoSet = {
  32825. pano: null,
  32826. candidates: [] //缓存顺序--如果需要打印的话
  32827. };
  32828. t || (t = 0);
  32829. option1 = void 0 !== option1 ? option1 : 0.6; //.75; 2024.3.22改小,也就是可以走的角度范围增加,主要针对像山野那种很大的场景,不知道可以走哪,容易因角度范围内无近点而飞到远处的情况。但不能太小,总是横着走路
  32830. var o = option2 ? "angle" : "direction";
  32831. var floor = viewer.modules.SiteModel.currentFloor;
  32832. var entity = viewer.modules.SiteModel.inEntity;
  32833. var getHeightDis = pano => {
  32834. if (floor && !floor.panos.includes(pano) && pano.position.z < this.position.z) {
  32835. //若是上方的漫游点,就正常走。因为一般不会点击天花板。
  32836. return this.position.z - pano.position.z;
  32837. } else {
  32838. return 0;
  32839. }
  32840. };
  32841. var disSquareMap = new Map();
  32842. this.panos.forEach(pano => {
  32843. var dis2 = pano.position.distanceToSquared(this.position); //距离目标点
  32844. disSquareMap.set(pano, dis2);
  32845. });
  32846. var changeTexCount = 0,
  32847. maxWaitDur = 300;
  32848. //maxSamplerChangeTex = THREE.Math.clamp( maxWaitDur / Potree.timeCollect.depthSampler.median, 2, 10) //计算换贴图最大数目
  32849. var request = [
  32850. //必要条件
  32851. Images360.filters.not(this.currentPano), Images360.filters.isEnabled(),
  32852. //Images360.filters.inFloorDirection( this.position, direction, option1 ), //原先用inPanoDirection,但容易穿楼层,当mouse较低或较高 //因不束缚纵向所以可能往相反反向
  32853. pano => {
  32854. /* let isNeighbour = this.isNeighbour(this.currentPano, pano, true, true); //不计算的
  32855. if(isNeighbour == void 0){
  32856. let willChangeTex = pano.depthTex && !this.depthSampler.imgDatas.some(e=>e.pano == pano)
  32857. if(changeTexCount < maxSamplerChangeTex || !willChangeTex ){
  32858. isNeighbour = this.isNeighbour(this.currentPano, pano, false, true);//计算
  32859. if(willChangeTex && isNeighbour != void 0) changeTexCount++
  32860. }else{
  32861. if(disSquareMap.get(pano) < 500)return true //因为费时,超过一定个数就不计算了,距离近的话先可通行。
  32862. }
  32863. } */
  32864. // 不会再changeTex了
  32865. var isNeighbour = this.isNeighbour(this.currentPano, pano, {
  32866. onlyUseTex: true
  32867. });
  32868. if (isNeighbour || pano.noNeighbour && disSquareMap.get(pano) < 200) {
  32869. //在靠近孤立点时可以通行。但是不好把握这个距离,太远的话很多地方都会不小心到孤立点,太近的话可能永远到不了。
  32870. return true;
  32871. }
  32872. }
  32873. /* (pano)=>{ //防止不小心穿越地板到下一层, 尽量走楼梯,实在没有楼梯或楼梯漫游点稀疏的话就通过楼层按钮。
  32874. let dis = getHeightDis(pano)
  32875. //console.log('getHeightDis',pano.id,dis)
  32876. if(dis < 3){//不能超过最大高度差( 最大高度差暂定为接近一层楼的高度。)(最好的解决方案是设置漫游可行)
  32877. return true
  32878. }else{
  32879. return this.isNeighbour(this.currentPano, pano)
  32880. }
  32881. } */];
  32882. if (!byKey) {
  32883. request.push(Images360.filters.inPanoDirection(this.position, this.getDirection(), option1 /* , true */)); //垂直方向上再稍微限制一下, 要接近视线方向,避免点击前方时因无路而到下一楼。但不能太高,否则楼梯上稍微朝下点击都到不了上方。之所以使用视线方向是因为镜头方向比鼠标方向目的性更强。
  32884. }
  32885. var list = [
  32886. //决胜项目
  32887. pano => {
  32888. return -disSquareMap.get(pano);
  32889. }, Images360.scoreFunctions[o](this.position, direction, true), pano => {
  32890. var neighbour = this.isNeighbour(this.currentPano, pano, {
  32891. dontCompute: true,
  32892. isNeighbour: true
  32893. }); //不计算的
  32894. return neighbour ? directionFactor : 0;
  32895. }
  32896. /* (pano)=>{//尽量不穿越地板到下一层
  32897. let dis = getHeightDis(pano)
  32898. return -dis * directionFactor * 0.1;
  32899. }, */
  32900. /* (pano)=>{ //尽量在一个建筑内行走,这样不易穿墙
  32901. let score = 0
  32902. if(entity ){
  32903. if(!entity.panos.includes(pano) ) score -= directionFactor * 0.01; //不能设置太高,否则会走不进大房间的小房间中,因为容易穿过小房间的一个门到另一个门外
  32904. if(!floor.panos.includes(pano)) {//避免穿楼层
  32905. let heightDiff = Math.abs(pano.position.z - this.position.z);
  32906. if(heightDiff > 2){
  32907. score -= directionFactor * 0.1 * heightDiff;
  32908. }
  32909. }
  32910. }
  32911. return score
  32912. } */];
  32913. if (!byKey && viewer.inputHandler.intersect && this.currentPano) {
  32914. //方便上下楼, 考虑panos之间的角度差
  32915. var pos1 = this.currentPano.floorPosition;
  32916. var vec1 = new Vector3().subVectors(viewer.inputHandler.intersect.location, pos1).normalize(); //应该只有atPano时才会执行到这吧?
  32917. list.push(function (pano) {
  32918. var pos2 = pano.floorPosition;
  32919. var vec2 = pos2.clone().sub(pos1).normalize();
  32920. return vec2.dot(vec1) * directionFactor * 4;
  32921. });
  32922. }
  32923. this.findRankedByScore(t, request, list, panoSet);
  32924. //console.log( 'costTime:',Date.now() - startTime)
  32925. return panoSet.pano;
  32926. }
  32927. findRankedByScore(e, t, i, n) {
  32928. n && (n.candidates = null,
  32929. //candidates 缓存顺序--如果需要打印的话
  32930. n.pano = null), e || (e = 0);
  32931. var r = Common.sortByScore(this.panos, t, i);
  32932. //console.log('findRankedByScore', r && r.map(u=>u.item.id + '| ' + math.toPrecision(u.score,4) + " | " + math.toPrecision(u.scores,4)))
  32933. return !r || 0 === r.length || e >= r.length ? null : (n && (n.candidates = r, n.pano = r[e].item), r[e].item);
  32934. }
  32935. updateClosestPano(intersect, state) {
  32936. //hover到的pano 大多数时候是null
  32937. var pano;
  32938. if (intersect instanceof Panorama) {
  32939. //漫游模式
  32940. pano = state ? intersect : null;
  32941. } else {
  32942. if (this.isAtPano() || this.bumping) {
  32943. return;
  32944. } else {
  32945. var filterFuncs = [];
  32946. intersect = intersect && intersect.location;
  32947. if (!intersect) return;
  32948. var sortFuncs = Potree.settings.editType != 'pano' ? [Images360.sortFunctions.floorDisSquaredToPoint(intersect)] : [Images360.sortFunctions.disSquaredToPoint(intersect)];
  32949. pano = Common.find(this.panos, filterFuncs, sortFuncs);
  32950. }
  32951. }
  32952. if (pano != this.closestPano) {
  32953. pano && (this.isPanoHover = !0);
  32954. this.closestPanoChanging(this.closestPano, pano); // 高亮marker
  32955. //console.log('closestPano '+ (pano ? pano.id : 'null' ))
  32956. this.closestPano = pano;
  32957. } else {
  32958. this.isPanoHover = !1;
  32959. }
  32960. }
  32961. closestPanoChanging(oldPano, newPano) {
  32962. if (!Potree.settings.ifShowMarker) return;
  32963. oldPano && oldPano.hoverOff({
  32964. byImages360: true
  32965. });
  32966. newPano && newPano.hoverOn({
  32967. byImages360: true
  32968. });
  32969. }
  32970. getTileDirection() {
  32971. //根据不同dataset的来存储
  32972. var vectorForward = viewer.scene.view.direction.clone();
  32973. var vectorForwards = viewer.scene.pointclouds.map(e => {
  32974. var inv = new Matrix4().copy(e.rotateMatrix).invert(); //乘上dataset的旋转的反转
  32975. var direction = vectorForward.clone().applyMatrix4(inv);
  32976. return {
  32977. datasetId: e.dataset_id,
  32978. direction: math.convertVector.ZupToYup(direction)
  32979. };
  32980. });
  32981. //return vectorForwards[0].direction
  32982. return {
  32983. datasetsLocal: vectorForwards,
  32984. vectorForward
  32985. };
  32986. }
  32987. update() {
  32988. //if(this.tileDownloader.started){
  32989. var vectorForwards = this.getTileDirection();
  32990. //vectorForwards = vectorForwards[0].direction
  32991. this.updateTileDownloader(tileArr, vectorForwards);
  32992. this.updatePanoRenderer(vectorForwards);
  32993. //}
  32994. this.updateZoomPano();
  32995. }
  32996. updateTileDownloader(t, vectorForward) {
  32997. var i = this.nextPano || this.currentPano;
  32998. if (i) {
  32999. this.tileDownloader.tilePrioritizer.updateCriteria(i, viewer.scene.view.position.clone(), vectorForward, t.length > 0 ? t : null), this.tileDownloader.processPriorityQueue = !0;
  33000. }
  33001. }
  33002. updatePanoRenderer(vectorForward) {
  33003. var i = this.nextPano || this.currentPano;
  33004. if (i) {
  33005. if (this.panoRenderer.hasQueuedTiles() && i) {
  33006. this.panoRenderer.updateDirection(vectorForward);
  33007. }
  33008. }
  33009. }
  33010. //等待部分加载完
  33011. checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, l) {
  33012. //console.log('checkAndWaitForTiledPanoLoad',pano.id)
  33013. if (!pano) {
  33014. console.error("Player.checkAndWaitForTiledPanoLoad() -> Cannot load texture for null pano.");
  33015. }
  33016. var vectorForward = this.getTileDirection();
  33017. if (!pano.isLoaded(basePanoSize)) {
  33018. iswait && viewer.waitForLoad(pano, function () {
  33019. //发送loading
  33020. return pano.isLoaded(basePanoSize);
  33021. });
  33022. /* var fov = {//test for direction 预加载的边缘有一丢丢不准确,尤其在相机倾斜时(4dkk也是)。
  33023. hFov: cameraLight.getHFOVForCamera(viewer.scene.getActiveCamera() ),
  33024. vFov: viewer.scene.getActiveCamera().fov
  33025. }//原先是null,不要求方向 */
  33026. var fov = null; //若不为null的话,因为可能可见范围的tile下载过了从而无法触发下载,然后得不到下载成功的消息,怎么办
  33027. pano.loadTiledPano( /* 1024 */basePanoSize, vectorForward, fov, isclear, l, null).done(function (e, t) {
  33028. callback1 && callback1(e, t);
  33029. }.bind(this)).fail(function (msg) {
  33030. callback2 && callback2(msg);
  33031. }.bind(this)).progress(function (e, t, i) {
  33032. progressCallback && progressCallback(e, t, i);
  33033. }.bind(this));
  33034. return !0;
  33035. }
  33036. }
  33037. fitPanoTowardPoint(o) {
  33038. //寻找最适合的点位
  33039. var point = o.point,
  33040. //相机最佳位置
  33041. target = o.target || o.point,
  33042. //实际要看的位置
  33043. require = o.require || [],
  33044. rank = o.rank || [],
  33045. force = o.force,
  33046. getAll = o.getAll,
  33047. bestDistance = o.bestDistance || 0,
  33048. sameFloor = o.sameFloor,
  33049. maxDis = o.maxDis,
  33050. dir = o.dir;
  33051. var camera = viewer.scene.getActiveCamera();
  33052. if (target && !dir) {
  33053. dir = new Vector3().subVectors(target, point).normalize();
  33054. }
  33055. var atFloor = sameFloor && viewer.modules.SiteModel.pointInWhichEntity(point, 'floor');
  33056. //if(o.floor)require.push(Panorama.filters.atFloor(o.floor))
  33057. var checkIntersect = o.checkIntersect;
  33058. var base = Math.max(300, viewer.bound.boundSize.length() * 3);
  33059. if (o.boundSphere) {
  33060. //只接受boundSphere
  33061. var aspect = 1; //size.x / size.y
  33062. var dis;
  33063. if (camera.aspect > aspect) {
  33064. //视野更宽则用bound的纵向来决定
  33065. dis = /* size.y */o.boundSphere.radius /* / 2 */ / MathUtils.degToRad(camera.fov / 2);
  33066. } else {
  33067. var hfov = cameraLight.getHFOVForCamera(camera, true);
  33068. dis = /* size.x */o.boundSphere.radius /* / 2 */ / (hfov / 2);
  33069. }
  33070. bestDistance = dis; //*0.8
  33071. }
  33072. var disSquareMap = new Map();
  33073. var bestDisSquared = bestDistance * bestDistance;
  33074. var maxDisSquared = maxDis && maxDis * maxDis;
  33075. this.panos.forEach(pano => {
  33076. var dis2 = pano.position.distanceToSquared(target); //距离目标点
  33077. disSquareMap.set(pano, dis2);
  33078. });
  33079. var panos = this.panos.sort((p1, p2) => {
  33080. return disSquareMap.get(p1) - disSquareMap.get(p2);
  33081. });
  33082. if (maxDisSquared) {
  33083. //热点超过最大距离不可见的
  33084. var panos2 = [],
  33085. _pano,
  33086. i = 0;
  33087. while (_pano = panos[i], disSquareMap.get(_pano) < maxDisSquared) {
  33088. panos2.push(_pano);
  33089. i++;
  33090. }
  33091. if (panos2.length == 0) return {
  33092. pano: _pano,
  33093. msg: 'tooFar'
  33094. }; //全部都大于maxDis, 就返回最近的
  33095. panos = panos2;
  33096. }
  33097. rank.push(pano => {
  33098. var dis1 = Math.abs(pano.position.distanceToSquared(point) - bestDisSquared); //距离最佳位置
  33099. disSquareMap.set(pano, dis1);
  33100. if (!target) {
  33101. return -dis1;
  33102. } else {
  33103. var dis2 = disSquareMap.get(pano);
  33104. if (o.gotoBestView) {
  33105. //忽略和当前视线的角度
  33106. return -(dis1 + dis2 * 0.3);
  33107. }
  33108. var vec2 = new Vector3().subVectors(target, pano.position).normalize();
  33109. var cos = dir.dot(vec2);
  33110. //let result = (- dis1 - Math.pow(dis2 , 1.5)) / (cos + 2) // cos+2是为了调整到1-3,
  33111. var result = (dis1 + dis2 * 0.3) * (-1 + cos * 0.9); //尽量贴近最佳位置的角度, 或贴近相机原来的角度 。尽量靠近最佳观测点,并且优先选择靠近目标点的位置.(注意cos的乘数不能太接近1,否则容易只考虑角度)
  33112. //Potree.Log(pano.id, dis1, dis2, cos, result,{font:{toFixed:2,fontSize:10}})
  33113. return result;
  33114. }
  33115. //注:热点最好加上法线信息,这样可以多加一个限制,尽量顺着热点像展示的方向。
  33116. }, pano => {
  33117. var score = 0;
  33118. if (pano.depthTex && checkIntersect) {
  33119. var intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true); //viewer.inputHandler.ifBlockedByIntersect({point:target, margin:0.1, cameraPos:pano})
  33120. if (intersect) {
  33121. score = 0;
  33122. } else {
  33123. score = base * 2;
  33124. }
  33125. } else {
  33126. score = base * 1.5; //没加载好的话,不管了 , 几乎当做无遮挡,否则容易到不了最近点
  33127. }
  33128. return score;
  33129. });
  33130. var g = Common.sortByScore(panos, require, rank);
  33131. // console.log(g)
  33132. /* let result1 = g && g.slice(0, 10)
  33133. if(result1){
  33134. g = Common.sortByScore(result1, [], [(e)=>{//避免遮挡
  33135. let pano = e.item;
  33136. let score = 0, log = ''
  33137. if(atFloor && atFloor.panos.includes(pano)){//如果不在任何一楼呢?
  33138. score += 600, log+='atFloor'
  33139. }
  33140. return {score, log}
  33141. }]);
  33142. if(g){
  33143. g.forEach(e=>{e.item = e.item.item})
  33144. }
  33145. console.log(g)
  33146. } */
  33147. var pano = g && g.length > 0 && g[0].item;
  33148. if (pano && checkIntersect) {
  33149. var intersect = !!viewer.ifPointBlockedByIntersect(target, pano.id, true);
  33150. if (intersect) {
  33151. return {
  33152. pano,
  33153. msg: 'sheltered'
  33154. };
  33155. }
  33156. }
  33157. //if(getAll)return g;
  33158. return pano;
  33159. //注:深度图有的位置会不准确,以至于会算出错误的遮挡、选择错误的pano,解决办法只能是移动下热点到更好的位置
  33160. }
  33161. //---------------scroll zoom ------------------------------------------
  33162. /* zoomIn = function() { //放大
  33163. this.zoomBy(1 + this.zoomSpeed);
  33164. }
  33165. zoomOut = function() {//缩小
  33166. this.zoomBy(1 - this.zoomSpeed);
  33167. } */
  33168. zoomBy(e, pointer) {
  33169. //以倍数
  33170. this.zoomTo(this.zoomLevel * e, pointer);
  33171. }
  33172. zoomTo(zoomLevel, pointer) {
  33173. //缩放到某绝对zoomLevel
  33174. var zoom = Potree.settings.zoom;
  33175. if (zoom.enabled) {
  33176. zoomLevel = MathUtils.clamp(zoomLevel, zoom.min, zoom.max);
  33177. //console.log(zoomLevel)
  33178. if (zoomLevel == this.zoomLevel) return;
  33179. this.zoomLevel = zoomLevel;
  33180. if (Potree.settings.panoZoomByPointer) {
  33181. //定点缩放:使当前鼠标所在的位置缩放后不变
  33182. var view = viewer.scene.view;
  33183. var originDir = viewer.scene.view.direction;
  33184. var oldPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  33185. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  33186. var newPointerDir = viewer.inputHandler.getMouseDirection(pointer).direction;
  33187. view.direction = oldPointerDir; //获取一下鼠标所在位置的yaw 和 pitch
  33188. var oldPitch = view.pitch,
  33189. oldYaw = view.yaw;
  33190. view.direction = newPointerDir;
  33191. var newPitch = view.pitch,
  33192. newYaw = view.yaw;
  33193. view.direction = originDir; //还原
  33194. viewer.scene.view.pitch -= newPitch - oldPitch;
  33195. viewer.scene.view.yaw -= newYaw - oldYaw;
  33196. } else {
  33197. viewer.setFOV(Potree.config.view.fov * (1 / this.zoomLevel));
  33198. }
  33199. }
  33200. }
  33201. zoomFovTo(fov) {
  33202. //通过fov来算zoomLevel
  33203. var zoomLevel = Potree.config.view.fov /* this.baseFov */ / fov;
  33204. this.zoomTo(zoomLevel);
  33205. }
  33206. smoothZoomTo(aimLevel) {
  33207. var dur = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  33208. var currentLevel = this.zoomLevel;
  33209. if (currentLevel == aimLevel) return;
  33210. var fun = progress => {
  33211. //progress > 1 && (progress = 1)
  33212. var level = currentLevel * (1 - progress) + aimLevel * progress;
  33213. this.zoomTo(level, !0);
  33214. };
  33215. transitions.start(fun, dur, null, null, 0, easing['easeInOutQuad']);
  33216. }
  33217. updateZoomPano() {
  33218. if (!this.panoRenderer.zoomPanoRenderingDisabled && Potree.settings.displayMode == 'showPanos') {
  33219. var currentPano = this.currentPano;
  33220. if (currentPano) {
  33221. var levelThreshold1 = Potree.settings.navTileClass == '1k' ? 1.3 : 1.7,
  33222. levelThreshold2 = 2;
  33223. var t = this.zoomLevel > levelThreshold1,
  33224. n = !(this.flying && this.nextPano && this.nextPano !== this.currentPano),
  33225. r = t && n;
  33226. this.tileDownloader.tilePrioritizer.setZoomingActive(r);
  33227. this.panoRenderer.setZoomingActive(r, currentPano, !0);
  33228. var o = (pano, ifZoom) => {
  33229. this.panoRenderer.resetRenderStatus(pano.id, !1, !0, this.qualityManager.getMaxNavPanoSize());
  33230. this.panoRenderer.clearAllQueuedUploadsForPano(pano.id);
  33231. this.panoRenderer.renderPanoTiles(pano.id, null, !1, !1);
  33232. pano.setZoomed(ifZoom);
  33233. };
  33234. if (r && (!currentPano.zoomed || this.qualityManager.zoomLevelResolution && this.qualityManager.zoomLevelResolution != '4k')) {
  33235. //needZoom
  33236. currentPano.zoomed || o(currentPano, !0);
  33237. if (Potree.settings.navTileClass == '1k' && Potree.settings.tileClass != '1k' && this.zoomLevel < levelThreshold2) {
  33238. this.panoRenderer.enableHighQuality(function () {
  33239. //开启2k
  33240. if (Potree.settings.tileClass != '4k') o(currentPano, !0);
  33241. }.bind(this));
  33242. } else {
  33243. this.panoRenderer.enableUltraHighQualityMode(function () {
  33244. //开启4k getMaxZoomPanoSize
  33245. this.qualityManager.useUltraHighResolutionPanos && (Potree.settings.zoom.max = Potree.config.ultraHighQualityMaxZoom);
  33246. o(currentPano, !0);
  33247. }.bind(this));
  33248. }
  33249. } else {
  33250. !t && currentPano.zoomed && o(currentPano, !1);
  33251. }
  33252. if (r && Potree.settings.navTileClass == '1k' && Potree.settings.tileClass == '4k') {
  33253. //目前只有手机端navTileClass == '1k' (分三个梯度)
  33254. var change = zoomedFlag => {
  33255. this.qualityManager.updateMaximums(); //更新maxZoomPanoSize
  33256. this.panoRenderer.setupZoomRenderTarget(); //更新renderTarget
  33257. //currentPano.setZoomed(t);//更新uniforms贴图
  33258. };
  33259. this.qualityManager.zoomLevelResolution = this.zoomLevel >= levelThreshold2 ? '4k' : this.zoomLevel > levelThreshold1 ? '2k' : '1k';
  33260. if (this.oldZoomLevel < levelThreshold2 && this.zoomLevel >= levelThreshold2) {
  33261. //1k/2k-4k
  33262. change();
  33263. o(currentPano, t);
  33264. } else if (this.oldZoomLevel <= levelThreshold1 && this.zoomLevel > levelThreshold1) {
  33265. //1k-2k
  33266. change();
  33267. } else if (this.oldZoomLevel > levelThreshold2 && this.zoomLevel <= levelThreshold2) {
  33268. //4k-2k/1k
  33269. change();
  33270. o(currentPano, t);
  33271. } else if (this.oldZoomLevel > levelThreshold1 && this.zoomLevel <= levelThreshold1) {
  33272. //2k-1k
  33273. change();
  33274. }
  33275. this.oldZoomLevel = this.zoomLevel;
  33276. }
  33277. }
  33278. }
  33279. }
  33280. //--------------------
  33281. addHighMapCube() {
  33282. //创建8*8的tile cube 主要因手机版崩溃 要在电脑端测试得设置maxRenderTargetSize
  33283. if (Potree.settings.tileClass == '4k' && this.qualityManager.maxRenderTargetSize == 2048) {
  33284. var geo = new PlaneGeometry(1, 1, 1, 1);
  33285. var cube = new Object3D();
  33286. cube.tiles = [];
  33287. for (var cubeIndex = 0; cubeIndex < 6; cubeIndex++) {
  33288. var face = new Object3D();
  33289. for (var i = 0; i < 8; i++) {
  33290. for (var j = 0; j < 8; j++) {
  33291. var tile = new Mesh(geo, new MeshBasicMaterial({
  33292. //side:THREE.DoubleSide
  33293. transparent: true,
  33294. opacity: 0.4,
  33295. depthTest: false
  33296. }));
  33297. tile.position.set(i - 3.5, j - 3.5, -4);
  33298. if (Potree.settings.isTest) {
  33299. var colorHue = Math.random();
  33300. tile.material.color = new Color().setHSL(colorHue, 0.6, 0.7);
  33301. /* tile.scoreLabel = new TextSprite( {
  33302. backgroundColor: { r: 0, g: 0, b: 0, a: 0 },
  33303. textColor: { r: 0, g: 0, b: 0, a: 1 },
  33304. borderRadius: 15,
  33305. renderOrder: 50, fontsize : 13,
  33306. text: '' ,
  33307. dontFixOrient:true
  33308. })
  33309. tile.scoreLabel.sprite.material.side = 2;
  33310. tile.scoreLabel.rotation.x = Math.PI
  33311. tile.add(tile.scoreLabel) */
  33312. }
  33313. tile.visible = false;
  33314. tile.tileX = i;
  33315. tile.tileY = j;
  33316. tile.cubeFace = cubeIndex;
  33317. //tile.renderOrder = RenderOrder.highTileCube
  33318. cube.tiles.push(tile);
  33319. face.add(tile);
  33320. }
  33321. }
  33322. switch (cubeIndex) {
  33323. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_X:
  33324. face.rotation.set(0, Math.PI / 2, 0);
  33325. break;
  33326. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_X:
  33327. face.rotation.set(0, -Math.PI / 2, 0);
  33328. break;
  33329. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Y:
  33330. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI);
  33331. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), Math.PI / 2);
  33332. face.quaternion.copy(rot1).multiply(rot2);
  33333. //face.rotation.set(Math.PI/2,0,0);
  33334. break;
  33335. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y:
  33336. //face.rotation.set(-Math.PI/2,0,0);
  33337. var rot1 = new Quaternion().setFromAxisAngle(new Vector3(0, 1, 0), Math.PI);
  33338. var rot2 = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2);
  33339. face.quaternion.copy(rot1).multiply(rot2);
  33340. break;
  33341. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_POSITIVE_Z:
  33342. face.rotation.set(0, Math.PI, 0);
  33343. break;
  33344. case GLCubeFaces$3.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z:
  33345. face.rotation.set(0, 0, 0);
  33346. }
  33347. face.scale.set(1, -1, 1);
  33348. face.cubeFace = cubeIndex;
  33349. cube.add(face);
  33350. }
  33351. cube.name = 'highMapCube';
  33352. this.highMapCube = cube;
  33353. viewer.scene.scene.add(cube);
  33354. {
  33355. var s = 0.1;
  33356. cube.scale.set(s, s, s);
  33357. } //注:由于原本的mesh上加了深度贴图,可能距离镜头比这里的近。凡是在cube以内的部分都会挡住cube导致模糊。但是应该不常见吧(另外到天空的边缘也是很近)。姑且depthTest=false
  33358. this.highMapCube.visible = false;
  33359. Potree.Utils.setObjectLayers(this.highMapCube, 'sceneObjects' /* 'skybox' */); //因它的深度是错误的,故不在skybox层渲染,影响edlRT, 而在renderOverlay时渲染覆盖。
  33360. //console.warn('addHighMapCube')
  33361. viewer.addEventListener('update', () => {
  33362. if (this.highMapCube.visibleTiles) {
  33363. this.updateTiles(); //逐步将visibleTiles加载完
  33364. }
  33365. });
  33366. viewer.addEventListener('camera_changed', e => {
  33367. if (e.viewport == viewer.mainViewport) {
  33368. //重新获取visibleTiles
  33369. Common.intervalTool.isWaiting('update4kTiles', () => {
  33370. var vectorForward = this.getDirection();
  33371. this.updateTiles(vectorForward);
  33372. }, 500);
  33373. }
  33374. });
  33375. }
  33376. }
  33377. isHighMapLoaded(cubeFace, tileX, tileY) {
  33378. var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY];
  33379. return !!tile.material.map;
  33380. }
  33381. updateTiles(direction) {
  33382. if (!this.highMapCube || !this.highMapCube.visible) return;
  33383. if (this.highMapCube.tiles.filter(e => e.image).length <= 10) return; //加载的太少了
  33384. //performance.mark('updateTiles-start')
  33385. if (direction) {
  33386. var camera = viewer.mainViewport.camera;
  33387. var hfov = cameraLight.getHFOVForCamera(camera, true) / 2;
  33388. var vfov = MathUtils.degToRad(camera.fov) / 2;
  33389. /* let hcos = Math.cos(hfov / 2)
  33390. let vcos = Math.cos(vfov / 2) */
  33391. var list = this.highMapCube.tiles;
  33392. list.forEach(e => {
  33393. //屏幕外的不显示
  33394. var pos = e.getWorldPosition(new Vector3());
  33395. var dir = new Vector3().subVectors(pos, this.highMapCube.position).normalize();
  33396. var hcos_ = dir.clone().setZ(direction.z).normalize().dot(direction); //在direction的斜面上水平角度差
  33397. var hRad = Math.acos(hcos_);
  33398. var vRad = -200;
  33399. if ( /* hRad > hfov + 0.08 */hRad / hfov > 1.5) {
  33400. e.score = -100;
  33401. } else {
  33402. vRad = Math.abs(Math.acos(dir.z) - Math.acos(direction.z));
  33403. if ( /* vRad > vfov + 0.08 */vRad / vfov > 1.5) {
  33404. e.score = -100;
  33405. } else {
  33406. e.score = -(hRad / hfov + vRad / vfov);
  33407. }
  33408. }
  33409. e.scores = hRad.toFixed(3) + ', ' + vRad.toFixed(3);
  33410. if (e.score == -100) {
  33411. this.resetTile(e);
  33412. }
  33413. });
  33414. this.highMapCube.visibleTiles = list.filter(e => e.score > -100);
  33415. //list.forEach(e=>e.scoreLabel.setText(e.scores))
  33416. }
  33417. var needRecover = this.highMapCube.visibleTiles.filter(e => !e.material.map);
  33418. if (needRecover.length) {
  33419. var maxCount = Common.getBestCount('4kmaxTileRecover', 0, 2, 1.5, 6, false, 2);
  33420. var count = 0;
  33421. console.log(maxCount);
  33422. needRecover.forEach((e, i) => {
  33423. //只更新若干个,因为太耗时了, 其余的等下帧更新
  33424. if (count >= maxCount) return;
  33425. var r = this.recoverTile(e);
  33426. if (r) count++;
  33427. });
  33428. }
  33429. }
  33430. getHighImage(image, cubeFace, tileX, tileY) {
  33431. var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY];
  33432. tile.image = image; //先记录下来
  33433. }
  33434. updateHighMap(image, cubeFace, tileX, tileY) {
  33435. //console.warn('updateHighMap')
  33436. var tile = this.highMapCube.children[cubeFace].children[tileX * 8 + tileY];
  33437. if (image) tile.image = image; //先记录下来
  33438. if (tile.material.map) return;
  33439. if (this.highMapCube.visibleTiles && !this.highMapCube.visibleTiles.includes(tile) /* this.highMapCube.texLoadedCount >= this.getMaxTileCount() */) {
  33440. return;
  33441. }
  33442. //简易创建贴图
  33443. /* var tex = this.$app.core.get('SceneRenderer').initSizedTexture2D(512, THREE.ClampToEdgeWrapping)
  33444. //var loaded = this.$app.core.get('Player').model.isHighMapLoaded(tile.cubeFace, tile.tileX, tile.tileY)
  33445. this.$app.core.get('SceneRenderer').uploadTexture2D(image, tex, 0, 0, 512, 512) //只替换tex对应的img,不新建
  33446. */
  33447. var tex = new Texture();
  33448. tex.image = image;
  33449. tex.flipY = false;
  33450. tex.wrapS = tex.wrapT = ClampToEdgeWrapping;
  33451. tex.generateMipmaps = false;
  33452. tex.minFilter = LinearFilter;
  33453. tex.needsUpdate = true;
  33454. tile.material.map = tex;
  33455. tile.material.opacity = 1;
  33456. tile.material.transparent = false;
  33457. tile.visible = true;
  33458. tile.material.needsUpdate = true; //发现每次开始放大但还未放大到4k时也会把之前加载过的4k加载
  33459. }
  33460. recoverTile(tile) {
  33461. if (tile.material.map) return;
  33462. if (tile.image) {
  33463. this.updateHighMap(tile.image, tile.cubeFace, tile.tileX, tile.tileY);
  33464. return true;
  33465. } else {
  33466. //console.log('no image')
  33467. }
  33468. }
  33469. resetTile(tile, kill) {
  33470. if (kill) {
  33471. //完全消灭
  33472. tile.image = null;
  33473. }
  33474. var map = tile.material.map;
  33475. if (map) {
  33476. map.dispose(); //这句执行了以后,h.__webglTexture一直就是undefined
  33477. map.loaded = !1;
  33478. map.version = 0;
  33479. //保底再执行一下这个,类似app.sceneRenderer.deallocateCubeTexture(tile.material.map)
  33480. var h = viewer.renderer.properties.get(map);
  33481. //console.log('__webglTexture',!!h.__webglTexture)
  33482. viewer.renderer.getContext().deleteTexture(h.__webglTexture);
  33483. tile.material.map = null;
  33484. tile.material.needsUpdate = true;
  33485. tile.visible = false;
  33486. //this.highMapCube.texLoadedCount --
  33487. //console.log('resetTile'/* , tile.cubeFace, tile.tileX, tile.tileY */)
  33488. }
  33489. }
  33490. resetHighMap() {
  33491. if (!this.highMapCube) return;
  33492. this.highMapCube.children.forEach(e => e.children.forEach(tile => {
  33493. this.resetTile(tile, true);
  33494. }));
  33495. //this.highMapCube.texLoadedCount = 0
  33496. this.highMapCube.visibleTiles = null;
  33497. this.hideHighMap();
  33498. //console.log('resetHighMap')
  33499. }
  33500. setHighMap(pano) {
  33501. if (!this.highMapCube) return;
  33502. this.highMapCube.position.copy(pano.position);
  33503. //可以利用第0个pano查看,其 rotation4dkk是(_x: 0, _y: -1.5707963267948966, _z: 0 )而手动旋转至(_x:1.5707963, _y: -1.57079, _z: 0)时才正确,说明要在4dkk的旋转基础上,绕x轴转90度,(也就是转成navvis坐标系), 然后得到YupToZup的函数写法的
  33504. this.highMapCube.quaternion.copy(math.convertQuaternion.YupToZup(pano.quaternion4dkk));
  33505. //乘上数据集整体的旋转:
  33506. var modelRotQua = new Quaternion().setFromRotationMatrix(pano.pointcloud.rotateMatrix);
  33507. this.highMapCube.quaternion.premultiply(modelRotQua);
  33508. }
  33509. showHighMap() {
  33510. if (!this.highMapCube) return;
  33511. //console.warn('showHighMap')
  33512. this.highMapCube.visible = true;
  33513. }
  33514. hideHighMap() {
  33515. if (!this.highMapCube) return;
  33516. //console.warn('hideHighMap')
  33517. this.highMapCube.visible = false;
  33518. }
  33519. //缩小后继续显示cube呢还是不显示? 不显示的话,就要把cube上的复制到renderTarget上……会不会又崩溃,or没加载的显示???
  33520. addPanoData(data, datasetId) {
  33521. //加载漫游点
  33522. //data[0].file_id = '00019'
  33523. if (data.data) data = data.data;
  33524. if (data.length == 0) console.error(datasetId + ' 没有漫游点');
  33525. //data = data.sort(function(a,b){return a.id-b.id})
  33526. data.forEach(info => {
  33527. //if(Potree.fileServer){
  33528. info.id = this.panos.length; //把info的id的一长串数字改简单点
  33529. //}
  33530. var pano = new Panorama(info, this);
  33531. pano.addEventListener('dispose', e => {
  33532. if (this.closestPano == pano) this.closestPano = null;
  33533. });
  33534. this.panos.push(pano);
  33535. if (Potree.settings.editType == 'pano') {
  33536. Potree.settings.datasetsPanos[datasetId].panos.push(pano);
  33537. }
  33538. });
  33539. }
  33540. loadDone() {
  33541. Potree.Utils.setObjectLayers(this.node, 'sceneObjects');
  33542. //this.updateCube(/* viewer.bound */)
  33543. this.panos.forEach(e => {
  33544. this.neighbourMap[e.id] = {};
  33545. e.label && Potree.Utils.setObjectLayers(e.label, 'bothMapAndScene');
  33546. e.label2 && Potree.Utils.setObjectLayers(e.label2, 'bothMapAndScene');
  33547. });
  33548. this.tileDownloader.setPanoData(this.panos, [] /* , Potree.settings.number */);
  33549. {
  33550. var minSize = new Vector3(1, 1, 1);
  33551. this.bound = math.getBoundByPoints(this.panos.map(e => e.position), minSize);
  33552. viewer.scene.pointclouds.forEach(pointcloud => pointcloud.getPanosBound());
  33553. }
  33554. if (viewer.scene.pointclouds.some(e => e.panos.length == 0)) {
  33555. //console.warn('存在数据集没有pano');
  33556. viewer.hasNoPanoDataset = true;
  33557. }
  33558. }
  33559. getPano(value) {
  33560. var typeName = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'id';
  33561. //默认找的是id,也可以是sid、uuid
  33562. return this.panos.find(p => p[typeName] == value);
  33563. }
  33564. }
  33565. ;
  33566. //判断当前点是否加载了全景图
  33567. Images360.prototype.checkAndWaitForPanoLoad = function () {
  33568. var isLoadedPanos = {},
  33569. LoadedTimePanos = {},
  33570. loadedCallback = {},
  33571. //add
  33572. maxTime = 5e3;
  33573. var withinTime = function withinTime() {
  33574. for (var panoId in isLoadedPanos) if (isLoadedPanos.hasOwnProperty(panoId) && isLoadedPanos[panoId]) {
  33575. var differTime = performance.now() - LoadedTimePanos[panoId];
  33576. if (differTime < maxTime) return !0;
  33577. }
  33578. return !1;
  33579. };
  33580. return function (pano, basePanoSize, doneFun1, doneFun2, progressCallback, iswait, isclear, p) {
  33581. loadedCallback[pano.id] = doneFun1; //add 因为有可能之前请求的没加doneFun1, 如果加载好就执行最新的doneFun1
  33582. if (withinTime()) {
  33583. //距离上次请求时间很近
  33584. //console.log(11)
  33585. return !0; //这里感觉应该是!1
  33586. }
  33587. var changeMode = e => {
  33588. if (e.mode == 'showPointCloud') {
  33589. console.warn('切到点云模式了,就删除loadedCallback记录', pano.id); //否则再次转为showPanos会被withinTime阻拦
  33590. delete isLoadedPanos[pano.id];
  33591. viewer.cancelLoad(pano);
  33592. loadedCallback[pano.id] && loadedCallback[pano.id](); //可以飞行了
  33593. doneFun2 && doneFun2();
  33594. this.removeEventListener('requestMode', changeMode);
  33595. }
  33596. };
  33597. this.addEventListener('requestMode', changeMode);
  33598. var callback1 = (param1, param2) => {
  33599. setTimeout(() => {
  33600. isLoadedPanos[pano.id] = !1;
  33601. loadedCallback[pano.id] && loadedCallback[pano.id](param1, param2);
  33602. this.removeEventListener('requestMode', changeMode);
  33603. }, 1);
  33604. };
  33605. var callback2 = param => {
  33606. //没有看到有传doneFun2的
  33607. setTimeout(() => {
  33608. isLoadedPanos[pano.id] = !1;
  33609. doneFun2 && doneFun2(param);
  33610. }, 1);
  33611. };
  33612. try {
  33613. null !== iswait && void 0 !== iswait || (iswait = !0);
  33614. isLoadedPanos[pano.id] = this.checkAndWaitForTiledPanoLoad(pano, basePanoSize, callback1, callback2, progressCallback, iswait, isclear, p);
  33615. //true代表没加载好
  33616. isLoadedPanos[pano.id] && (LoadedTimePanos[pano.id] = performance.now());
  33617. return isLoadedPanos[pano.id];
  33618. } catch (msg) {
  33619. isLoadedPanos[pano.id] = !1;
  33620. LoadedTimePanos[pano.id] = performance.now() - maxTime;
  33621. throw msg;
  33622. }
  33623. };
  33624. }(); //加载全景图的流程:请求下载当前点的最低分辨率图(不过有可能已经下载了),并且请求uploadTile渲染当前漫游点,若tile都upload完(先6个)会发送消息,LoadComplete 从而回调成功。
  33625. Images360.prototype.getNeighbours = function () {
  33626. //逐渐自动获取neighbours。 200个点差不多在半分钟内算完
  33627. var lastIndex, inited; //标记上次查询到哪,防止重新sortByScore
  33628. return function (interacted) {
  33629. if (!this.currentPano || viewer.mainViewport.view.isFlying() || viewer.lastFrameChanged || viewer.inputHandler.drag /* interacted */) {
  33630. //拖拽时不更新,否则移动端卡
  33631. return lastIndex = 0;
  33632. }
  33633. var nearPanos = this.tileDownloader.tilePrioritizer.nearPanos;
  33634. if (!nearPanos) return;
  33635. //let startTime = Date.now()
  33636. var panos = [this.currentPano, ...nearPanos];
  33637. this.depthSampler.updateNearPanos(panos);
  33638. var maxWaitDur = browser.isMobile() ? 40 : 60;
  33639. var changeCount = 0,
  33640. maxChangeTex = browser.isMobile() ? 1 : 3,
  33641. getCount = 0;
  33642. var changeTexCount = () => {
  33643. changeCount++;
  33644. };
  33645. var median = Potree.timeCollect.depthSamChangeImg.median;
  33646. var ifOverTime = () => {
  33647. var is = changeCount >= maxChangeTex || changeCount * median + getCount * 0.01 > maxWaitDur; //不换贴图也要一丢丢计算时间
  33648. /* if(is){
  33649. console.log('OverTime, changeCount', changeCount)
  33650. } */
  33651. return is;
  33652. };
  33653. this.depthSampler.addEventListener('changeImg', changeTexCount);
  33654. outer: for (var i = lastIndex, j = panos.length; i < j; i++) {
  33655. var pano = panos[i];
  33656. var others = panos.slice(i + 1, j);
  33657. lastIndex = i;
  33658. if (!pano.pointcloud.hasDepthTex && i > 0) break; //点云的情况下最好不改相机位置,因为其他位置点云还没加载完,所以不判断当前点以外的漫游点
  33659. var g = Common.sortByScore(others, [], [Images360.scoreFunctions.distanceSquared(pano.position)]);
  33660. for (var a = 0, b = g.length; a < b; a++) {
  33661. var item = g[a];
  33662. if (item.item == pano) continue;
  33663. if (this.neighbourMap[pano.id][item.item.id] != void 0 && this.neighbourMap[item.item.id][pano.id] != void 0 /* this.isNeighbour(pano,item.item,{dontCompute:true}) != void 0 */) continue; //确定结果了就不需要算
  33664. //console.log('check isNeighbour', pano.id, item.item.id)
  33665. var byCloud = !pano.pointcloud.hasDepthTex;
  33666. var result = this.isNeighbour(pano, item.item, {
  33667. onlyUseTex: !byCloud,
  33668. computeDirFirst: true,
  33669. computeTwoDir: true
  33670. }); //计算
  33671. if (result != void 0) {
  33672. //计算了 (byTex时其实并不一定)
  33673. //console.log('提前计算neighbor', pano.id, item.item.id)
  33674. this.dispatchEvent({
  33675. type: 'getNeighbourAuto',
  33676. panos: [pano, item.item]
  33677. });
  33678. if (byCloud) {
  33679. //只计算一次
  33680. //console.log('提前计算neighbor byCloud', result, pano.id, item.item.id)
  33681. break outer;
  33682. }
  33683. getCount++;
  33684. if (ifOverTime()) {
  33685. break outer;
  33686. }
  33687. }
  33688. }
  33689. lastIndex = i + 1; //这轮结束
  33690. }
  33691. /* if(changeCount){
  33692. console.log( 'changeCount', changeCount)
  33693. } */
  33694. this.depthSampler.removeEventListener('changeImg', changeTexCount);
  33695. if (!inited) {
  33696. inited = true;
  33697. this.addEventListener('loadedDepthImg', e => {
  33698. //console.log('loadedDepthImg',e.pano)
  33699. lastIndex = 0; //主要针对刚打开场景第一个点有杂点时单向不成功,要立即进一步双向计算ifShelter
  33700. });
  33701. }
  33702. /* let costTime = Date.now() - startTime
  33703. costTime > maxWaitDur && console.log( 'costTime:',costTime) */
  33704. };
  33705. }();
  33706. Images360.filters = {
  33707. inPanoDirection: function inPanoDirection(pos, dir, i, log) {
  33708. //pano在mouse的方向上
  33709. return function (pano) {
  33710. var r = pano.floorPosition.clone().sub(pos).normalize();
  33711. var o = pano.position.clone().sub(pos).normalize();
  33712. log && console.log('dire', pano.id, r.dot(dir), o.dot(dir));
  33713. return r.dot(dir) > i || o.dot(dir) > i;
  33714. };
  33715. },
  33716. inFloorDirection: function inFloorDirection(pos, dir, min, log) {
  33717. //pano在mouse的水平方向上
  33718. return function (pano) {
  33719. var vec = new Vector2().subVectors(pano.floorPosition, pos).normalize();
  33720. var dir_ = new Vector2().copy(dir).normalize();
  33721. log && console.log('dire', pano.id, vec.dot(dir_));
  33722. return vec.dot(dir_) > min;
  33723. /* var i = pano.floorPosition.clone().sub(pos).setZ(0).normalize();//改成在xz方向上,否则点击墙面不会移动
  33724. return i.dot(dir.clone().setZ(0)) > min */
  33725. };
  33726. },
  33727. isNotBehindNormal: function isNotBehindNormal(e, t) {
  33728. var i = new Vector3();
  33729. return t = t.clone(), function (n) {
  33730. var r = i.copy(n.position).sub(e).normalize();
  33731. return r.dot(t) > 0;
  33732. };
  33733. },
  33734. isCloseEnoughTo: function isCloseEnoughTo(e, t) {
  33735. return function (i) {
  33736. //因为marker可能比地面高,所以识别范围要比marker看起来更近一些。(因为投影到地板的位置比marker更近)
  33737. return e.distanceTo(i.floorPosition) < t; //许钟文
  33738. };
  33739. },
  33740. not: function not(e) {
  33741. return function (t) {
  33742. return t !== e;
  33743. };
  33744. },
  33745. isEnabled: function isEnabled() {
  33746. return function (t) {
  33747. return t.enabled;
  33748. };
  33749. },
  33750. isVisible: function isVisible() {
  33751. return function (t) {
  33752. return t.visible;
  33753. };
  33754. }
  33755. };
  33756. Images360.scoreFunctions = {
  33757. direction: function direction(curPos, dir, ifLog) {
  33758. return function (pano) {
  33759. var pos1 = /* pano.floorPosition */pano.position; //旧:改为权重放在marker上,这样对有斜坡的更准确,如上楼, 但这样近距离的pano角度就会向下了,以致于走不到
  33760. var n = pos1.clone().sub(curPos).normalize();
  33761. //ifLog && console.log('direction', pano.id, n.dot(dir) * directionFactor )
  33762. return n.dot(dir) * directionFactor;
  33763. };
  33764. },
  33765. distance: function distance(pos1) {
  33766. var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  33767. var ifLog = arguments.length > 2 ? arguments[2] : undefined;
  33768. if (pos1.position) pos1 = pos1.position;
  33769. return function (pano) {
  33770. //许钟文 改
  33771. var pos2 = pano.position.clone();
  33772. //ifLog && console.log('distance', pano.id, pos1.distance(pos2) * -1 )
  33773. return pos1.distanceTo(pos2) * -1 * r;
  33774. };
  33775. },
  33776. distanceSquared: function distanceSquared(pos1) {
  33777. var r = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  33778. if (pos1.position) pos1 = pos1.position;
  33779. return function (pano) {
  33780. //许钟文 改
  33781. var pos2 = pano.position.clone();
  33782. return pos1.distanceToSquared(pos2) * -1 * r;
  33783. };
  33784. },
  33785. angle: function angle(e, t) {
  33786. return function (i) {
  33787. var n = i.position.clone().sub(e).normalize();
  33788. return n.angleTo(t) * Potree.config.navigation.angleFactor;
  33789. };
  33790. }
  33791. };
  33792. Images360.sortFunctions = {
  33793. //排序函数,涉及到两个item相减
  33794. floorDisSquaredToPoint: function floorDisSquaredToPoint(e) {
  33795. return function (t, i) {
  33796. return t.floorPosition.distanceToSquared(e) - i.floorPosition.distanceToSquared(e);
  33797. };
  33798. },
  33799. disSquaredToPoint: function disSquaredToPoint(e) {
  33800. return function (t, i) {
  33801. return t.position.distanceToSquared(e) - i.position.distanceToSquared(e);
  33802. };
  33803. }
  33804. };
  33805. Images360.prototype.updateCube = function () {
  33806. //增加细分的版本,且垂直方向上取中位数 侧边多条
  33807. var minDis = 0.2; //pano和墙距离不能小于相机的near
  33808. var height = 1; //准确计算的话要分别计算两个pano的地面、天花板之间的俯仰角,和pano之间的还不一样。这里统一假设一个比较小的高度,因高度越大 maxSinAlpha 越大
  33809. var minTanBeta = minDis / height; /* (pano0.position.z - pano0.floorPosition.z) */
  33810. var minBeta = Math.atan(minTanBeta);
  33811. var maxSinAlpha = Math.cos(minBeta); // 注:beta = Math/2 - alpha
  33812. var skyHeight = 50;
  33813. return function (pano0, pano1) {
  33814. if (Potree.settings.displayMode != 'showPanos' || pano0 == pano1 || this.cubePanos.includes(pano0) && this.cubePanos.includes(pano1)) return;
  33815. this.cubePanos = [pano0, pano1];
  33816. viewer.addTimeMark('updateCube', 'start');
  33817. //console.log('updateCube',pano0.id, pano1&&pano1.id)
  33818. var useBound = (bound, size) => {
  33819. size = size || bound.getSize(new Vector3());
  33820. var center = bound.getCenter(new Vector3());
  33821. size.max(new Vector3(HighMapCubeWidth, HighMapCubeWidth, HighMapCubeWidth));
  33822. this.cube.geometry = new BoxBufferGeometry(1, 1, 1, 1);
  33823. this.cube.scale.copy(size);
  33824. this.cube.position.copy(center);
  33825. if (Potree.settings.testCube) {
  33826. this.cubeTest.geometry = this.cube.geometry;
  33827. this.cubeTest.scale.copy(size);
  33828. this.cubeTest.position.copy(center);
  33829. }
  33830. return 'useBound';
  33831. };
  33832. var getPanoBound = (pano, dis) => {
  33833. //因漫游点可能在点云外部,如室外平地,所以需要union进漫游点
  33834. var panoBound = new Box3();
  33835. panoBound.expandByPoint(pano.position);
  33836. var margin = dis ? Math.max(dis * 0.1, 10) : 10;
  33837. panoBound.expandByVector(new Vector3(margin, margin, margin)); //give pano a margin 。 随着bound扩大,margin要相应扩大,否则当距离很远时看起来就像没有
  33838. return pano.pointcloud.bound.clone().union(panoBound);
  33839. };
  33840. this.cube.geometry.dispose();
  33841. if (pano1) {
  33842. //过渡
  33843. var dontAddSides;
  33844. var dis = pano0.position.distanceTo(pano1.position);
  33845. if (dis == 0) return;
  33846. var sinAlpha = Math.abs(pano0.position.z - pano1.position.z) / dis; //俯仰角的sin,随角度增大而增大 0-1
  33847. var score = (1 + sinAlpha * 20) * dis; //score越大创建的mesh越不适合
  33848. var isNeighbour = this.isNeighbour(pano0, pano1);
  33849. //console.log(pano0.id, pano1.id, maxSinAlpha.toFixed(2), sinAlpha.toFixed(2), score.toFixed(2), isNeighbour)
  33850. if (sinAlpha > maxSinAlpha || !pano0.pointcloud.hasDepthTex || !pano1.pointcloud.hasDepthTex || (isNeighbour ? score > 100 : score > 50)) {
  33851. var bound = getPanoBound(pano0, dis).union(getPanoBound(pano1, dis));
  33852. var size = bound.getSize(new Vector3());
  33853. var max = Math.max(size.x, size.y, size.z);
  33854. size.set(max, max, max); //距离太远的数据集,过渡会畸变。所以扩大skybox,且为立方体
  33855. return useBound(bound, size);
  33856. } else if (isNeighbour ? score > 70 : score > 15) {
  33857. dontAddSides = true; //pano间有阻挡时得到的side点可能使通道变窄,所以去掉。
  33858. }
  33859. //俯仰角增大时可能不在同一楼层,算出来的mesh不太好,所以更倾向直接使用cube,或去除side。
  33860. var half = browser.isMobile() ? 4 : 8; //自行输入 (点云计算的慢,还不准)
  33861. var count1 = 2 * half; //偶数个 每个pano向 外dir 个数
  33862. //奇数个的好处:在窄空间内能探测到最远距离,坏处是前方有尖角。偶数个的坏处就是可能检测距离太近。
  33863. var getDir = (angle_, vec) => {
  33864. //旋转获得水平向量
  33865. var rotMat = new Matrix4().makeRotationZ(angle_);
  33866. return vec.clone().applyMatrix4(rotMat);
  33867. };
  33868. var getFar = (dir, pano, origin, height) => {
  33869. //获取在这个方向上和墙体intersect的距离
  33870. //在垂直方向上分出多个方向,取一个最可能的接近真实的距离
  33871. var maxH = 40,
  33872. minH = 2,
  33873. minR = 0.5,
  33874. maxR = 2;
  33875. height = height == void 0 ? Math.min(skyHeight, pano.ceilZ - pano.floorPosition.z) : height;
  33876. //let r = height (maxH - minH)* 0.14 // 高度越小,角度越小
  33877. //let r = minR + ( maxR - minR) * THREE.Math.clamp((height - minH) / (maxH - minH),0,1) //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
  33878. var r = math.linearClamp(height, [minH, maxH], [minR, maxR]);
  33879. var getZ = deg => {
  33880. deg *= r;
  33881. deg = MathUtils.clamp(deg, 1, 80);
  33882. return Math.tan(MathUtils.degToRad(deg));
  33883. };
  33884. var dirs_; //注意:角度太大会碰到天花板或地板,越远越容易碰到, 在地下停车场就会伸展不开。 更多取接近0度的,否则围墙矮一点就会取到远处。
  33885. dirs_ = [15, 8, 3, -1, -5];
  33886. dirs_ = dirs_.map(deg => dir.clone().setZ(getZ(deg)).normalize());
  33887. var max = 50;
  33888. var count2 = dirs_.length;
  33889. var disArr = dirs_.map((dir_, i) => {
  33890. var intersect = this.getIntersect(pano, dir_, origin);
  33891. var projectLen = intersect && intersect.distance ? dir_.dot(dir) * intersect.distance : max; //得到project在dir的长度
  33892. return projectLen; //得水平距离
  33893. });
  33894. //console.log(pano ? pano.id : 'side','disArr', disArr.slice(0))
  33895. disArr.sort((a, b) => {
  33896. return b - a;
  33897. }); //从大到小
  33898. //console.log(pano ? pano.id : 'side','disArr', disArr)
  33899. var dis = disArr[Math.floor(count2 / 2 - 0.5)]; //对半、取前(中位数)
  33900. return dis;
  33901. };
  33902. var sideCount = [0, 0];
  33903. var addPos = (pano, vec) => {
  33904. //添加这个pano这一侧向外半圆的顶点
  33905. //添加pano位置对应的最高点最低点:
  33906. var minZ, maxZ;
  33907. minZ = pano.floorPosition.z;
  33908. maxZ = pano.getCeilHeight();
  33909. if (maxZ == Infinity) maxZ = skyHeight + pano.position.z; //maxZ = Math.max(skyHeight, maxZ)
  33910. [maxZ, minZ].forEach(z => {
  33911. posArr.push(pano.position.clone().setZ(z));
  33912. });
  33913. //在画面上线条从左往右数
  33914. var angle = Math.PI / (count1 - 1);
  33915. var dirs = []; //平分这半边180度
  33916. for (var i = 0; i < count1; i++) {
  33917. dirs.push(getDir(Math.PI / 2 - i * angle, vec)); //正的在左边
  33918. }
  33919. var dirs2 = dirs.map(dir => {
  33920. return {
  33921. dir,
  33922. dis: getFar(dir, pano)
  33923. };
  33924. });
  33925. //剔除那些突然间离相机很近的dir。有可能是拍摄的人、或者杆子、树
  33926. /* dirs2.forEach((e,i)=>{
  33927. console.log(i, e.dis)
  33928. let smallThanBefore = ()=>{
  33929. return dirs2[i-1].dis / e.dis > maxRatio
  33930. }
  33931. let smallThanAfter = ()=>{
  33932. return dirs2[i+1].dis / e.dis > maxRatio
  33933. }
  33934. if(i>0 && i<count1-1 && smallThanBefore() && smallThanAfter()){//比左右两边都小很多
  33935. e.disB = (dirs2[i-1].dis + dirs2[i+1].dis) / 2 //平均数
  33936. console.log('两者之间',i,e.disB)
  33937. }else if(i==count1-1 && smallThanBefore() ) {//比前者小很多
  33938. e.disB = dirs2[i-1].dis * 0.8
  33939. console.log('smallThanBefore', i, e.disB)
  33940. }else if(i==0 && smallThanAfter() ){//比后者小很多
  33941. e.disB = dirs2[i+1].dis * 0.8
  33942. console.log('smallThanAftere', i, e.disB)
  33943. }
  33944. }) */
  33945. var maxRatio1 = 3,
  33946. maxRatio2 = 8; //超过maxRatio1就要加入判断,而最终结果的设限其实是maxRatio2
  33947. var minWidth = 0.5;
  33948. var computeWidth = (start, end) => {
  33949. start += 1; //不包含start和end
  33950. var count = end - start;
  33951. var dis = 0;
  33952. for (var m = start; m < end; m++) {
  33953. //得平均数
  33954. dis += dirs2[m].dis;
  33955. }
  33956. dis /= count;
  33957. var angle = Math.PI / (count1 - 1) * count / 2;
  33958. var width = dis * Math.tan(angle); //得到block的半宽度
  33959. return width;
  33960. };
  33961. var changeDis = (start, end) => {
  33962. //不包含start
  33963. start += 1; //不包含start和end
  33964. for (var m = start; m < end; m++) {
  33965. dirs2[m].disB = dirs2[end].dis * 0.8;
  33966. //console.log('changeDis', m, dirs2[m].disB)
  33967. }
  33968. };
  33969. var start = -1;
  33970. for (var _i = 0; _i < count1; _i++) {
  33971. //遍历时将左边dis比之小很多且宽度较小的改大
  33972. //console.log(i, dirs2[i].dis)
  33973. var j = _i - 1;
  33974. var ratios = 0;
  33975. while (j > start && dirs2[_i].dis / dirs2[j].dis > maxRatio1) {
  33976. ratios += dirs2[_i].dis / dirs2[j].dis;
  33977. j--;
  33978. }
  33979. var count = _i - j - 1;
  33980. ratios /= count;
  33981. if (count > 0 && computeWidth(j, _i) < minWidth * ratios / maxRatio2) {
  33982. //怎么感觉好像改成了视觉宽度小于某个值即可,那直接用count好了?
  33983. changeDis(j, _i);
  33984. start = _i; //在此之前的修改过,之后不用再判断
  33985. }
  33986. /* if(count > 0 && (count == 1 || computeWidth(j,i)<minWidth)){//若只有一个不用判断宽度直接修改
  33987. changeDis(j,i)
  33988. start = i //在此之前的修改过,之后不用再判断
  33989. } */
  33990. }
  33991. dirs2.forEach((e, index) => {
  33992. var dir = e.dir.clone().multiplyScalar(e.disB || e.dis);
  33993. [maxZ, minZ].forEach(z => {
  33994. posArr.push(pano.position.clone().setZ(z).add(dir)); //获取到外墙点
  33995. });
  33996. });
  33997. };
  33998. var addSide = () => {
  33999. //两个漫游点间两边各加一些侧线
  34000. //中点处的
  34001. var top0 = pano0.ceilZ == Infinity ? pano0.position.z + skyHeight : pano0.ceilZ;
  34002. var top1 = pano1.ceilZ == Infinity ? pano1.position.z + skyHeight : pano1.ceilZ;
  34003. var midMaxZ = (top0 + top1) / 2;
  34004. var midMinZ = (pano0.floorPosition.z + pano1.floorPosition.z) / 2;
  34005. var mid = new Vector3().addVectors(pano0.position, pano1.position).multiplyScalar(0.5);
  34006. if (!dontAddSides) {
  34007. if (pano0.pointcloud.hasDepthTex && pano0.pointcloud.hasDepthTex) {
  34008. var panos = [pano0, pano1];
  34009. var vecs = [vec.clone().negate(), vec];
  34010. var axis = [[-1, 1], [1, -1]];
  34011. var dis2d = new Vector2().subVectors(pano0.position, pano1.position).length(); //水平上的距离
  34012. var maxDis = 50,
  34013. _minDis = 0.5,
  34014. minR = 0.2,
  34015. maxR = 1.2;
  34016. //let r = maxR - ( maxR - minR) * THREE.Math.clamp((dis2d - minDis) / (maxDis - minDis),0,1) //dis2d越大,角度要越小 //THREE.Math.smoothstep(currentDis, op.nearBound, op.farBound);
  34017. var r = math.linearClamp(dis2d, [_minDis, maxDis], [maxR, minR]);
  34018. //console.log('dis2d',dis2d,'r',r)
  34019. var angles = (browser.isMobile() /* || dis2d<4 */ ? [60] : [50, 70] /* [35,65] */).map(deg => {
  34020. //正的在左边 尽量能够平分中间这段墙体。 (角度为从中心向外)
  34021. var angle = MathUtils.clamp(deg * r, 5, 80);
  34022. //console.log('angle',angle)
  34023. return MathUtils.degToRad(angle);
  34024. });
  34025. axis.forEach((axis_, index0) => {
  34026. var disToSides = [];
  34027. var accordingPano = index0 == 0 ? pano0 : pano1; //根据离该点在vec方向上的距离顺序来存顶点
  34028. panos.forEach((pano, index) => {
  34029. var dirs = angles.map(angle => getDir(axis_[index] * angle, vecs[index])); //一侧的若干角度
  34030. dirs.forEach((dir_, i) => {
  34031. var dis1 = getFar(dir_, pano);
  34032. var disToPano2d = dis1 * Math.cos(angles[i]);
  34033. if (disToPano2d < dis2d) {
  34034. //超过的话都到另一半pano的半圆了,不计入。(角度越小越容易超过)
  34035. var disToSide = dis1 * Math.sin(angles[i]);
  34036. if (pano != accordingPano) {
  34037. disToPano2d = dis2d - disToPano2d; //反一下
  34038. }
  34039. dir_.multiplyScalar(dis1);
  34040. disToSides.push({
  34041. disToSide,
  34042. disToPano2d,
  34043. pano,
  34044. dir_
  34045. });
  34046. } else {
  34047. //console.log('超过',index0,index,i)
  34048. }
  34049. });
  34050. });
  34051. if (disToSides.length) {
  34052. //disToSides.sort((a,b)=>{return b-a});//从大到小
  34053. //由距离accordingPano的近到远:
  34054. disToSides.sort((a, b) => {
  34055. return a.disToPano2d - b.disToPano2d;
  34056. });
  34057. //console.log('disToSides', index0, disToSides)
  34058. if (disToSides.length == 1 && disToSides[0].disToSide < 0.5) {
  34059. disToSides = []; //如果太近直接去除
  34060. }
  34061. disToSides.forEach(e => {
  34062. //求z
  34063. var ratio = e.disToPano2d / dis2d;
  34064. var r = accordingPano == pano0 ? 1 - ratio : ratio;
  34065. var sideMaxZ_ = top0 * r + top1 * (1 - r);
  34066. var sideMinZ_ = pano0.floorPosition.z * r + pano1.floorPosition.z * (1 - r);
  34067. [sideMaxZ_, sideMinZ_].forEach(z => {
  34068. posArr.push(e.pano.position.clone().setZ(z).add(e.dir_)); //是直接使用最长dis的那个intersect点好还是mid
  34069. });
  34070. });
  34071. }
  34072. sideCount[index0] = disToSides.length; //记录侧边个数
  34073. });
  34074. } else {
  34075. //这段针对点云时,仅测试才会执行到
  34076. sideCount = [1, 1];
  34077. var sideDirs = [getDir(Math.PI / 2, vec), getDir(-Math.PI / 2, vec)];
  34078. sideDirs.forEach((dir_, index) => {
  34079. var dis = getFar(dir_, null, mid, midMaxZ - midMinZ); //直接从中点求两侧的距离
  34080. dir_.multiplyScalar( /* Math.max( */dis /* , sideDis[index]) */);
  34081. [midMaxZ, midMinZ].forEach(z => {
  34082. posArr.push(mid.clone().setZ(z).add(dir_));
  34083. });
  34084. });
  34085. }
  34086. }
  34087. //中心:
  34088. [midMaxZ, midMinZ].forEach(z => {
  34089. posArr.push(mid.clone().setZ(z));
  34090. });
  34091. };
  34092. //positions存放顺序:pano的每边的 zMax和zMin 、count1个dir的点 ;侧边的点 ;连接处顶底的中点
  34093. var addFaces = () => {
  34094. var getPI = function getPI(index, posType, panoIndex) {
  34095. //获取顶点序号
  34096. return 2 + (count1 * 2 + 2) * panoIndex + index * 2 + (posType == 'top' ? 0 : 1);
  34097. };
  34098. var getSidePI = function getSidePI(index, posType, panoIndex) {
  34099. //获取侧边顶点序号
  34100. if (panoIndex == 1) index += sideCount[0];
  34101. return getPI(index, posType, 2) - 2;
  34102. };
  34103. var getPanoPI = function getPanoPI(posType, panoIndex) {
  34104. //获取pano处对应的点序号
  34105. return getPI(-1, posType, panoIndex);
  34106. };
  34107. var topCenter = posArr.length - 2; //最后添加的两个中心点
  34108. var btmCenter = posArr.length - 1;
  34109. for (var i = 0; i < 2; i++) {
  34110. for (var index = 1; index < count1; index++) {
  34111. //pano外侧半圆围墙
  34112. faceArr.push([getPI(index, 'top', i), getPI(index - 1, 'btm', i), getPI(index - 1, 'top', i)],
  34113. //加入一块四方面
  34114. [getPI(index, 'top', i), getPI(index, 'btm', i), getPI(index - 1, 'btm', i)]);
  34115. faceArr.push([getPI(index, 'top', i), getPI(index - 1, 'top', i), getPanoPI('top', i)]); //天花板扇形
  34116. faceArr.push([getPI(index, 'btm', i), getPI(index - 1, 'btm', i), getPanoPI('btm', i)]); //地板扇形
  34117. }
  34118. var j = (i + 1) % 2; //另一个pano
  34119. //侧边
  34120. for (var u = 0; u <= sideCount[i]; u++) {
  34121. //侧边每个四方的左上右上左下右下四个点
  34122. var pLT = u == 0 ? getPI(0, 'top', i) : getSidePI(u - 1, 'top', i);
  34123. var pRT = u == sideCount[i] ? getPI(count1 - 1, 'top', j) : getSidePI(u, 'top', i);
  34124. var pLB = u == 0 ? getPI(0, 'btm', i) : getSidePI(u - 1, 'btm', i);
  34125. var pRB = u == sideCount[i] ? getPI(count1 - 1, 'btm', j) : getSidePI(u, 'btm', i);
  34126. faceArr.push([pLT, pLB, pRB], [pLT, pRB, pRT]); //外侧四方面
  34127. faceArr.push([pLT, topCenter, pRT], [pLB, btmCenter, pRB]); //顶部和底部到整体中心的扇形(由于点的顺序是根据和两个pano的距离,因此到中心的夹角并没按顺序排列,所以可能会重叠)
  34128. if (i == 0) {
  34129. //只需要算一次
  34130. //顶部和底部中心与两个pano边构成的三角形
  34131. if (u == 0) {
  34132. faceArr.push([pLT, getPI(count1 - 1, 'top', i), topCenter], [pLB, getPI(count1 - 1, 'btm', i), btmCenter]);
  34133. }
  34134. //不能用else 因为当length==0时u==0也==sideCount[i],此时就是要两个面
  34135. if (u == sideCount[i]) {
  34136. faceArr.push([pRT, getPI(0, 'top', j), topCenter], [pRB, getPI(0, 'btm', j), btmCenter]);
  34137. }
  34138. }
  34139. }
  34140. }
  34141. };
  34142. var posArr = [];
  34143. var faceArr = [];
  34144. //两点连线的水平向量
  34145. var vec = new Vector3().subVectors(pano0.position, pano1.position).setZ(0).normalize();
  34146. /* let sideDis0 = */
  34147. addPos(pano0, vec);
  34148. /* let sideDis1 = */
  34149. addPos(pano1, vec.clone().negate());
  34150. addSide();
  34151. addFaces();
  34152. //MeshDraw.updateGeometry(this.cube.geometry, posArr, faceArr)
  34153. var geo = MeshDraw.createGeometry(posArr, faceArr);
  34154. this.cube.geometry = geo;
  34155. this.cube.scale.set(1, 1, 1);
  34156. this.cube.position.set(0, 0, 0);
  34157. if (Potree.settings.testCube) {
  34158. this.cubeTest.geometry = geo;
  34159. this.cubeTest.scale.set(1, 1, 1);
  34160. this.cubeTest.position.set(0, 0, 0);
  34161. }
  34162. } else {
  34163. useBound(getPanoBound(pano0));
  34164. }
  34165. viewer.addTimeMark('updateCube', 'end');
  34166. return true;
  34167. /*
  34168. 关于卡顿:
  34169. 即使使用cube,若scale设置为只容纳两个pano,也会卡顿。但也是有的卡有的不卡。
  34170. 若按照原先的复杂geo,一般在平直的街道上行走流畅,经过拐弯或者复杂区域较卡。减小geo复杂度没有什么作用。
  34171. 注: 修改skybox,若不准的话,会遮住其他mesh,比如marker。尤其在没有深度贴图时。
  34172. 耗时: chrome: 20+ ,但是firefox:500+ 咋回事 ? iphonex safari: 40+
  34173. */
  34174. };
  34175. }();
  34176. /*
  34177. viewer.images360.flyToPano(viewer.images360.getPano('1765955963253690368|70','sid'))
  34178. viewer.images360.flyToPano(viewer.images360.lastPano)
  34179. */
  34180. /**
  34181. * @author alteredq / http://alteredqualia.com/
  34182. *
  34183. * Full-screen textured quad shader
  34184. */
  34185. var CopyShader = {
  34186. uniforms: {
  34187. "tDiffuse": {
  34188. value: null
  34189. },
  34190. "opacity": {
  34191. value: 1.0
  34192. }
  34193. },
  34194. vertexShader: ["varying vec2 vUv;", "void main() {", "vUv = uv;", "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );", "}"].join("\n"),
  34195. fragmentShader: ["uniform float opacity;", "uniform sampler2D tDiffuse;", "varying vec2 vUv;", "void main() {", "vec4 texel = texture2D( tDiffuse, vUv );",
  34196. //如果开启premultipliedAlpha用这个,否则用注释的
  34197. "gl_FragColor = opacity * texel;",
  34198. //"gl_FragColor = texture2D( tDiffuse, vUv );",
  34199. //"gl_FragColor.a *= opacity;",
  34200. "}"].join("\n")
  34201. };
  34202. /**
  34203. * @author alteredq / http://alteredqualia.com/
  34204. */
  34205. var Pass = function Pass() {
  34206. // if set to true, the pass is processed by the composer
  34207. this.enabled = true;
  34208. // if set to true, the pass indicates to swap read and write buffer after rendering
  34209. this.needsSwap = true;
  34210. // if set to true, the pass clears its buffer before rendering
  34211. this.clear = false;
  34212. // if set to true, the result of the pass is rendered to screen
  34213. this.renderToScreen = false;
  34214. };
  34215. Object.assign(Pass.prototype, {
  34216. setSize: function setSize(width, height) {},
  34217. render: function render(renderer, writeBuffer, readBuffer, delta, maskActive) {
  34218. console.error('THREE.Pass: .render() must be implemented in derived pass.');
  34219. }
  34220. });
  34221. var ShaderPass = function ShaderPass(shader, textureID) {
  34222. Pass.call(this);
  34223. this.textureID = textureID !== undefined ? textureID : "tDiffuse";
  34224. if (shader instanceof ShaderMaterial) {
  34225. this.uniforms = shader.uniforms;
  34226. this.material = shader;
  34227. } else if (shader) {
  34228. this.uniforms = UniformsUtils.clone(shader.uniforms);
  34229. this.material = new ShaderMaterial({
  34230. defines: Object.assign({}, shader.defines),
  34231. uniforms: this.uniforms,
  34232. vertexShader: shader.vertexShader,
  34233. fragmentShader: shader.fragmentShader,
  34234. transparent: true //add
  34235. });
  34236. }
  34237. this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
  34238. this.scene = new Scene();
  34239. this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null);
  34240. this.quad.frustumCulled = false; // Avoid getting clipped
  34241. this.scene.add(this.quad);
  34242. };
  34243. ShaderPass.prototype = Object.assign(Object.create(Pass.prototype), {
  34244. constructor: ShaderPass,
  34245. render: function render(scene, camera, viewports, renderer, writeBuffer, readBuffer, delta, maskActive) {
  34246. var oldTarget = renderer.getRenderTarget();
  34247. /* if(this.readTarget){ //add
  34248. readBuffer = oldTarget
  34249. } */
  34250. if (this.uniforms[this.textureID]) {
  34251. this.uniforms[this.textureID].value = readBuffer.texture;
  34252. }
  34253. this.quad.material = this.material;
  34254. if (this.renderToScreen) {
  34255. renderer.render(this.scene, this.camera);
  34256. } else {
  34257. renderer.setRenderTarget(writeBuffer);
  34258. if (this.clear) renderer.clear();
  34259. renderer.render(this.scene, this.camera);
  34260. renderer.setRenderTarget(oldTarget);
  34261. }
  34262. }
  34263. });
  34264. /* const mapHeight = -1000;//要比点云低。最低
  34265. const cameraHeight = 1000; //最高 */
  34266. var panosHeight = config$1.map.mapHeight + 100; //要比点云低 (marker)
  34267. var cursorHeight = 0; //比地图高就行
  34268. var routeLayerHeight = config$1.map.mapHeight + 105;
  34269. var texLoader$5 = new TextureLoader();
  34270. var planeGeo$1 = new PlaneBufferGeometry(1, 1);
  34271. var markerSize = 1;
  34272. var initCameraFeildWidth = 50;
  34273. var panoMarkerMats;
  34274. class MapViewer extends ViewerBase {
  34275. constructor(dom) {
  34276. super(dom, {
  34277. clearColor: Potree.config.mapBG,
  34278. name: 'mapViewer',
  34279. antialias: true
  34280. });
  34281. this.visible = true;
  34282. this.initScene();
  34283. this.needRender_ = false;
  34284. this.mapLayer = new MapLayer(this, this.viewports[0]);
  34285. this.scene.add(this.mapLayer.sceneGroup);
  34286. this.mapLayer.sceneGroup.position.setZ(Potree.config.map.mapHeight);
  34287. this.mapRatio = 0.5;
  34288. this.splitDir = 'leftRight';
  34289. this.renderMeasure = false;
  34290. //因context的preserveDrawingBuffer为false之后,canvas渲染多个viewport时会自动clear,所以若不渲染就会是空的。所以没有变化时就直接拷贝buffer好了。
  34291. this.copyPass = new ShaderPass(CopyShader);
  34292. this.copyBuffer = new WebGLRenderTarget(100, 100, {
  34293. minFilter: LinearFilter,
  34294. magFilter: LinearFilter,
  34295. format: RGBAFormat,
  34296. stencilBuffer: false
  34297. });
  34298. viewer.addEventListener("camera_changed", e => {
  34299. var needUpdateCursor;
  34300. if (e.viewport == viewer.mainViewport) {
  34301. needUpdateCursor = true;
  34302. } else if (e.viewport == this.viewports[0]) {
  34303. //attachedToViewer
  34304. needUpdateCursor = true;
  34305. this.mapChanged = true;
  34306. this.updateWhenAtViewer();
  34307. e.changeInfo.projectionChanged && this.setViewLimit();
  34308. }
  34309. needUpdateCursor && this.updateCursor();
  34310. });
  34311. this.addEventListener("camera_changed", e => {
  34312. e.changeInfo.projectionChanged && this.setViewLimit();
  34313. });
  34314. //viewer.addEventListener("global_mousemove", this.updateWhenAtViewer.bind(this)) //鼠标移动时reticule也动,所以直接就needRender
  34315. /* viewer.reticule.addEventListener('update',(e)=>{
  34316. if(this.attachedToViewer)this.needRender = true
  34317. }) */
  34318. viewer.scene.addEventListener("360_images_added", this.addPanos.bind(this));
  34319. viewer.addEventListener("loadPointCloudDone", this.initProjection.bind(this));
  34320. this.addEventListener('global_click', e => {
  34321. if (!e.isTouch && e.button != MOUSE.LEFT) return;
  34322. this.updateClosestPano(e.intersect);
  34323. });
  34324. this.addEventListener('add', e => {
  34325. //添加其他mesh
  34326. this.scene.add(e.object);
  34327. if (e.name == 'route') {
  34328. e.object.position.z = routeLayerHeight;
  34329. }
  34330. Potree.Utils.setObjectLayers(e.object, 'mapObjects');
  34331. });
  34332. viewer.addEventListener('allLoaded', () => {
  34333. this.setViewLimit('standard');
  34334. });
  34335. if (!Potree.settings.isOfficial) {
  34336. var domRoot = viewer.renderer.domElement.parentElement;
  34337. var elAttach = $("<input type='button' value='map绑定'></input>");
  34338. elAttach.css({
  34339. position: "absolute",
  34340. right: '80%',
  34341. bottom: '20px',
  34342. zIndex: "10000",
  34343. fontSize: '1em',
  34344. color: "black",
  34345. background: 'rgba(255,255,255,0.8)'
  34346. });
  34347. var state = false;
  34348. elAttach.on("click", () => {
  34349. state = !state;
  34350. this.attachToMainViewer(state, 'measure');
  34351. elAttach.val(state ? 'map分离' : 'map绑定');
  34352. });
  34353. domRoot.appendChild(elAttach[0]);
  34354. }
  34355. }
  34356. get needRender() {
  34357. return this.needRender_;
  34358. }
  34359. set needRender(n) {
  34360. this.needRender_ = n;
  34361. n && (this.viewports[0].needRender = true); //使attachedToViewer时在renderDefault中可渲染
  34362. }
  34363. get mapChanged() {
  34364. return this.mapChanged_;
  34365. }
  34366. set mapChanged(c) {
  34367. //镜头移动、地图内容改变都会为true
  34368. this.mapChanged_ = c;
  34369. c && (this.needRender = true);
  34370. }
  34371. waitLoadDone(callback) {
  34372. //确保加载完后执行
  34373. var timer; //等待一段时间看有没有新加载的tile,如果超过这个时间没有就不等了,算加载结束
  34374. var pauseCountDown = () => {
  34375. //重新等待加载结束,中断倒计时
  34376. clearTimeout(timer);
  34377. //console.log('pauseCountDown')
  34378. };
  34379. var freshCountDown = () => {
  34380. //刷新倒计时
  34381. //console.log('freshCountDown')
  34382. clearTimeout(timer);
  34383. timer = setTimeout(() => {
  34384. this.mapLayer.removeEventListener('loadDone', freshCountDown);
  34385. this.mapLayer.removeEventListener('startLoad', pauseCountDown);
  34386. callback();
  34387. }, document.hidden ? 5000 : 500);
  34388. };
  34389. this.mapLayer.addEventListener('loadDone', freshCountDown);
  34390. this.mapLayer.addEventListener('startLoad', pauseCountDown);
  34391. if (this.mapLayer.loadingInProgress == 0) {
  34392. freshCountDown();
  34393. }
  34394. }
  34395. addListener(images360) {
  34396. images360.addEventListener('flyToPano', e => {
  34397. var toPano = e.toPano;
  34398. if (toPano.dontMoveMap) return;
  34399. /* transitions.start(lerp.vector(this.view.position, toPano.pano.position.clone().setZ(cameraHeight),
  34400. (pos, progress)=>{
  34401. }), toPano.duration, null, 0, easing[toPano.easeName] ); */
  34402. var boundSize; // = new THREE.Vector2(10,10)
  34403. this.moveTo(toPano.pano.position.clone().setZ(Potree.config.map.cameraHeight), boundSize, toPano.duration, null, toPano.easeName);
  34404. });
  34405. }
  34406. initProjection() {
  34407. this.started = true;
  34408. this.mapLayer.initProjection();
  34409. }
  34410. initScene() {
  34411. var w = initCameraFeildWidth;
  34412. var width = this.renderArea.clientWidth;
  34413. var height = this.renderArea.clientHeight;
  34414. //let aspect = width / height
  34415. this.camera = new OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2 /* -w/2, w/2, w/2/aspect, -w/2/aspect */, 0.01, 10000);
  34416. this.camera.zoom = width / w; //zoom越大视野越小
  34417. //this.camera.position.set(0,0,10);
  34418. this.camera.up.set(0, 0, 1);
  34419. //this.camera.lookAt(new THREE.Vector3())
  34420. //this.camera.updateMatrixWorld()
  34421. this.view = new ExtendView();
  34422. this.view.position.set(0, 0, Potree.config.map.cameraHeight);
  34423. this.view.lookAt(0, 0, 0);
  34424. var viewport = new Viewport(this.view, this.camera, {
  34425. left: 0,
  34426. bottom: 0,
  34427. width: 1,
  34428. height: 1,
  34429. name: 'mapViewport'
  34430. });
  34431. viewport.axis = ["x", "y"];
  34432. viewport.axisSign = [1, 1];
  34433. viewport.noPointcloud = true; //不要渲染点云
  34434. viewport.render = this.render.bind(this); //标志给mainView渲染
  34435. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  34436. viewport.addEventListener('resize', () => {
  34437. this.copyBuffer.setSize(viewport.resolution2.x, viewport.resolution2.y);
  34438. });
  34439. this.viewports = [viewport];
  34440. this.controls = new FirstPersonControls(this, this.viewports[0]);
  34441. this.controls.setEnable(true);
  34442. this.scene = new Scene();
  34443. this.inputHandler = new InputHandler(this, this.scene);
  34444. this.inputHandler.name = 'mapInputHandler';
  34445. //this.inputHandler.addInputListener(this.controls);
  34446. this.inputHandler.registerInteractiveScene(this.scene); //interactiveScenes
  34447. this.viewports[0].interactiveScenes = this.inputHandler.interactiveScenes; //供viewer的inputHandler使用
  34448. var cursor = new Mesh(planeGeo$1, new MeshBasicMaterial({
  34449. transparent: true,
  34450. opacity: 0.9,
  34451. depthTest: false,
  34452. //防止透明冲突
  34453. map: texLoader$5.load(Potree.resourcePath + '/textures/pic_location128.png')
  34454. }));
  34455. cursor.position.set(0, 0, cursorHeight);
  34456. this.cursor = cursor;
  34457. this.scene.add(cursor);
  34458. Potree.Utils.setObjectLayers(this.scene, 'mapObjects');
  34459. }
  34460. setViewLimit(state) {
  34461. //设置边界,当编辑空间模型等时要解禁
  34462. if (!state) state = this.limitBoundState;
  34463. if (!state) return;
  34464. this.limitBoundState = state;
  34465. var setting = Potree.config.OrthoCameraLimit[state];
  34466. if (setting) {
  34467. this.camera.zoomLimit = $.extend({}, setting.zoom);
  34468. var lonlatCenter = viewer.transform.lonlatToLocal.inverse([0, 0]);
  34469. var minY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], -90 + setting.latPad])[1]; //屏幕边界的bound
  34470. var maxY = viewer.transform.lonlatToLocal.forward([lonlatCenter[0], 90 - setting.latPad])[1];
  34471. /*this.view.limitBound = new THREE.Box3(
  34472. new THREE.Vector3(setting.xBound[0], minY, Potree.config.map.cameraHeight),
  34473. new THREE.Vector3(setting.xBound[1], maxY, 1 / 0)
  34474. ) */
  34475. var halfHeight = this.viewports[0].resolution.y / 2 / this.camera.zoom; //屏幕所占高度的一半
  34476. var halfWidth = this.viewports[0].resolution.x / 2 / this.camera.zoom;
  34477. this.view.limitBound = new Box3(new Vector3(setting.xBound[0] + halfWidth, minY + halfHeight, Potree.config.map.cameraHeight), new Vector3(setting.xBound[1] - halfWidth, maxY - halfHeight, 1 / 0));
  34478. } else {
  34479. this.view.limitBound = null;
  34480. this.camera.zoomLimit = null;
  34481. }
  34482. }
  34483. updateCursor() {
  34484. //console.log('pos', viewer.mainViewport.camera.position.toArray() )
  34485. var scale = math.getScaleForConstantSize({
  34486. //规定下最小最大像素
  34487. minSize: 80,
  34488. maxSize: 200,
  34489. nearBound: initCameraFeildWidth * 0.1,
  34490. farBound: initCameraFeildWidth * 2,
  34491. camera: this.camera,
  34492. position: this.cursor.getWorldPosition(new Vector3()),
  34493. resolution: this.viewports[0].resolution //2
  34494. });
  34495. this.cursor.scale.set(scale, scale, scale); //当地图缩放时
  34496. this.cursor.position.copy(viewer.mainViewport.camera.position).setZ(cursorHeight); //当场景镜头旋转移动时
  34497. this.cursor.rotation.z = viewer.mainViewport.view.yaw;
  34498. this.needRender = true;
  34499. }
  34500. addPanos(e) {
  34501. var panosGroup = new Object3D();
  34502. panosGroup.name = 'markers';
  34503. panoMarkerMats = {
  34504. default: new MeshBasicMaterial({
  34505. transparent: true,
  34506. opacity: 0.5,
  34507. map: texLoader$5.load(Potree.resourcePath + '/textures/map_marker.png')
  34508. }),
  34509. selected: new MeshBasicMaterial({
  34510. transparent: true,
  34511. opacity: 1,
  34512. map: texLoader$5.load(Potree.resourcePath + '/textures/map_marker.png')
  34513. })
  34514. };
  34515. e.images.panos.forEach(pano => {
  34516. pano.mapMarker = new Mesh(planeGeo$1, panoMarkerMats.default);
  34517. pano.mapMarker.position.copy(pano.position).setZ(0);
  34518. pano.mapMarker.scale.set(markerSize, markerSize, markerSize);
  34519. pano.mapMarker.name = 'mapMarker';
  34520. panosGroup.add(pano.mapMarker);
  34521. var mouseover = e => {
  34522. if (!e.byMap) {
  34523. pano.mapMarker.material = panoMarkerMats.selected;
  34524. if (!e.byMainView) pano.dispatchEvent({
  34525. type: "hoverOn",
  34526. byMap: true
  34527. });
  34528. this.needRender = true;
  34529. }
  34530. };
  34531. var mouseleave = e => {
  34532. if (!e.byMap) {
  34533. pano.mapMarker.material = panoMarkerMats.default;
  34534. if (!e.byMainView) pano.dispatchEvent({
  34535. type: "hoverOff",
  34536. byMap: true
  34537. });
  34538. this.needRender = true;
  34539. }
  34540. };
  34541. pano.mapMarker.addEventListener('mouseover', mouseover);
  34542. pano.mapMarker.addEventListener('mouseleave', mouseleave);
  34543. pano.addEventListener('hoverOn', mouseover);
  34544. pano.addEventListener('hoverOff', mouseleave);
  34545. var onclick = e => {
  34546. viewer.images360.flyToPano(pano);
  34547. };
  34548. pano.mapMarker.addEventListener('click', onclick);
  34549. pano.addEventListener('isVisible', e => {
  34550. //是否显示该点的mesh(不显示也能走)
  34551. //console.log('panoMarker isVisible', pano.id, e.visible)
  34552. Potree.Utils.updateVisible(pano.mapMarker, 'panoVisible', e.visible);
  34553. this.needRender = true;
  34554. });
  34555. pano.addEventListener('rePos', e => {
  34556. pano.mapMarker.position.copy(pano.position).setZ(0);
  34557. });
  34558. });
  34559. this.scene.add(panosGroup);
  34560. panosGroup.position.z = panosHeight;
  34561. this.panosGroup = panosGroup;
  34562. Potree.Utils.setObjectLayers(panosGroup, 'mapObjects');
  34563. /* e.images.on('markersDisplayChange', (show)=>{
  34564. panosGroup.visible = show
  34565. this.needRender = true
  34566. }) */
  34567. //-------
  34568. //this.fitPanosToViewport()
  34569. this.initFitView();
  34570. }
  34571. updateClosestPano(intersect) {
  34572. if (viewer.images360.flying) return;
  34573. intersect = intersect && intersect.orthoIntersect;
  34574. if (!intersect) return;
  34575. intersect = intersect.clone().setZ(0);
  34576. var minDis = 20; //距离鼠标不能太远
  34577. var filterFuncs = [Images360.filters.isEnabled(), Images360.filters.isVisible(),
  34578. //只走显示的点,否则会走到别的层
  34579. pano => {
  34580. return pano.position.clone().setZ(0).distanceTo(intersect) < minDis;
  34581. }];
  34582. var pano = Common.find(viewer.images360.panos, filterFuncs, [Images360.sortFunctions.floorDisSquaredToPoint(intersect)]);
  34583. if (pano && pano != viewer.images360.currentPano) {
  34584. viewer.images360.flyToPano(pano);
  34585. }
  34586. }
  34587. fitPanosToViewport() {
  34588. //使所有漫游点占满viewport
  34589. //var w = viewer.bound.boundSize.x;
  34590. var boundSize = viewer.images360.bound.size.clone().multiplyScalar(1.1);
  34591. boundSize.max(new Vector3(4, 4, 4));
  34592. var endPosition = viewer.images360.bound.center.clone();
  34593. this.moveTo(endPosition, boundSize, 0);
  34594. }
  34595. fitToPointcloud(pointcloud) {
  34596. var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 400;
  34597. var boundSize = pointcloud.bound.getSize(new Vector3()); /* .multiplyScalar(1.1); */
  34598. boundSize.max(new Vector3(4, 4, 4));
  34599. var endPosition = pointcloud.bound.getCenter(new Vector3());
  34600. this.moveTo(endPosition, boundSize, duration); //给点duration去变化 否则地图放大后所占的还是很小
  34601. }
  34602. initFitView() {
  34603. var dis = 5,
  34604. px = 70; //地图上px像素长度代表的距离为dis //px是手动缩放到5m后发现是这个长度
  34605. var zoom = px / dis;
  34606. this.camera.zoom = zoom;
  34607. this.moveTo(viewer.images360.position /* viewer.images360.bound.center */);
  34608. this.camera.updateProjectionMatrix();
  34609. }
  34610. fitToDatasets(datasets) {
  34611. var bound = new Box3();
  34612. datasets.forEach(e => bound.union(e.bound));
  34613. var center = bound.getCenter(new Vector3());
  34614. var size = bound.getSize(new Vector3());
  34615. this.moveTo(center, size, 200); //给duration是为了顺应视口大小改变,缓冲
  34616. }
  34617. moveTo(endPosition, boundSize) {
  34618. var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  34619. var margin = arguments.length > 3 ? arguments[3] : undefined;
  34620. var easeName = arguments.length > 4 ? arguments[4] : undefined;
  34621. var callback = arguments.length > 5 ? arguments[5] : undefined;
  34622. //前两个参数有xy即可
  34623. endPosition = new Vector3(endPosition.x, endPosition.y, Potree.config.map.cameraHeight);
  34624. this.view.moveOrthoCamera(this.viewports[0], {
  34625. endPosition,
  34626. boundSize,
  34627. margin,
  34628. callback
  34629. }, duration, easeName);
  34630. /* let endZoom, startZoom = this.camera.zoom
  34631. //修改相机为bound中心,这样能看到全部(宽度范围内)
  34632. this.view.setView({ position:endPosition, duration,
  34633. callback:()=>{//done
  34634. },
  34635. onUpdate:(progress)=>{
  34636. if(boundSize){
  34637. let aspect = boundSize.x / boundSize.y
  34638. let w, h;
  34639. if(this.camera.aspect > aspect){//视野更宽则用bound的纵向来决定
  34640. h = boundSize.y
  34641. //w = h * this.camera.aspect
  34642. endZoom = this.viewports[0].resolution.y / h
  34643. }else{
  34644. w = boundSize.x;
  34645. //h = w / this.camera.aspect
  34646. endZoom = this.viewports[0].resolution.x / w
  34647. }
  34648. //onUpdate时更新endzoom是因为画布大小可能更改
  34649. this.camera.zoom = endZoom * progress + startZoom * (1 - progress)
  34650. this.camera.updateProjectionMatrix()
  34651. }
  34652. },
  34653. Easing:easeName
  34654. }) */
  34655. }
  34656. updateWhenAtViewer(e) {
  34657. //两个触发来源: 1 camera_changed时 2 mapLayer.needUpdate时。 render在viewer中执行
  34658. if (this.attachedToViewer) {
  34659. if (this.started) this.mapLayer.update();
  34660. this.needRender = true;
  34661. }
  34662. }
  34663. update(delta, areaSize) {
  34664. if (!this.visible && !this.attachedToViewer) return;
  34665. if (this.attachedToViewer) {
  34666. if (this.mapLayer.needUpdate) {
  34667. this.updateWhenAtViewer();
  34668. }
  34669. return;
  34670. }
  34671. this.updateScreenSize();
  34672. this.controls.update(delta);
  34673. this.view.applyToCamera(this.camera);
  34674. var changed = this.cameraChanged();
  34675. if (this.started && (changed || this.mapLayer.needUpdate)) this.mapLayer.update();
  34676. if (changed /*|| || this.needRender */) {
  34677. /* this.dispatchEvent({
  34678. type: "camera_changed",
  34679. camera: this.camera,
  34680. viewport : this.viewports[0]
  34681. }) */
  34682. this.mapChanged = true;
  34683. this.needRender = true;
  34684. this.updateCursor(); //更改大小
  34685. }
  34686. this.render();
  34687. }
  34688. attachToMainViewer(state, desc) {
  34689. var mapRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.5;
  34690. var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  34691. //转移到viewer中。测量时展示or截图需要
  34692. if (!Potree.settings.isOfficial) this.renderArea.style.display = state ? 'none' : 'block';
  34693. if (state) {
  34694. this.enabledOld = this.enabled;
  34695. this.enabled = true;
  34696. if (mapRatio != 'dontSet') {
  34697. this.changeSplitScreenDir(options.dir, mapRatio);
  34698. if (this.attachedToViewer) {
  34699. //this.fitPanosToViewport()
  34700. viewer.updateScreenSize({
  34701. forceUpdateSize: true
  34702. });
  34703. return;
  34704. }
  34705. viewer.viewports = [viewer.mainViewport, viewer.mapViewer.viewports[0]]; //因为mainViewer的相机变化会触发map的变化,所以先渲染mainViewer
  34706. }
  34707. if (desc == 'measure') this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene); //虽然用的是viewer的inputHandler,但借用了this.inputHandler的interactiveScenes
  34708. else if (desc == 'split4Screens') {
  34709. this.inputHandler.registerInteractiveScene(viewer.scene.scene);
  34710. }
  34711. } else {
  34712. if (!this.attachedToViewer) return;
  34713. viewer.mainViewport.left = 0;
  34714. viewer.mainViewport.bottom = 0;
  34715. viewer.mainViewport.width = 1;
  34716. viewer.mainViewport.height = 1;
  34717. this.viewports[0].width = 1;
  34718. this.viewports[0].bottom = 0;
  34719. this.viewports[0].height = 1;
  34720. this.viewports[0].left = 0;
  34721. this.renderMeasure || this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  34722. this.inputHandler.unregisterInteractiveScene(viewer.scene.scene);
  34723. viewer.viewports = [viewer.mainViewport];
  34724. this.updateScreenSize({
  34725. forceUpdateSize: true
  34726. }); //更新相机projectionMatrix
  34727. }
  34728. //if(desc == 'measure')this.renderMeasure = state
  34729. this.attachedToViewer = state;
  34730. viewer.updateScreenSize({
  34731. forceUpdateSize: true
  34732. });
  34733. //mapRatio != 'dontSet' && !options.dontFit && this.moveTo(...)//要写在updateScreenSize后面,因为要根据视图大小来fit
  34734. if (options.moveToCurrentPos) {
  34735. var boundSize = new Vector2(10, 10);
  34736. var duration = 1000;
  34737. this.moveTo(viewer.images360.position.clone(), boundSize, duration);
  34738. }
  34739. this.needRender = true;
  34740. }
  34741. setDrawMeasure(draw) {
  34742. this.renderMeasure = !!draw;
  34743. if (draw) {
  34744. this.inputHandler.registerInteractiveScene(viewer.measuringTool.scene);
  34745. } else {
  34746. this.inputHandler.unregisterInteractiveScene(viewer.measuringTool.scene);
  34747. }
  34748. }
  34749. changeSplitScreenDir(dir, mapRatio) {
  34750. //左右 | 上下
  34751. //if(!dir || dir == this.dir)return
  34752. if (dir) this.splitDir = dir;
  34753. this.updateSplitSize(mapRatio);
  34754. /* if(this.attachedToViewer){ //如果已经分屏了,中途修改方向的话……
  34755. this.updateSplitSize()
  34756. } */
  34757. }
  34758. updateSplitSize(mapRatio) {
  34759. if (mapRatio != void 0) this.mapRatio = mapRatio;
  34760. //console.log(this.mapRatio)
  34761. if (this.splitDir == 'leftRight') {
  34762. //地图在左方
  34763. viewer.mainViewport.left = this.mapRatio;
  34764. viewer.mainViewport.width = 1 - this.mapRatio;
  34765. this.viewports[0].width = this.mapRatio;
  34766. viewer.mainViewport.bottom = this.viewports[0].bottom = 0;
  34767. viewer.mainViewport.height = this.viewports[0].height = 1;
  34768. } else if (this.splitDir == 'upDown') {
  34769. //地图在下方
  34770. viewer.mainViewport.bottom = this.mapRatio;
  34771. viewer.mainViewport.height = 1 - this.mapRatio;
  34772. this.viewports[0].height = this.mapRatio;
  34773. viewer.mainViewport.left = this.viewports[0].left = 0;
  34774. viewer.mainViewport.width = this.viewports[0].width = 1;
  34775. }
  34776. if (this.attachedToViewer) {
  34777. viewer.updateScreenSize({
  34778. forceUpdateSize: true
  34779. });
  34780. }
  34781. }
  34782. render1() {
  34783. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  34784. //viewer的preserveDrawingBuffer为false时的版本
  34785. var needCopy, waitCopy;
  34786. if (!this.visible && !this.attachedToViewer || !this.needRender && !params.force) {
  34787. if (this.attachedToViewer) {
  34788. needCopy = true;
  34789. } else {
  34790. return;
  34791. }
  34792. }
  34793. waitCopy = this.attachedToViewer && this.needRender && !params.force; //是否写入到copyBuffer。双屏时,若needRender就拷贝到copyBuffer中,双屏时就直接使用copyBuffer。 四屏时因渲染点云会每帧都渲染,所以不需要缓存。
  34794. var renderer = params.renderer || this.renderer;
  34795. if (waitCopy) {
  34796. this.copyBuffer.setSize(params.viewport.resolution2.x, params.viewport.resolution2.y);
  34797. renderer.setRenderTarget(this.copyBuffer);
  34798. } else if (params.target) {
  34799. renderer.setRenderTarget(params.target);
  34800. }
  34801. /* if(params.resize){
  34802. this.emitResizeMsg(new THREE.Vector2(params.width,params.height, viewport:params.viewport))
  34803. } */
  34804. params.clear ? params.clear() : renderer.clear();
  34805. if (!needCopy || waitCopy) {
  34806. //重绘
  34807. viewer.dispatchEvent({
  34808. type: "render.begin",
  34809. viewer: this,
  34810. viewport: this.viewports[0],
  34811. params
  34812. });
  34813. Potree.Utils.setCameraLayers(this.camera, ['map', 'mapObjects', 'bothMapAndScene']);
  34814. if (this.mapGradientBG) {
  34815. //渲染背景
  34816. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  34817. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  34818. }
  34819. renderer.render(this.scene, this.camera);
  34820. renderer.render(viewer.scene.scene, this.camera);
  34821. //测量线等
  34822. //params.renderOverlay && params.renderOverlay( $.extend({}, params, { isMap:true }))
  34823. renderer.setRenderTarget(params.target || null);
  34824. }
  34825. if (needCopy || waitCopy) {
  34826. //使用缓存 ----当viewer的preserveDrawingBuffer为false的话,使用buffer
  34827. this.copyPass.render(null, null, null, renderer, params.target || null, this.copyBuffer);
  34828. }
  34829. this.needRender = false;
  34830. return true;
  34831. }
  34832. clear(params) {
  34833. if (this.transparentBG) {
  34834. this.renderer.setClearColor(0x000000, 0);
  34835. } else {
  34836. this.renderer.setClearColor(Potree.config.mapBG, 1);
  34837. }
  34838. (params.renderer || this.renderer).clear();
  34839. }
  34840. //拆成两次渲染,一个地图一个其他物体,且地图渲染后保存在buffer中,只有当地图变化后才重渲染。
  34841. render() {
  34842. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  34843. if (!this.visible && !this.attachedToViewer || !this.needRender && !params.force) {
  34844. //注意:mapViewer.needRender的权重高于它的viewport的needRender,也就是说,当attachedToViewer时,viewer即使needRender, mapViewer也不一定会渲染。
  34845. return;
  34846. }
  34847. viewer.addTimeMark('mapRender', 'start');
  34848. var renderer = params.renderer || this.renderer;
  34849. if (this.mapChanged) {
  34850. //渲染地图背景
  34851. renderer.setRenderTarget(this.copyBuffer);
  34852. params.clear ? params.clear(params) : this.clear(params);
  34853. if (this.mapGradientBG) {
  34854. //渲染背景
  34855. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  34856. renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  34857. }
  34858. Potree.Utils.setCameraLayers(this.camera, ['map']);
  34859. renderer.render(this.scene, this.camera);
  34860. params.renderBG && params.renderBG(this.viewports[0]);
  34861. this.mapChanged = false;
  34862. renderer.setRenderTarget(params.target || null);
  34863. }
  34864. params.clear ? params.clear(params) : this.clear(params);
  34865. this.copyPass.render(null, null, null, renderer, params.target || null, this.copyBuffer); //拷贝地图背景
  34866. renderer.clearDepth(); //防止地图遮挡其他物体
  34867. //绘制其他物体
  34868. Potree.Utils.setCameraLayers(this.camera, ['mapObjects', 'bothMapAndScene']);
  34869. viewer.dispatchEvent({
  34870. type: "render.begin",
  34871. viewer: this,
  34872. viewport: this.viewports[0],
  34873. params
  34874. });
  34875. this.attachedToViewer || renderer.render(viewer.scene.scene, this.camera); //类同renderOverlay
  34876. renderer.render(this.scene, this.camera);
  34877. if (!this.attachedToViewer && this.renderMeasure) {
  34878. //在未attach到主页面时也要渲染测量线
  34879. viewer.dispatchEvent({
  34880. type: "render.pass.perspective_overlay",
  34881. camera: this.camera,
  34882. /* screenshot:params.screenshot, */viewport: this.viewports[0],
  34883. renderer
  34884. });
  34885. }
  34886. renderer.setRenderTarget(null);
  34887. this.needRender = false;
  34888. viewer.addTimeMark('mapRender', 'end');
  34889. return true;
  34890. }
  34891. renderOverlay() {
  34892. //偶尔需要绘制测量线
  34893. viewer.renderOverlay({
  34894. camera: this.camera,
  34895. viewport: this.viewports[0],
  34896. renderer: this.renderer
  34897. });
  34898. }
  34899. }
  34900. /*
  34901. 渲染顺序:
  34902. 地图
  34903. 背景Overlay
  34904. 地图scene的物体,如cursor、 marker
  34905. 点云(如果有)
  34906. overlay,两层:第一层:viewer的scene中bothMapAndScene的如reticule. 第二层:如测量线(attachToMainViewer时才渲染)
  34907. */
  34908. //本地调试地图白屏是因为代码自动更新了 但没刷新
  34909. class U {
  34910. static toVector3(v, offset) {
  34911. return new Vector3().fromArray(v, offset || 0);
  34912. }
  34913. static toBox3(b) {
  34914. return new Box3(U.toVector3(b), U.toVector3(b, 3));
  34915. }
  34916. static findDim(schema, name) {
  34917. var dim = schema.find(dim => dim.name == name);
  34918. if (!dim) throw new Error('Failed to find ' + name + ' in schema');
  34919. return dim;
  34920. }
  34921. static sphereFrom(b) {
  34922. return b.getBoundingSphere(new Sphere());
  34923. }
  34924. }
  34925. ;
  34926. class PointCloudEptGeometry {
  34927. constructor(url, info) {
  34928. var version = info.version;
  34929. var schema = info.schema;
  34930. var bounds = info.bounds;
  34931. var boundsConforming = info.boundsConforming;
  34932. var xyz = [U.findDim(schema, 'X'), U.findDim(schema, 'Y'), U.findDim(schema, 'Z')];
  34933. var scale = xyz.map(d => d.scale || 1);
  34934. var offset = xyz.map(d => d.offset || 0);
  34935. this.eptScale = U.toVector3(scale);
  34936. this.eptOffset = U.toVector3(offset);
  34937. this.url = url;
  34938. this.info = info;
  34939. this.type = 'ept';
  34940. this.schema = schema;
  34941. this.span = info.span || info.ticks;
  34942. this.boundingBox = U.toBox3(bounds);
  34943. this.tightBoundingBox = U.toBox3(boundsConforming);
  34944. this.offset = U.toVector3([0, 0, 0]);
  34945. this.boundingSphere = U.sphereFrom(this.boundingBox);
  34946. this.tightBoundingSphere = U.sphereFrom(this.tightBoundingBox);
  34947. this.version = new Potree.Version('1.7');
  34948. this.projection = null;
  34949. this.fallbackProjection = null;
  34950. if (info.srs && info.srs.horizontal) {
  34951. this.projection = info.srs.authority + ':' + info.srs.horizontal;
  34952. }
  34953. if (info.srs.wkt) {
  34954. if (!this.projection) this.projection = info.srs.wkt;else this.fallbackProjection = info.srs.wkt;
  34955. }
  34956. {
  34957. // TODO [mschuetz]: named projections that proj4 can't handle seem to cause problems.
  34958. // remove them for now
  34959. try {
  34960. proj4(this.projection);
  34961. } catch (e) {
  34962. this.projection = null;
  34963. }
  34964. }
  34965. {
  34966. var attributes = new PointAttributes();
  34967. attributes.add(PointAttribute.POSITION_CARTESIAN);
  34968. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  34969. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  34970. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  34971. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  34972. attributes.add(new PointAttribute("returnNumber", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  34973. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  34974. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  34975. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  34976. this.pointAttributes = attributes;
  34977. }
  34978. this.spacing = (this.boundingBox.max.x - this.boundingBox.min.x) / this.span;
  34979. var hierarchyType = info.hierarchyType || 'json';
  34980. var dataType = info.dataType;
  34981. if (dataType == 'laszip') {
  34982. this.loader = new Potree.EptLaszipLoader();
  34983. } else if (dataType == 'binary') {
  34984. this.loader = new Potree.EptBinaryLoader();
  34985. } else if (dataType == 'zstandard') {
  34986. this.loader = new Potree.EptZstandardLoader();
  34987. } else {
  34988. throw new Error('Could not read data type: ' + dataType);
  34989. }
  34990. }
  34991. }
  34992. ;
  34993. class EptKey {
  34994. constructor(ept, b, d, x, y, z) {
  34995. this.ept = ept;
  34996. this.b = b;
  34997. this.d = d;
  34998. this.x = x || 0;
  34999. this.y = y || 0;
  35000. this.z = z || 0;
  35001. }
  35002. name() {
  35003. return this.d + '-' + this.x + '-' + this.y + '-' + this.z;
  35004. }
  35005. step(a, b, c) {
  35006. var min = this.b.min.clone();
  35007. var max = this.b.max.clone();
  35008. var dst = new Vector3().subVectors(max, min);
  35009. if (a) min.x += dst.x / 2;else max.x -= dst.x / 2;
  35010. if (b) min.y += dst.y / 2;else max.y -= dst.y / 2;
  35011. if (c) min.z += dst.z / 2;else max.z -= dst.z / 2;
  35012. return new Potree.EptKey(this.ept, new Box3(min, max), this.d + 1, this.x * 2 + a, this.y * 2 + b, this.z * 2 + c);
  35013. }
  35014. children() {
  35015. var result = [];
  35016. for (var a = 0; a < 2; ++a) {
  35017. for (var b = 0; b < 2; ++b) {
  35018. for (var c = 0; c < 2; ++c) {
  35019. var add = this.step(a, b, c).name();
  35020. if (!result.includes(add)) result = result.concat(add);
  35021. }
  35022. }
  35023. }
  35024. return result;
  35025. }
  35026. }
  35027. class PointCloudEptGeometryNode extends PointCloudTreeNode {
  35028. constructor(ept, b, d, x, y, z) {
  35029. super();
  35030. this.ept = ept;
  35031. this.key = new Potree.EptKey(this.ept, b || this.ept.boundingBox, d || 0, x, y, z);
  35032. this.id = PointCloudEptGeometryNode.IDCount++;
  35033. this.geometry = null;
  35034. this.boundingBox = this.key.b;
  35035. this.tightBoundingBox = this.boundingBox;
  35036. this.spacing = this.ept.spacing / Math.pow(2, this.key.d);
  35037. this.boundingSphere = U.sphereFrom(this.boundingBox);
  35038. // These are set during hierarchy loading.
  35039. this.hasChildren = false;
  35040. this.children = {};
  35041. this.numPoints = -1;
  35042. this.level = this.key.d;
  35043. this.loaded = false;
  35044. this.loading = false;
  35045. this.oneTimeDisposeHandlers = [];
  35046. var k = this.key;
  35047. this.name = this.toPotreeName(k.d, k.x, k.y, k.z);
  35048. this.index = parseInt(this.name.charAt(this.name.length - 1));
  35049. }
  35050. isGeometryNode() {
  35051. return true;
  35052. }
  35053. getLevel() {
  35054. return this.level;
  35055. }
  35056. isTreeNode() {
  35057. return false;
  35058. }
  35059. isLoaded() {
  35060. return this.loaded;
  35061. }
  35062. getBoundingSphere() {
  35063. return this.boundingSphere;
  35064. }
  35065. getBoundingBox() {
  35066. return this.boundingBox;
  35067. }
  35068. url() {
  35069. return this.ept.url + 'ept-data/' + this.filename();
  35070. }
  35071. getNumPoints() {
  35072. return this.numPoints;
  35073. }
  35074. filename() {
  35075. return this.key.name();
  35076. }
  35077. getChildren() {
  35078. var children = [];
  35079. for (var i = 0; i < 8; i++) {
  35080. if (this.children[i]) {
  35081. children.push(this.children[i]);
  35082. }
  35083. }
  35084. return children;
  35085. }
  35086. addChild(child) {
  35087. this.children[child.index] = child;
  35088. child.parent = this;
  35089. }
  35090. load() {
  35091. if (this.loaded || this.loading) return;
  35092. if (Potree.numNodesLoading >= Potree.maxNodesLoading) return;
  35093. this.loading = true;
  35094. ++Potree.numNodesLoading;
  35095. if (this.numPoints == -1) this.loadHierarchy();
  35096. this.loadPoints();
  35097. }
  35098. loadPoints() {
  35099. this.ept.loader.load(this);
  35100. }
  35101. loadHierarchy() {
  35102. var _this = this;
  35103. return _asyncToGenerator(function* () {
  35104. var nodes = {};
  35105. nodes[_this.filename()] = _this;
  35106. _this.hasChildren = false;
  35107. var eptHierarchyFile = "".concat(_this.ept.url, "ept-hierarchy/").concat(_this.filename(), ".json");
  35108. var response = yield fetch(eptHierarchyFile);
  35109. var hier = yield response.json();
  35110. // Since we want to traverse top-down, and 10 comes
  35111. // lexicographically before 9 (for example), do a deep sort.
  35112. var keys = Object.keys(hier).sort((a, b) => {
  35113. var [da, xa, ya, za] = a.split('-').map(n => parseInt(n, 10));
  35114. var [db, xb, yb, zb] = b.split('-').map(n => parseInt(n, 10));
  35115. if (da < db) return -1;
  35116. if (da > db) return 1;
  35117. if (xa < xb) return -1;
  35118. if (xa > xb) return 1;
  35119. if (ya < yb) return -1;
  35120. if (ya > yb) return 1;
  35121. if (za < zb) return -1;
  35122. if (za > zb) return 1;
  35123. return 0;
  35124. });
  35125. keys.forEach(v => {
  35126. var [d, x, y, z] = v.split('-').map(n => parseInt(n, 10));
  35127. var a = x & 1,
  35128. b = y & 1,
  35129. c = z & 1;
  35130. var parentName = d - 1 + '-' + (x >> 1) + '-' + (y >> 1) + '-' + (z >> 1);
  35131. var parentNode = nodes[parentName];
  35132. if (!parentNode) return;
  35133. parentNode.hasChildren = true;
  35134. var key = parentNode.key.step(a, b, c);
  35135. var node = new Potree.PointCloudEptGeometryNode(_this.ept, key.b, key.d, key.x, key.y, key.z);
  35136. node.level = d;
  35137. node.numPoints = hier[v];
  35138. parentNode.addChild(node);
  35139. nodes[key.name()] = node;
  35140. });
  35141. })();
  35142. }
  35143. doneLoading(bufferGeometry, tightBoundingBox, np, mean) {
  35144. bufferGeometry.boundingBox = this.boundingBox;
  35145. this.geometry = bufferGeometry;
  35146. this.tightBoundingBox = tightBoundingBox;
  35147. this.numPoints = np;
  35148. this.mean = mean;
  35149. this.loaded = true;
  35150. this.loading = false;
  35151. --Potree.numNodesLoading;
  35152. }
  35153. toPotreeName(d, x, y, z) {
  35154. var name = 'r';
  35155. for (var i = 0; i < d; ++i) {
  35156. var shift = d - i - 1;
  35157. var mask = 1 << shift;
  35158. var step = 0;
  35159. if (x & mask) step += 4;
  35160. if (y & mask) step += 2;
  35161. if (z & mask) step += 1;
  35162. name += step;
  35163. }
  35164. return name;
  35165. }
  35166. dispose() {
  35167. if (this.geometry && this.parent != null) {
  35168. this.geometry.dispose();
  35169. this.geometry = null;
  35170. this.loaded = false;
  35171. // this.dispatchEvent( { type: 'dispose' } );
  35172. for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  35173. var handler = this.oneTimeDisposeHandlers[i];
  35174. handler();
  35175. }
  35176. this.oneTimeDisposeHandlers = [];
  35177. }
  35178. }
  35179. }
  35180. PointCloudEptGeometryNode.IDCount = 0;
  35181. class ExtendPointCloudOctree extends PointCloudOctree {
  35182. constructor(geometry, material) {
  35183. material = material || new ExtendPointCloudMaterial();
  35184. super(geometry, material);
  35185. //xzw move from material 。 adaptive_point_size才使用
  35186. /* this.visibleNodesTexture = Utils.generateDataTexture(2048, 1, new THREE.Color(0xffffff));
  35187. this.visibleNodesTexture.minFilter = THREE.NearestFilter;
  35188. this.visibleNodesTexture.magFilter = THREE.NearestFilter; */
  35189. this.boundingBox = this.pcoGeometry.tightBoundingBox; //this.pcoGeometry.boundingBox; //boundingBox是正方体,所以换掉
  35190. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  35191. this.nodeMaxLevel = 0; //add
  35192. if (!this.pcoGeometry.loader.version.equalOrHigher('1.5')) {
  35193. //las 一级一级增长的,但是testNodeMaxLevel时需要大于0
  35194. this.nodeMaxLevel = 1; //add
  35195. }
  35196. this.maxLevel = Infinity;
  35197. this.temp = {
  35198. sizeFitToLevel: {},
  35199. opacity: {}
  35200. }; //add
  35201. //add
  35202. this.panos = [];
  35203. this.matrixAutoUpdate = false; //最好禁止updateMatrix 直接使用matrixWorld
  35204. this.orientationUser = 0;
  35205. this.translateUser = new Vector3();
  35206. this.rotateMatrix = new Matrix4();
  35207. this.transformMatrix = new Matrix4(); // 数据集的变化矩阵
  35208. this.transformInvMatrix = new Matrix4();
  35209. /* this.transformMatrix2 = new THREE.Matrix4;// 数据集的变化矩阵
  35210. this.transformInvMatrix2 = new THREE.Matrix4; */
  35211. this.rotateInvMatrix = new Matrix4();
  35212. this.material.spacing = this.pcoGeometry.spacing; //初始化一下 以便于设置pointsize
  35213. this.nodeMaxLevelPredict = this.predictNodeMaxLevel(); //预测maxNodeLevel
  35214. this.testMaxNodeCount = this.testMaxNodeCount2 = 0;
  35215. this._visible = true;
  35216. this.pcoGeometry.addEventListener('updateNodeMaxLevel', this.updateNodeMaxLevel.bind(this));
  35217. this.isPointcloud = true; //add
  35218. }
  35219. /*
  35220. 注释:node的level从最大的box 0开始。
  35221. 且加载任意一个node必定也会加载它的所有祖先。(如visibleNodes中有一个level为4,则一定有3,2,1,0)
  35222. visibleNodes就是所有可见的node,比如:
  35223. 如果相机在0这个位置朝下,这时候的visibleNodes中只有一个level为0的node;
  35224. 而如果朝上看,上方的几个node如果在视野中占据足够大的位置的话,就会加载。
  35225. 如果相机在2这个位置朝上,这时候的visibleNodes中所包含的level为: 0,1,2
  35226. ________________
  35227. | | | |
  35228. |__2| | |
  35229. | 1 | 1 |
  35230. |_______|_______|
  35231. | |
  35232. | |
  35233. | 0 |
  35234. |_______________|
  35235. 查看box可在potree中开启
  35236. */
  35237. updateNodeMaxLevel(e) {
  35238. //目前点云包含node的最高level
  35239. var level = Math.max(e.level, this.nodeMaxLevel);
  35240. if (level != this.nodeMaxLevel) {
  35241. this.nodeMaxLevel = level;
  35242. //viewer.dispatchEvent({type:'updateNodeMaxLevel', pointcloud: this, nodeMaxLevel:level})
  35243. console.log('updateNodeMaxLevel ' + this.dataset_id + " : " + this.nodeMaxLevel);
  35244. setTimeout(() => {
  35245. this.setPointLevel(); //重新计算 延迟是因为testNodeMax会变回旧的
  35246. }, 1);
  35247. if (!Potree.settings.sizeFitToLevel) {
  35248. this.changePointSize();
  35249. }
  35250. }
  35251. } //注:在没有加载到真实的 nodeMaxLevel之前,点云会显示得偏大
  35252. //panoEdit时比预测值小很多?
  35253. testMaxNodeLevel(camera) {
  35254. //手动使maxLevel达到最高,从而迫使updateNodeMaxLevel。 因为Potree.settings.pointDensity 不为 'high'时,maxLevel不是所加载的最高,就很容易加载不出下一个层级,导致无法知道nodeMaxLevel
  35255. if (this.testMaxNodeLevelDone) return;
  35256. //if(this.nodeMaxLevel > this.nodeMaxLevelPredict.min )return
  35257. if (this.nodeMaxLevel == 0) return true;
  35258. if (camera.type == "OrthographicCamera" || this.testMaxNodeCount < 50) {
  35259. if (!Potree.Utils.isInsideFrustum(this.bound, camera)) {
  35260. return true;
  35261. }
  35262. } else if (!viewer.atDatasets.includes(this)) return true; //否则老远就count++
  35263. var levels = this.visibleNodes.map(e => e.getLevel());
  35264. var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  35265. if (actMaxLevel < this.maxLevel) return true; // 还没加载到能加载到的最高。 但在细节设置较低时,排除作用微弱。
  35266. //尝试加载出更高级的level
  35267. var old = this.maxLevel;
  35268. this.maxLevel = 12;
  35269. //var visibleNodes1 = this.visibleNodes.map(e=>e.getLevel())
  35270. //console.log('visibleNodes1',visibleNodes1)
  35271. Potree.updatePointClouds([this], viewer.scene.getActiveCamera(), viewer.mainViewport.resolution);
  35272. //不在camera可视范围内还是加载不出来。即使临时修改位置
  35273. var visibleNodes2 = this.visibleNodes.map(e => e.getLevel());
  35274. //console.log('visibleNodes2',visibleNodes2)
  35275. this.maxLevel = old;
  35276. this.testMaxNodeCount++;
  35277. viewer.testMaxNodeCount++;
  35278. //console.log('testMaxNodeCount', this.dataset_id, this.testMaxNodeCount, 'nodeMaxLevel', this.nodeMaxLevel )
  35279. if (this.testMaxNodeCount == Potree.config.testNodeCount1) {
  35280. //差不多等当前所在数据集nodeMaxLevel加载出来
  35281. this.changePointSize(); //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  35282. }
  35283. if (this.testMaxNodeCount > 100) {
  35284. console.log('testMaxNodeLevel次数超出,强制结束:', this.dataset_id, this.nodeMaxLevel, this.nodeMaxLevelPredict.min);
  35285. this.testMaxNodeLevelDone = 'moreThanMaxCount';
  35286. return; //在可以看见点云的情况下,超时,有可能是预测的max是错的
  35287. }
  35288. if (this.nodeMaxLevel < this.nodeMaxLevelPredict.min) return true; //仍需要继续testMaxNodeLevel
  35289. this.testMaxNodeCount2++; // 已经> this.nodeMaxLevelPredict.min 后,开始计数。因为min可能低于真实nodeMaxLevel所以要再试几次
  35290. if (this.testMaxNodeCount2 < 50) return true; //再试几次 ( 主要是细节调得低时需要多测几次才加载到
  35291. this.testMaxNodeLevelDone = true;
  35292. }
  35293. updateMatrixWorld(force) {
  35294. //add
  35295. super.updateMatrixWorld(force);
  35296. this.matrixWorldInverse = this.matrixWorld.clone().invert();
  35297. }
  35298. setPointLevel() {
  35299. var pointDensity = Potree.settings.pointDensity;
  35300. var config = Potree.config.pointDensity[pointDensity];
  35301. if (!config) return;
  35302. /* if(this.testingMaxLevel){
  35303. this.maxLevel = 12;//先加载到最大的直到测试完毕。由于5个level为一组来加载,所以如果写4最高能加载到5,如果写5最高能加载到下一个级别的最高也就是10
  35304. //console.log('maxLevel: '+e.maxLevel + ' testingMaxLevel中 ' )
  35305. }else{ */
  35306. var percent = config.percentByUser && Potree.settings.UserDensityPercent != void 0 ? Potree.settings.UserDensityPercent : config.maxLevelPercent;
  35307. this.maxLevel = Math.round(percent * this.nodeMaxLevel);
  35308. //console.log('maxLevel: '+e.maxLevel + ', density : '+Potree.settings.pointDensity, ", percent :"+percent);
  35309. if (Potree.settings.sizeFitToLevel) {
  35310. this.changePointSize();
  35311. }
  35312. this.changePointOpacity();
  35313. //}
  35314. viewer.dealBeforeRender || viewer.dispatchEvent('content_changed');
  35315. }
  35316. //预测可能的nodeMaxLevel:
  35317. predictNodeMaxLevel() {
  35318. //预测maxNodeLevel。 可能只适用于我们相机拍的点云
  35319. var spacing = {
  35320. min: 0.005,
  35321. max: 0.014
  35322. }; //最小节的两点间的距离 ,获得方法:spacing / Math.pow(2, nodeMaxLevel)。 目前观测的我们自己拍的这个数值的范围大概是这样
  35323. var min = Math.log2(this.material.spacing / spacing.max); //有见过最大是0.01368
  35324. var max = Math.log2(this.material.spacing / spacing.min); //大部分是 0.006
  35325. //console.log('predictNodeMaxLevel:', this.name , min, max )
  35326. //只对深时相机,其他相机不准
  35327. return {
  35328. min,
  35329. max
  35330. };
  35331. }
  35332. getHighestNodeSpacing() {
  35333. return this.material.spacing / Math.pow(2, this.nodeMaxLevel); //前提是这个nodeMaxLevel是准确的
  35334. }
  35335. updateMaterial(material, visibleNodes, camera, renderer, resolution) {
  35336. //改
  35337. material.fov = camera.fov * (Math.PI / 180);
  35338. /* material.screenWidth = renderer.domElement.clientWidth;
  35339. material.screenHeight = renderer.domElement.clientHeight; */
  35340. material.resolution = resolution;
  35341. material.spacing = this.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  35342. material.near = camera.near;
  35343. material.far = camera.far;
  35344. material.uniforms.octreeSize.value = this.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  35345. }
  35346. pick(viewer, viewport, camera, ray) {
  35347. var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  35348. //改
  35349. var renderer = viewer.renderer;
  35350. var pRenderer = viewer.pRenderer;
  35351. viewer.addTimeMark('pick', 'start');
  35352. var getVal = (a, b) => a != void 0 ? a : b;
  35353. var pickWindowSize = params.pickWindowSize; //拾取像素边长,越小越精准,但点云稀疏的话可能容易出现识别不到的情况。 另外左下侧会有缝隙无法识别到,缝隙大小和这个值有关//突然发现pickWindowSize在一百以内的变化对pick费时影响甚微,1和100差1毫秒不到,但400时会多4毫秒
  35354. if (pickWindowSize == void 0) {
  35355. if (Potree.settings.displayMode == 'showPanos') {
  35356. pickWindowSize = 50;
  35357. } else {
  35358. var r0 = this.nodeMaxLevel > 0 ? this.maxLevel / this.nodeMaxLevel : 0.5;
  35359. pickWindowSize = MathUtils.clamp(Math.round((1.1 - r0) * 80), 15, 100);
  35360. }
  35361. }
  35362. if (camera.type == 'OrthographicCamera') {
  35363. var cameraDir = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
  35364. pickWindowSize *= 4; //pointsize比较大时截取太小会没多少点可以选
  35365. }
  35366. var pickOutsideClipRegion = getVal(params.pickOutsideClipRegion, false);
  35367. var size = viewport ? viewport.resolution : renderer.getSize(new Vector2());
  35368. var width = Math.ceil(getVal(params.width, size.width)); //renderTarget大小。影响识别精度
  35369. var height = Math.ceil(getVal(params.height, size.height));
  35370. var screenshot = () => {
  35371. if (window.testScreen) {
  35372. var dataUrl = Potree.Utils.renderTargetToDataUrl(pickState.renderTarget, width, height, renderer);
  35373. Potree.Common.downloadFile(dataUrl, 'screenshot.png');
  35374. window.testScreen = 0;
  35375. }
  35376. };
  35377. var pointSizeType = getVal(params.pointSizeType, this.material.pointSizeType);
  35378. var pointSize = getVal(params.pointSize, this.material.size);
  35379. var nodes = this.nodesOnRay(this.visibleNodes, ray);
  35380. if (nodes.length === 0) {
  35381. return null;
  35382. }
  35383. //console.log('nodes.length != 0', this.name)
  35384. if (!this.pickState) {
  35385. var scene = new Scene();
  35386. var material = new ExtendPointCloudMaterial();
  35387. material.activeAttributeName = "indices"; //indices
  35388. var renderTarget = new WebGLRenderTarget(1, 1, {
  35389. minFilter: LinearFilter,
  35390. magFilter: NearestFilter,
  35391. format: RGBAFormat
  35392. });
  35393. this.pickState = {
  35394. renderTarget: renderTarget,
  35395. material: material,
  35396. scene: scene
  35397. };
  35398. }
  35399. ;
  35400. var pickState = this.pickState;
  35401. var pickMaterial = pickState.material;
  35402. {
  35403. // update pick material
  35404. pickMaterial.pointSizeType = pointSizeType;
  35405. //pickMaterial.shape = this.material.shape;
  35406. pickMaterial.shape = Potree.PointShape.PARABOLOID;
  35407. pickMaterial.uniforms.uFilterReturnNumberRange.value = this.material.uniforms.uFilterReturnNumberRange.value;
  35408. pickMaterial.uniforms.uFilterNumberOfReturnsRange.value = this.material.uniforms.uFilterNumberOfReturnsRange.value;
  35409. pickMaterial.uniforms.uFilterGPSTimeClipRange.value = this.material.uniforms.uFilterGPSTimeClipRange.value;
  35410. pickMaterial.uniforms.uFilterPointSourceIDClipRange.value = this.material.uniforms.uFilterPointSourceIDClipRange.value;
  35411. pickMaterial.size = pointSize;
  35412. pickMaterial.uniforms.minSize.value = this.material.uniforms.minSize.value;
  35413. pickMaterial.uniforms.maxSize.value = this.material.uniforms.maxSize.value;
  35414. pickMaterial.classification = this.material.classification;
  35415. pickMaterial.recomputeClassification();
  35416. //pickClipped判断转移到上一层函数
  35417. var {
  35418. bigClipInBox,
  35419. clipBoxes_in,
  35420. clipBoxes_out
  35421. } = this.material;
  35422. pickMaterial.setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, []);
  35423. this.updateMaterial(pickMaterial, nodes, camera, renderer, new Vector2(width, height));
  35424. }
  35425. pickState.renderTarget.setSize(width, height); //仅绘制屏幕大小的,而不乘以devicePixelRatio
  35426. var pixelPos = new Vector2(params.x, params.y);
  35427. var gl = renderer.getContext();
  35428. //规定渲染范围,只渲染一小块
  35429. /* renderer.setScissorTest(true);
  35430. gl.enable(gl.SCISSOR_TEST);
  35431. gl.scissor(
  35432. parseInt(pixelPos.x - (pickWindowSize - 1) / 2),
  35433. parseInt(pixelPos.y - (pickWindowSize - 1) / 2),
  35434. parseInt(pickWindowSize), parseInt(pickWindowSize));
  35435. */ //---这段没用
  35436. pickState.renderTarget.scissor.set(parseInt(pixelPos.x - (pickWindowSize - 1) / 2), parseInt(pixelPos.y - (pickWindowSize - 1) / 2), parseInt(pickWindowSize), parseInt(pickWindowSize));
  35437. pickState.renderTarget.scissorTest = true;
  35438. renderer.state.buffers.depth.setTest(pickMaterial.depthTest);
  35439. renderer.state.buffers.depth.setMask(pickMaterial.depthWrite);
  35440. renderer.state.setBlending(NoBlending);
  35441. {
  35442. // RENDER
  35443. renderer.setRenderTarget(pickState.renderTarget);
  35444. gl.clearColor(0, 0, 0, 0);
  35445. //renderer.clear(true, true, true);
  35446. var tmp = this.material;
  35447. this.material = pickMaterial;
  35448. pRenderer.renderOctree(this, nodes, camera, pickState.renderTarget); //只绘制ray pick到的部分nodes
  35449. screenshot();
  35450. this.material = tmp;
  35451. }
  35452. var clamp = (number, min, max) => Math.min(Math.max(min, number), max);
  35453. var x = parseInt(clamp(pixelPos.x - (pickWindowSize - 1) / 2, 0, width));
  35454. var y = parseInt(clamp(pixelPos.y - (pickWindowSize - 1) / 2, 0, height));
  35455. /* let w = parseInt(Math.min(x + pickWindowSize, width) - x);
  35456. let h = parseInt(Math.min(y + pickWindowSize, height) - y); */
  35457. var pixelCount = pickWindowSize * pickWindowSize; //w * h;
  35458. var buffer = new Uint8Array(4 * pixelCount);
  35459. //w<pickWindowSize会报错
  35460. gl.readPixels(x, y, pickWindowSize, pickWindowSize, gl.RGBA, gl.UNSIGNED_BYTE, buffer); //这句花费最多时间 pc:2-4, 即使只有1*1像素
  35461. renderer.clear(true, true, true); //绘制完就clear否则download的图会有上次的轨迹
  35462. renderer.setRenderTarget(null);
  35463. renderer.state.reset();
  35464. renderer.setScissorTest(false);
  35465. gl.disable(gl.SCISSOR_TEST);
  35466. var pixels = buffer;
  35467. var ibuffer = new Uint32Array(buffer.buffer); //四个数整合成一个
  35468. // find closest hit inside pixelWindow boundaries
  35469. var min = Number.MAX_VALUE;
  35470. var hits = [],
  35471. hits2 = [],
  35472. rSquare;
  35473. if (!params.all) {
  35474. var r = MathUtils.clamp(Math.floor(pickWindowSize / 2), 1, 40);
  35475. rSquare = r * r;
  35476. }
  35477. for (var u = 0; u < pickWindowSize; u++) {
  35478. for (var v = 0; v < pickWindowSize; v++) {
  35479. var offset = u + v * pickWindowSize;
  35480. var distance = Math.pow(u - (pickWindowSize - 1) / 2, 2) + Math.pow(v - (pickWindowSize - 1) / 2, 2);
  35481. var pcIndex = pixels[4 * offset + 3]; //nodes index(第四位)
  35482. pixels[4 * offset + 3] = 0; //去除nodes index后剩下的是index(前三位)
  35483. var pIndex = ibuffer[offset]; //index
  35484. if (!(pcIndex === 0 && pIndex === 0) && pcIndex !== undefined && pIndex !== undefined) {
  35485. var hit = {
  35486. pIndex: pIndex,
  35487. pcIndex: pcIndex,
  35488. distanceToCenter: distance
  35489. };
  35490. if (params.all) {
  35491. hits.push(hit);
  35492. } else {
  35493. if (hits.length > 0) {
  35494. //最后选取的是最靠近鼠标的那个pick
  35495. if (distance < hits[0].distanceToCenter) {
  35496. hits[0] = hit;
  35497. }
  35498. } else {
  35499. hits.push(hit);
  35500. }
  35501. if (distance < rSquare) hits2.push(hit); //add
  35502. }
  35503. }
  35504. }
  35505. }
  35506. if (!params.all && Potree.settings.pickFrontPointRatio) {
  35507. if (hits2.length) {
  35508. //add
  35509. hits = hits2;
  35510. }
  35511. }
  35512. // { // DEBUG: show panel with pick image
  35513. // let img = Utils.pixelsArrayToImage(buffer, w, h);
  35514. // let screenshot = img.src;
  35515. // if(!this.debugDIV){
  35516. // this.debugDIV = $(`
  35517. // <div id="pickDebug"
  35518. // style="position: absolute;
  35519. // right: 400px; width: 300px;
  35520. // bottom: 44px; width: 300px;
  35521. // z-index: 1000;
  35522. // "></div>`);
  35523. // $(document.body).append(this.debugDIV);
  35524. // }
  35525. // this.debugDIV.empty();
  35526. // this.debugDIV.append($(`<img src="${screenshot}"
  35527. // style="transform: scaleY(-1); width: 300px"/>`));
  35528. // //$(this.debugWindow.document).append($(`<img src="${screenshot}"/>`));
  35529. // //this.debugWindow.document.write('<img src="'+screenshot+'"/>');
  35530. // }
  35531. for (var _hit of hits) {
  35532. var point = {};
  35533. if (!nodes[_hit.pcIndex]) {
  35534. return null;
  35535. }
  35536. var node = nodes[_hit.pcIndex];
  35537. var pc = node.sceneNode;
  35538. var geometry = node.geometryNode.geometry;
  35539. var _loop = function _loop() {
  35540. var attribute = geometry.attributes[attributeName];
  35541. if (attributeName === 'position') {
  35542. var _x = attribute.array[3 * _hit.pIndex + 0];
  35543. var _y = attribute.array[3 * _hit.pIndex + 1];
  35544. var z = attribute.array[3 * _hit.pIndex + 2];
  35545. var position = new Vector3(_x, _y, z);
  35546. position.applyMatrix4(pc.matrixWorld);
  35547. point[attributeName] = position;
  35548. //add
  35549. if (!params.all && Potree.settings.pickFrontPointRatio) {
  35550. if (camera.type == 'OrthographicCamera') {
  35551. var vec = new Vector3().subVectors(position, camera.position);
  35552. _hit.disSquare = vec.projectOnVector(cameraDir).length(); //只考虑到相机的垂直距离
  35553. } else {
  35554. _hit.disSquare = camera.position.distanceTo(position);
  35555. }
  35556. }
  35557. } else if (attributeName === 'indices') {} else {
  35558. var values = attribute.array.slice(attribute.itemSize * _hit.pIndex, attribute.itemSize * (_hit.pIndex + 1));
  35559. if (attribute.potree) {
  35560. var {
  35561. scale,
  35562. offset: _offset
  35563. } = attribute.potree;
  35564. values = values.map(v => v / scale + _offset);
  35565. }
  35566. point[attributeName] = values;
  35567. //debugger;
  35568. //if (values.itemSize === 1) {
  35569. // point[attribute.name] = values.array[hit.pIndex];
  35570. //} else {
  35571. // let value = [];
  35572. // for (let j = 0; j < values.itemSize; j++) {
  35573. // value.push(values.array[values.itemSize * hit.pIndex + j]);
  35574. // }
  35575. // point[attribute.name] = value;
  35576. //}
  35577. }
  35578. };
  35579. for (var attributeName in geometry.attributes) {
  35580. _loop();
  35581. }
  35582. _hit.point = point;
  35583. }
  35584. viewer.addTimeMark('pick', 'end');
  35585. if (params.all) {
  35586. return hits.map(hit => hit.point);
  35587. } else {
  35588. if (hits.length === 0) {
  35589. return null;
  35590. } else {
  35591. if (Potree.settings.pickFrontPointRatio == 0) {
  35592. //如果不需要选偏离镜头近的,就要离中心近的即可
  35593. //console.log(hits[0], hits2, pixelPos)
  35594. return hits[0].point;
  35595. }
  35596. //为了防止透过点云缝隙,选到后排的点云,将选取的位置离相机的距离考虑进去。倾向选择离相机近、且离鼠标位置近的点。(否则按照原方案只选离鼠标位置最近的,可能从高楼不小心走到下层,导航选点也是)
  35597. var sorted1 = hits.sort((a, b) => a.disSquare - b.disSquare).slice();
  35598. var nearest = sorted1[0]; //return nearest.point; //直接用最近点 在点云稀疏时不太跟手,如地面上,最近点往往在鼠标下方
  35599. hits.forEach(hit => {
  35600. var disDiff = hit.disSquare - nearest.disSquare; //和最近点的偏差
  35601. hit.disDiff = disDiff;
  35602. hit.score = -hit.distanceToCenter - disDiff * Potree.settings.pickFrontPointRatio;
  35603. });
  35604. var sorted2 = hits.sort((a, b) => b.score - a.score);
  35605. //console.log(sorted2[0].point.position.z )
  35606. return sorted2[0].point;
  35607. }
  35608. }
  35609. }
  35610. // 设置点大小
  35611. changePointSize(num, sizeFitToLevel) {
  35612. var size, nodeMaxLevel;
  35613. var dontRender = viewer.dealBeforeRender;
  35614. if (this.material.pointSizeType != PointSizeType.ATTENUATED) {
  35615. num && (size = num / Potree.config.material.realPointSize / 1.3);
  35616. } else {
  35617. var num_ = num;
  35618. if (num_ == void 0) {
  35619. num_ = this.temp.pointSize;
  35620. } else {
  35621. this.temp.pointSize = num_;
  35622. }
  35623. num_ = num_ / (Potree.config.material.realPointSize / Potree.config.material.pointSize); //兼容
  35624. //num_ = Math.pow(num_, 1.05) * 5
  35625. nodeMaxLevel = this.testMaxNodeCount >= Potree.config.testNodeCount1 ? this.nodeMaxLevel : Math.max(this.nodeMaxLevel, this.nodeMaxLevelPredict.max); //防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  35626. if (sizeFitToLevel || Potree.settings.sizeFitToLevel) {
  35627. //按照点云质量来调整的版本: 近似将pointSizeType换成ADAPTIVE
  35628. var str = this.temp.pointSize + ':' + this.maxLevel + ':' + nodeMaxLevel;
  35629. var value = this.temp.sizeFitToLevel[str]; //储存。防止每次渲染(反复切换density)都要算。
  35630. if (value) {
  35631. size = value;
  35632. } else {
  35633. if (this.maxLevel == Infinity) return;
  35634. var base = this.material.spacing / Math.pow(2, this.maxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2. (不同场景还是会有偏差)
  35635. var r = nodeMaxLevel > 0 ? this.maxLevel / nodeMaxLevel : 0.5; //越大,越精细,需要越缩小
  35636. base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(r, 3 * r + 0.3)) : 0.1; //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了)
  35637. //base *= nodeMaxLevel > 0 ? Math.max(0.1, Math.pow(this.maxLevel / nodeMaxLevel, 1.1)) : 0.1 //低质量的缩小点,因为视觉上看太大了。navvis是不铺满的,我们也留一点缝隙(但是ortho是不用缩小的,如果能分开判断就好了)
  35638. size = base * 20 * num_; /* * window.devicePixelRatio */
  35639. //在t-8BCqxQAr93 会议室 和 t-e2Kb2iU 隧道 两个场景里调节,因为它们的spacing相差较大,观察会议室墙壁的龟裂程度
  35640. this.temp.sizeFitToLevel[str] = size;
  35641. }
  35642. } else {
  35643. /* let base = 0.007; */var _base = this.material.spacing / Math.pow(2, nodeMaxLevel); //点云大小在level为0时设置为spacing,每长一级,大小就除以2
  35644. //base的数值理论上应该是右侧算出来的,但发现有的场景nodeMaxLevel和nodeMaxLevelPredict差别较大的点云显示也过大,而直接换成固定值反而可以适应所有场景。该固定值来源于 getHighestNodeSpacing 最小值,修改了下。(会不会是我们的相机其实该值是固定的,根据该值算出的spacing才是有误差的? 如果换了相机是否要改值?)
  35645. //2022-12-21又换回非固定值。因为有的场景如SS-t-t01myDqnfE的两个数据集密集程度差别很大,应该将稀疏点云的大小设置的大些。 但是这样的缺点是两个数据集因相接处有大有小无法融合。
  35646. size = _base * 20 * num_; /* * window.devicePixelRatio */
  35647. }
  35648. }
  35649. //console.log('changePointSize:' + this.dataset_id + ' , num: ' + (num && num.toPrecision(3)) + ' , size: ' + size.toPrecision(3), 'nodeMaxLevel', nodeMaxLevel.toPrecision(3), 'testMaxNodeCount',this.testMaxNodeCount /* this.material.spacing */)
  35650. if (size) {
  35651. if (Potree.settings.sortCloudMat) {
  35652. //被废弃,不给material分组了
  35653. this.size = size;
  35654. this.material.size = size;
  35655. } else {
  35656. this.material.size = size;
  35657. }
  35658. }
  35659. dontRender || viewer.dispatchEvent('content_changed');
  35660. }
  35661. // 设置点透明度
  35662. changePointOpacity(num, canMoreThanOne) {
  35663. //num:0-1 navvis用的是亮度
  35664. if (num == void 0) {
  35665. num = this.temp.pointOpacity;
  35666. } else {
  35667. this.temp.pointOpacity = num;
  35668. }
  35669. var dontRender = viewer.dealBeforeRender; //在执行beforeRender时更改的话不要发送content_changed 尤其分屏
  35670. if (Potree.settings.notAdditiveBlending) {
  35671. return this.material.opacity = num;
  35672. }
  35673. var opacity;
  35674. if (num == 1) {
  35675. opacity = 1;
  35676. } else {
  35677. var str = (Potree.settings.sizeFitToLevel ? 'sizeFit:' : '') + (canMoreThanOne ? 'canMoreThanOne:' : '') + this.temp.pointOpacity + ':' + this.maxLevel + ':' + this.nodeMaxLevel;
  35678. var value = this.temp.opacity[str]; //储存。防止每次渲染(反复切换density)都要算。
  35679. if (value) {
  35680. opacity = value;
  35681. } else {
  35682. if (Potree.settings.sizeFitToLevel) {
  35683. //按照点云质量来调整的版本:
  35684. var base = this.material.spacing / Math.pow(1.7, this.maxLevel); //随着level提高,点云重叠几率增多
  35685. var minBase = this.material.spacing / Math.pow(1.7, this.nodeMaxLevel);
  35686. var ratio = Math.min(1 / base, 1 / minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  35687. opacity = base * ratio * num;
  35688. if (!canMoreThanOne) {
  35689. opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  35690. }
  35691. } else {
  35692. var _base2 = this.material.spacing / Math.pow(2, this.maxLevel);
  35693. var _minBase = this.material.spacing / Math.pow(2, this.nodeMaxLevel);
  35694. //console.log(1 / base, 1 / minBase / 6)
  35695. var _ratio = Math.min(1 / _base2, 1 / _minBase / 3); //ratio为一个能使opacity不大于1 的 乘量,minBase要除以一个数,该数调越大减弱效果越强。level越低opacity和面板越接,level越高效果越弱,以减免过度重叠后的亮度。
  35696. opacity = _base2 * _ratio * num;
  35697. if (!canMoreThanOne) {
  35698. opacity = MathUtils.clamp(opacity, 0, 0.999); //到1就不透明了(可能出现一段一样)
  35699. }
  35700. }
  35701. this.temp.opacity[str] = opacity;
  35702. }
  35703. //缺点:防止颜色过亮主要是相机离远时,当在漫游点处由于离点云太近,可能会导致高质量点云看起来很暗。
  35704. }
  35705. //console.log('changePointOpacity ' + this.dataset_id + ', num : ' + num + ' , opacity : ' + this.material.opacity) //检查是否做到了低质量时num==opacity,中质量opacity稍小于num,高质量更小
  35706. if (Potree.settings.sortCloudMat) {
  35707. this.opacity = opacity;
  35708. this.material.opacity = opacity;
  35709. } else {
  35710. this.material.opacity = opacity;
  35711. }
  35712. dontRender || viewer.dispatchEvent('content_changed');
  35713. }
  35714. updateBound() {
  35715. var boundingBox_ = this.pcoGeometry.tightBoundingBox.clone().applyMatrix4(this.matrixWorld); //tightBoundingBox是点云原始的bound,但经过(绕z)旋转后bound有所改变,比之前体积更大。
  35716. this.bound = boundingBox_;
  35717. this.bound2 = this.getBoundWithPanos();
  35718. }
  35719. getBoundWithPanos() {
  35720. //确保panoBound在内的bound
  35721. var bound = this.bound.clone();
  35722. this.panos.forEach(pano => {
  35723. var panoBound = new Box3();
  35724. panoBound.expandByPoint(pano.position);
  35725. panoBound.expandByVector(new Vector3(1, 1, 1)); //give pano a margin
  35726. bound.union(panoBound);
  35727. });
  35728. return bound;
  35729. }
  35730. getPanosBound() {
  35731. //仅由所有pano构成的bound
  35732. if (this.panos.length > 0) {
  35733. var minSize = new Vector3(1, 1, 1);
  35734. this.panosBound = math.getBoundByPoints(this.panos.map(e => e.position), minSize);
  35735. } else {
  35736. this.panosBound = null;
  35737. }
  35738. }
  35739. getUnrotBoundPoint(type) {
  35740. //获取没有旋转的tightBounding的水平四个点
  35741. //如果alighment支持任意轴旋转,水平面上看到的可能就是六边形了,失去意义,到时候不能用这个。也可以若只绕z旋转, 使用tightBoundingBox,否则bound
  35742. var bound = this.pcoGeometry.tightBoundingBox;
  35743. if (type == 'all') {
  35744. return [new Vector3(bound.min.x, bound.min.y, bound.min.z), new Vector3(bound.max.x, bound.min.y, bound.min.z), new Vector3(bound.max.x, bound.max.y, bound.min.z), new Vector3(bound.min.x, bound.max.y, bound.min.z), new Vector3(bound.min.x, bound.min.y, bound.max.z), new Vector3(bound.max.x, bound.min.y, bound.max.z), new Vector3(bound.max.x, bound.max.y, bound.max.z), new Vector3(bound.min.x, bound.max.y, bound.max.z)].map(e => e.applyMatrix4(this.matrixWorld));
  35745. } else return [new Vector3(bound.min.x, bound.min.y, 0), new Vector3(bound.max.x, bound.min.y, 0), new Vector3(bound.max.x, bound.max.y, 0), new Vector3(bound.min.x, bound.max.y, 0)].map(e => e.applyMatrix4(this.matrixWorld));
  35746. }
  35747. getVolume() {
  35748. /* var points = this.getUnrotBoundPoint() -----在只绕z轴旋转时这么写也行
  35749. var area = Math.abs(math.getArea(points))
  35750. return area * (this.bound.max.z - this.bound.min.z) */
  35751. var bound = this.pcoGeometry.tightBoundingBox.clone();
  35752. var size = bound.getSize(new Vector3());
  35753. return size.x * size.y * size.z;
  35754. }
  35755. ifContainsPoint(pos) {
  35756. //pos是否坐落于tightBound内
  35757. /* if(!this.bound || !this.bound.containsPoint(pos))return ---这样写也行
  35758. var points = this.getUnrotBoundPoint()
  35759. return math.isPointInArea(points, null, pos) */
  35760. //要把tightBoundingBox想象成一个volumeBox
  35761. var box = this.pcoGeometry.tightBoundingBox;
  35762. var center = box.getCenter(new Vector3());
  35763. var size = box.getSize(new Vector3());
  35764. var boxMatrix = new Matrix4().setPosition(center.x, center.y, center.z);
  35765. boxMatrix.scale(size);
  35766. boxMatrix.premultiply(this.matrixWorld);
  35767. return Potree.Utils.isIntersectBox(pos, boxMatrix);
  35768. }
  35769. intersectBox(boxWorldMatrix) {
  35770. var boxM = boxWorldMatrix.clone().premultiply(this.matrixWorld.clone().invert()); //box乘上点云逆矩阵 (因为点云的忽略掉其matrixWorld, 为了保持相对位置不变,box要左乘matrixWorld的逆)(因第一个参数bound不好变形,第二个参数box可以)
  35771. return Potree.Utils.isIntersectBox(this.pcoGeometry.tightBoundingBox, boxM);
  35772. }
  35773. }
  35774. class ProfileData {
  35775. constructor(profile) {
  35776. this.profile = profile;
  35777. this.segments = [];
  35778. this.boundingBox = new Box3();
  35779. for (var i = 0; i < profile.points.length - 1; i++) {
  35780. var start = profile.points[i];
  35781. var end = profile.points[i + 1];
  35782. var startGround = new Vector3(start.x, start.y, 0);
  35783. var endGround = new Vector3(end.x, end.y, 0);
  35784. var center = new Vector3().addVectors(endGround, startGround).multiplyScalar(0.5);
  35785. var length = startGround.distanceTo(endGround);
  35786. var side = new Vector3().subVectors(endGround, startGround).normalize();
  35787. var up = new Vector3(0, 0, 1);
  35788. var forward = new Vector3().crossVectors(side, up).normalize();
  35789. var N = forward;
  35790. var cutPlane = new Plane().setFromNormalAndCoplanarPoint(N, startGround);
  35791. var halfPlane = new Plane().setFromNormalAndCoplanarPoint(side, center);
  35792. var segment = {
  35793. start: start,
  35794. end: end,
  35795. cutPlane: cutPlane,
  35796. halfPlane: halfPlane,
  35797. length: length,
  35798. points: new Points$1()
  35799. };
  35800. this.segments.push(segment);
  35801. }
  35802. }
  35803. size() {
  35804. var size = 0;
  35805. for (var segment of this.segments) {
  35806. size += segment.points.numPoints;
  35807. }
  35808. return size;
  35809. }
  35810. }
  35811. ;
  35812. class ProfileRequest {
  35813. constructor(pointcloud, profile, maxDepth, callback) {
  35814. this.pointcloud = pointcloud;
  35815. this.profile = profile;
  35816. this.maxDepth = maxDepth || Number.MAX_VALUE;
  35817. this.callback = callback;
  35818. this.temporaryResult = new ProfileData(this.profile);
  35819. this.pointsServed = 0;
  35820. this.highestLevelServed = 0;
  35821. this.priorityQueue = new BinaryHeap(function (x) {
  35822. return 1 / x.weight;
  35823. });
  35824. this.initialize();
  35825. }
  35826. initialize() {
  35827. this.priorityQueue.push({
  35828. node: this.pointcloud.pcoGeometry.root,
  35829. weight: Infinity
  35830. });
  35831. }
  35832. // traverse the node and add intersecting descendants to queue
  35833. traverse(node) {
  35834. var stack = [];
  35835. for (var i = 0; i < 8; i++) {
  35836. var child = node.children[i];
  35837. if (child && this.pointcloud.nodeIntersectsProfile(child, this.profile)) {
  35838. stack.push(child);
  35839. }
  35840. }
  35841. while (stack.length > 0) {
  35842. var _node = stack.pop();
  35843. var weight = _node.boundingSphere.radius;
  35844. this.priorityQueue.push({
  35845. node: _node,
  35846. weight: weight
  35847. });
  35848. // add children that intersect the cutting plane
  35849. if (_node.level < this.maxDepth) {
  35850. for (var _i = 0; _i < 8; _i++) {
  35851. var _child = _node.children[_i];
  35852. if (_child && this.pointcloud.nodeIntersectsProfile(_child, this.profile)) {
  35853. stack.push(_child);
  35854. }
  35855. }
  35856. }
  35857. }
  35858. }
  35859. update() {
  35860. if (!this.updateGeneratorInstance) {
  35861. this.updateGeneratorInstance = this.updateGenerator();
  35862. }
  35863. var result = this.updateGeneratorInstance.next();
  35864. if (result.done) {
  35865. this.updateGeneratorInstance = null;
  35866. }
  35867. }
  35868. *updateGenerator() {
  35869. // load nodes in queue
  35870. // if hierarchy expands, also load nodes from expanded hierarchy
  35871. // once loaded, add data to this.points and remove node from queue
  35872. // only evaluate 1-50 nodes per frame to maintain responsiveness
  35873. var start = performance.now();
  35874. var maxNodesPerUpdate = 1;
  35875. var intersectedNodes = [];
  35876. for (var i = 0; i < Math.min(maxNodesPerUpdate, this.priorityQueue.size()); i++) {
  35877. var element = this.priorityQueue.pop();
  35878. var node = element.node;
  35879. if (node.level > this.maxDepth) {
  35880. continue;
  35881. }
  35882. if (node.loaded) {
  35883. // add points to result
  35884. intersectedNodes.push(node);
  35885. exports.lru.touch(node);
  35886. this.highestLevelServed = Math.max(node.getLevel(), this.highestLevelServed);
  35887. var geom = node.pcoGeometry;
  35888. var hierarchyStepSize = geom ? geom.hierarchyStepSize : 1;
  35889. var doTraverse = node.getLevel() === 0 || node.level % hierarchyStepSize === 0 && node.hasChildren;
  35890. if (doTraverse) {
  35891. this.traverse(node);
  35892. }
  35893. } else {
  35894. node.load();
  35895. this.priorityQueue.push(element);
  35896. }
  35897. }
  35898. if (intersectedNodes.length > 0) {
  35899. for (var done of this.getPointsInsideProfile(intersectedNodes, this.temporaryResult)) {
  35900. if (!done) {
  35901. //console.log("updateGenerator yields");
  35902. yield false;
  35903. }
  35904. }
  35905. if (this.temporaryResult.size() > 100) {
  35906. this.pointsServed += this.temporaryResult.size();
  35907. this.callback.onProgress({
  35908. request: this,
  35909. points: this.temporaryResult
  35910. });
  35911. this.temporaryResult = new ProfileData(this.profile);
  35912. }
  35913. }
  35914. if (this.priorityQueue.size() === 0) {
  35915. // we're done! inform callback and remove from pending requests
  35916. if (this.temporaryResult.size() > 0) {
  35917. this.pointsServed += this.temporaryResult.size();
  35918. this.callback.onProgress({
  35919. request: this,
  35920. points: this.temporaryResult
  35921. });
  35922. this.temporaryResult = new ProfileData(this.profile);
  35923. }
  35924. this.callback.onFinish({
  35925. request: this
  35926. });
  35927. var index = this.pointcloud.profileRequests.indexOf(this);
  35928. if (index >= 0) {
  35929. this.pointcloud.profileRequests.splice(index, 1);
  35930. }
  35931. }
  35932. yield true;
  35933. }
  35934. *getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage) {
  35935. var checkpoint = performance.now();
  35936. var accepted = new Uint32Array(numPoints);
  35937. var mileage = new Float64Array(numPoints);
  35938. var acceptedPositions = new Float32Array(numPoints * 3);
  35939. var numAccepted = 0;
  35940. var pos = new Vector3();
  35941. var svp = new Vector3();
  35942. var view = new Float32Array(node.geometry.attributes.position.array);
  35943. for (var i = 0; i < numPoints; i++) {
  35944. pos.set(view[i * 3 + 0], view[i * 3 + 1], view[i * 3 + 2]);
  35945. pos.applyMatrix4(matrix);
  35946. var distance = Math.abs(segment.cutPlane.distanceToPoint(pos));
  35947. var centerDistance = Math.abs(segment.halfPlane.distanceToPoint(pos));
  35948. if (distance < this.profile.width / 2 && centerDistance < segment.length / 2) {
  35949. svp.subVectors(pos, segment.start);
  35950. var localMileage = segmentDir.dot(svp);
  35951. accepted[numAccepted] = i;
  35952. mileage[numAccepted] = localMileage + totalMileage;
  35953. points.boundingBox.expandByPoint(pos);
  35954. pos.sub(this.pointcloud.position);
  35955. acceptedPositions[3 * numAccepted + 0] = pos.x;
  35956. acceptedPositions[3 * numAccepted + 1] = pos.y;
  35957. acceptedPositions[3 * numAccepted + 2] = pos.z;
  35958. numAccepted++;
  35959. }
  35960. if (i % 1000 === 0) {
  35961. var duration = performance.now() - checkpoint;
  35962. if (duration > 4) {
  35963. //console.log(`getAccepted yield after ${duration}ms`);
  35964. yield false;
  35965. checkpoint = performance.now();
  35966. }
  35967. }
  35968. }
  35969. accepted = accepted.subarray(0, numAccepted);
  35970. mileage = mileage.subarray(0, numAccepted);
  35971. acceptedPositions = acceptedPositions.subarray(0, numAccepted * 3);
  35972. //let end = performance.now();
  35973. //let duration = end - start;
  35974. //console.log("accepted duration ", duration)
  35975. //console.log(`getAccepted finished`);
  35976. yield [accepted, mileage, acceptedPositions];
  35977. }
  35978. *getPointsInsideProfile(nodes, target) {
  35979. var checkpoint = performance.now();
  35980. var totalMileage = 0;
  35981. var pointsProcessed = 0;
  35982. for (var segment of target.segments) {
  35983. for (var node of nodes) {
  35984. var numPoints = node.numPoints;
  35985. var geometry = node.geometry;
  35986. if (!numPoints) {
  35987. continue;
  35988. }
  35989. {
  35990. // skip if current node doesn't intersect current segment
  35991. var bbWorld = node.boundingBox.clone().applyMatrix4(this.pointcloud.matrixWorld);
  35992. var bsWorld = bbWorld.getBoundingSphere(new Sphere());
  35993. var start = new Vector3(segment.start.x, segment.start.y, bsWorld.center.z);
  35994. var end = new Vector3(segment.end.x, segment.end.y, bsWorld.center.z);
  35995. var closest = new Line3(start, end).closestPointToPoint(bsWorld.center, true, new Vector3());
  35996. var distance = closest.distanceTo(bsWorld.center);
  35997. var intersects = distance < bsWorld.radius + target.profile.width;
  35998. if (!intersects) {
  35999. continue;
  36000. }
  36001. }
  36002. //{// DEBUG
  36003. // console.log(node.name);
  36004. // let boxHelper = new Potree.Box3Helper(node.getBoundingBox());
  36005. // boxHelper.matrixAutoUpdate = false;
  36006. // boxHelper.matrix.copy(viewer.scene.pointclouds[0].matrixWorld);
  36007. // viewer.scene.scene.add(boxHelper);
  36008. //}
  36009. var sv = new Vector3().subVectors(segment.end, segment.start).setZ(0);
  36010. var segmentDir = sv.clone().normalize();
  36011. var points = new Points$1();
  36012. var nodeMatrix = new Matrix4().makeTranslation(...node.boundingBox.min.toArray());
  36013. var matrix = new Matrix4().multiplyMatrices(this.pointcloud.matrixWorld, nodeMatrix);
  36014. pointsProcessed = pointsProcessed + numPoints;
  36015. var accepted = null;
  36016. var mileage = null;
  36017. var acceptedPositions = null;
  36018. for (var result of this.getAccepted(numPoints, node, matrix, segment, segmentDir, points, totalMileage)) {
  36019. if (!result) {
  36020. var _duration = performance.now() - checkpoint;
  36021. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  36022. yield false;
  36023. checkpoint = performance.now();
  36024. } else {
  36025. [accepted, mileage, acceptedPositions] = result;
  36026. }
  36027. }
  36028. var duration = performance.now() - checkpoint;
  36029. if (duration > 4) {
  36030. //console.log(`getPointsInsideProfile yield after ${duration}ms`);
  36031. yield false;
  36032. checkpoint = performance.now();
  36033. }
  36034. points.data.position = acceptedPositions;
  36035. var relevantAttributes = Object.keys(geometry.attributes).filter(a => !["position", "indices"].includes(a));
  36036. for (var attributeName of relevantAttributes) {
  36037. var attribute = geometry.attributes[attributeName];
  36038. var numElements = attribute.array.length / numPoints;
  36039. if (numElements !== parseInt(numElements)) {
  36040. debugger;
  36041. }
  36042. var Type = attribute.array.constructor;
  36043. var filteredBuffer = new Type(numElements * accepted.length);
  36044. var source = attribute.array;
  36045. var _target = filteredBuffer;
  36046. for (var i = 0; i < accepted.length; i++) {
  36047. var index = accepted[i];
  36048. var _start = index * numElements;
  36049. var _end = _start + numElements;
  36050. var sub = source.subarray(_start, _end);
  36051. _target.set(sub, i * numElements);
  36052. }
  36053. points.data[attributeName] = filteredBuffer;
  36054. }
  36055. points.data['mileage'] = mileage;
  36056. points.numPoints = accepted.length;
  36057. segment.points.add(points);
  36058. }
  36059. totalMileage += segment.length;
  36060. }
  36061. for (var _segment of target.segments) {
  36062. target.boundingBox.union(_segment.points.boundingBox);
  36063. }
  36064. //console.log(`getPointsInsideProfile finished`);
  36065. yield true;
  36066. }
  36067. finishLevelThenCancel() {
  36068. if (this.cancelRequested) {
  36069. return;
  36070. }
  36071. this.maxDepth = this.highestLevelServed;
  36072. this.cancelRequested = true;
  36073. //console.log(`maxDepth: ${this.maxDepth}`);
  36074. }
  36075. cancel() {
  36076. this.callback.onCancel();
  36077. this.priorityQueue = new BinaryHeap(function (x) {
  36078. return 1 / x.weight;
  36079. });
  36080. var index = this.pointcloud.profileRequests.indexOf(this);
  36081. if (index >= 0) {
  36082. this.pointcloud.profileRequests.splice(index, 1);
  36083. }
  36084. }
  36085. }
  36086. class WorkerPool {
  36087. constructor() {
  36088. this.workers = {};
  36089. }
  36090. getWorker(url) {
  36091. if (!this.workers[url]) {
  36092. this.workers[url] = [];
  36093. }
  36094. if (this.workers[url].length === 0) {
  36095. var _worker = new Worker(url);
  36096. this.workers[url].push(_worker);
  36097. }
  36098. var worker = this.workers[url].pop();
  36099. return worker;
  36100. }
  36101. returnWorker(url, worker) {
  36102. this.workers[url].push(worker);
  36103. }
  36104. }
  36105. ;
  36106. function createPointcloudData(pointcloud) {
  36107. var material = pointcloud.material;
  36108. var ranges = [];
  36109. for (var [name, value] of material.ranges) {
  36110. ranges.push({
  36111. name: name,
  36112. value: value
  36113. });
  36114. }
  36115. if (typeof material.elevationRange[0] === "number") {
  36116. ranges.push({
  36117. name: "elevationRange",
  36118. value: material.elevationRange
  36119. });
  36120. }
  36121. if (typeof material.intensityRange[0] === "number") {
  36122. ranges.push({
  36123. name: "intensityRange",
  36124. value: material.intensityRange
  36125. });
  36126. }
  36127. var pointSizeTypeName = Object.entries(Potree.PointSizeType).find(e => e[1] === material.pointSizeType)[0];
  36128. var jsonMaterial = {
  36129. activeAttributeName: material.activeAttributeName,
  36130. ranges: ranges,
  36131. size: material.size,
  36132. minSize: material.minSize,
  36133. pointSizeType: pointSizeTypeName,
  36134. matcap: material.matcap
  36135. };
  36136. var pcdata = {
  36137. name: pointcloud.name,
  36138. url: pointcloud.pcoGeometry.url,
  36139. position: pointcloud.position.toArray(),
  36140. rotation: pointcloud.rotation.toArray(),
  36141. scale: pointcloud.scale.toArray(),
  36142. material: jsonMaterial
  36143. };
  36144. return pcdata;
  36145. }
  36146. function createProfileData(profile) {
  36147. var data = {
  36148. uuid: profile.uuid,
  36149. name: profile.name,
  36150. points: profile.points.map(p => p.toArray()),
  36151. height: profile.height,
  36152. width: profile.width
  36153. };
  36154. return data;
  36155. }
  36156. function createVolumeData(volume) {
  36157. var data = {
  36158. uuid: volume.uuid,
  36159. type: volume.constructor.name,
  36160. name: volume.name,
  36161. position: volume.position.toArray(),
  36162. rotation: volume.rotation.toArray(),
  36163. scale: volume.scale.toArray(),
  36164. visible: volume.visible,
  36165. clip: volume.clip
  36166. };
  36167. return data;
  36168. }
  36169. function createCameraAnimationData(animation) {
  36170. var controlPoints = animation.controlPoints.map(cp => {
  36171. var cpdata = {
  36172. position: cp.position.toArray(),
  36173. target: cp.target.toArray()
  36174. };
  36175. return cpdata;
  36176. });
  36177. var data = {
  36178. uuid: animation.uuid,
  36179. name: animation.name,
  36180. duration: animation.duration,
  36181. t: animation.t,
  36182. curveType: animation.curveType,
  36183. visible: animation.visible,
  36184. controlPoints: controlPoints
  36185. };
  36186. return data;
  36187. }
  36188. function createMeasurementData(measurement) {
  36189. var data = {
  36190. uuid: measurement.uuid,
  36191. name: measurement.name,
  36192. points: measurement.points.map(p => p.position.toArray()),
  36193. showDistances: measurement.showDistances,
  36194. showCoordinates: measurement.showCoordinates,
  36195. showArea: measurement.showArea,
  36196. closed: measurement.closed,
  36197. showAngles: measurement.showAngles,
  36198. showHeight: measurement.showHeight,
  36199. showCircle: measurement.showCircle,
  36200. showAzimuth: measurement.showAzimuth,
  36201. showEdges: measurement.showEdges,
  36202. color: measurement.color.toArray()
  36203. };
  36204. return data;
  36205. }
  36206. function createOrientedImagesData(images) {
  36207. var data = {
  36208. cameraParamsPath: images.cameraParamsPath,
  36209. imageParamsPath: images.imageParamsPath
  36210. };
  36211. return data;
  36212. }
  36213. function createGeopackageData(geopackage) {
  36214. var data = {
  36215. path: geopackage.path
  36216. };
  36217. return data;
  36218. }
  36219. function createAnnotationData(annotation) {
  36220. var data = {
  36221. uuid: annotation.uuid,
  36222. title: annotation.title.toString(),
  36223. description: annotation.description,
  36224. position: annotation.position.toArray(),
  36225. offset: annotation.offset.toArray(),
  36226. children: []
  36227. };
  36228. if (annotation.cameraPosition) {
  36229. data.cameraPosition = annotation.cameraPosition.toArray();
  36230. }
  36231. if (annotation.cameraTarget) {
  36232. data.cameraTarget = annotation.cameraTarget.toArray();
  36233. }
  36234. if (typeof annotation.radius !== "undefined") {
  36235. data.radius = annotation.radius;
  36236. }
  36237. return data;
  36238. }
  36239. function createAnnotationsData(viewer) {
  36240. var map = new Map();
  36241. viewer.scene.annotations.traverseDescendants(a => {
  36242. var aData = createAnnotationData(a);
  36243. map.set(a, aData);
  36244. });
  36245. for (var [annotation, data] of map) {
  36246. for (var child of annotation.children) {
  36247. var childData = map.get(child);
  36248. data.children.push(childData);
  36249. }
  36250. }
  36251. var annotations = viewer.scene.annotations.children.map(a => map.get(a));
  36252. return annotations;
  36253. }
  36254. function createSettingsData(viewer) {
  36255. return {
  36256. pointBudget: viewer.getPointBudget(),
  36257. fov: viewer.getFOV(),
  36258. edlEnabled: viewer.getEDLEnabled(),
  36259. edlRadius: viewer.getEDLRadius(),
  36260. edlStrength: viewer.getEDLStrength(),
  36261. background: viewer.getBackground(),
  36262. minNodeSize: viewer.getMinNodeSize(),
  36263. showBoundingBoxes: viewer.getShowBoundingBox()
  36264. };
  36265. }
  36266. function createSceneContentData(viewer) {
  36267. var data = [];
  36268. var potreeObjects = [];
  36269. viewer.scene.scene.traverse(node => {
  36270. if (node.potree) {
  36271. potreeObjects.push(node);
  36272. }
  36273. });
  36274. for (var object of potreeObjects) {
  36275. if (object.potree.file) {
  36276. var saveObject = {
  36277. file: object.potree.file
  36278. };
  36279. data.push(saveObject);
  36280. }
  36281. }
  36282. return data;
  36283. }
  36284. function createViewData(viewer) {
  36285. var view = viewer.scene.view;
  36286. var data = {
  36287. position: view.position.toArray(),
  36288. target: view.getPivot().toArray()
  36289. };
  36290. return data;
  36291. }
  36292. function createClassificationData(viewer) {
  36293. var classifications = viewer.classifications;
  36294. var data = classifications;
  36295. return data;
  36296. }
  36297. function saveProject(viewer) {
  36298. var scene = viewer.scene;
  36299. var data = {
  36300. type: "Potree",
  36301. version: 1.7,
  36302. settings: createSettingsData(viewer),
  36303. view: createViewData(viewer),
  36304. classification: createClassificationData(viewer),
  36305. pointclouds: scene.pointclouds.map(createPointcloudData),
  36306. measurements: scene.measurements.map(createMeasurementData),
  36307. volumes: scene.volumes.map(createVolumeData),
  36308. cameraAnimations: scene.cameraAnimations.map(createCameraAnimationData),
  36309. profiles: scene.profiles.map(createProfileData),
  36310. annotations: createAnnotationsData(viewer),
  36311. orientedImages: scene.orientedImages.map(createOrientedImagesData),
  36312. geopackages: scene.geopackages.map(createGeopackageData)
  36313. // objects: createSceneContentData(viewer),
  36314. };
  36315. return data;
  36316. }
  36317. class ControlPoint {
  36318. constructor() {
  36319. this.position = new Vector3(0, 0, 0);
  36320. this.target = new Vector3(0, 0, 0);
  36321. this.positionHandle = null;
  36322. this.targetHandle = null;
  36323. }
  36324. }
  36325. ;
  36326. class CameraAnimation extends EventDispatcher$1 {
  36327. constructor(viewer) {
  36328. super();
  36329. this.viewer = viewer;
  36330. this.selectedElement = null;
  36331. this.controlPoints = [];
  36332. this.uuid = MathUtils.generateUUID();
  36333. this.node = new Object3D();
  36334. this.node.name = "camera animation";
  36335. this.viewer.scene.scene.add(this.node);
  36336. this.frustum = this.createFrustum();
  36337. this.node.add(this.frustum);
  36338. this.name = "Camera Animation";
  36339. this.duration = 5;
  36340. this.t = 0;
  36341. // "centripetal", "chordal", "catmullrom"
  36342. this.curveType = "centripetal";
  36343. this.visible = true;
  36344. this.createUpdateHook();
  36345. this.createPath();
  36346. }
  36347. static defaultFromView(viewer) {
  36348. var animation = new CameraAnimation(viewer);
  36349. var camera = viewer.scene.getActiveCamera();
  36350. var target = viewer.scene.view.getPivot();
  36351. var cpCenter = new Vector3(0.3 * camera.position.x + 0.7 * target.x, 0.3 * camera.position.y + 0.7 * target.y, 0.3 * camera.position.z + 0.7 * target.z);
  36352. var targetCenter = new Vector3(0.05 * camera.position.x + 0.95 * target.x, 0.05 * camera.position.y + 0.95 * target.y, 0.05 * camera.position.z + 0.95 * target.z);
  36353. var r = camera.position.distanceTo(target) * 0.3;
  36354. //const dir = target.clone().sub(camera.position).normalize();
  36355. var angle = Utils.computeAzimuth(camera.position, target);
  36356. var n = 5;
  36357. for (var i = 0; i < n; i++) {
  36358. var u = 1.5 * Math.PI * (i / n) + angle;
  36359. var dx = r * Math.cos(u);
  36360. var dy = r * Math.sin(u);
  36361. var cpPos = [cpCenter.x + dx, cpCenter.y + dy, cpCenter.z];
  36362. var targetPos = [targetCenter.x + dx * 0.1, targetCenter.y + dy * 0.1, targetCenter.z];
  36363. var cp = animation.createControlPoint();
  36364. cp.position.set(...cpPos);
  36365. cp.target.set(...targetPos);
  36366. }
  36367. return animation;
  36368. }
  36369. createUpdateHook() {
  36370. var viewer = this.viewer;
  36371. viewer.addEventListener("update", () => {
  36372. var camera = viewer.scene.getActiveCamera();
  36373. var {
  36374. width,
  36375. height
  36376. } = viewer.renderer.getSize(new Vector2());
  36377. this.node.visible = this.visible;
  36378. for (var cp of this.controlPoints) {
  36379. {
  36380. // position
  36381. var projected = cp.position.clone().project(camera);
  36382. var visible = this.visible && projected.z < 1 && projected.z > -1;
  36383. if (visible) {
  36384. var x = width * (projected.x * 0.5 + 0.5);
  36385. var y = height - height * (projected.y * 0.5 + 0.5);
  36386. cp.positionHandle.svg.style.left = x - cp.positionHandle.svg.clientWidth / 2;
  36387. cp.positionHandle.svg.style.top = y - cp.positionHandle.svg.clientHeight / 2;
  36388. cp.positionHandle.svg.style.display = "";
  36389. } else {
  36390. cp.positionHandle.svg.style.display = "none";
  36391. }
  36392. }
  36393. {
  36394. // target
  36395. var _projected = cp.target.clone().project(camera);
  36396. var _visible = this.visible && _projected.z < 1 && _projected.z > -1;
  36397. if (_visible) {
  36398. var _x = width * (_projected.x * 0.5 + 0.5);
  36399. var _y = height - height * (_projected.y * 0.5 + 0.5);
  36400. cp.targetHandle.svg.style.left = _x - cp.targetHandle.svg.clientWidth / 2;
  36401. cp.targetHandle.svg.style.top = _y - cp.targetHandle.svg.clientHeight / 2;
  36402. cp.targetHandle.svg.style.display = "";
  36403. } else {
  36404. cp.targetHandle.svg.style.display = "none";
  36405. }
  36406. }
  36407. }
  36408. this.line.material.resolution.set(width, height);
  36409. this.updatePath();
  36410. {
  36411. // frustum
  36412. var frame = this.at(this.t);
  36413. var frustum = this.frustum;
  36414. frustum.position.copy(frame.position);
  36415. frustum.lookAt(...frame.target.toArray());
  36416. frustum.scale.set(20, 20, 20);
  36417. frustum.material.resolution.set(width, height);
  36418. }
  36419. });
  36420. }
  36421. createControlPoint(index) {
  36422. if (index === undefined) {
  36423. index = this.controlPoints.length;
  36424. }
  36425. var cp = new ControlPoint();
  36426. if (this.controlPoints.length >= 2 && index === 0) {
  36427. var cp1 = this.controlPoints[0];
  36428. var cp2 = this.controlPoints[1];
  36429. var dir = cp1.position.clone().sub(cp2.position).multiplyScalar(0.5);
  36430. cp.position.copy(cp1.position).add(dir);
  36431. var tDir = cp1.target.clone().sub(cp2.target).multiplyScalar(0.5);
  36432. cp.target.copy(cp1.target).add(tDir);
  36433. } else if (this.controlPoints.length >= 2 && index === this.controlPoints.length) {
  36434. var _cp2 = this.controlPoints[this.controlPoints.length - 2];
  36435. var _cp3 = this.controlPoints[this.controlPoints.length - 1];
  36436. var _dir = _cp3.position.clone().sub(_cp2.position).multiplyScalar(0.5);
  36437. cp.position.copy(_cp2.position).add(_dir);
  36438. var _tDir = _cp3.target.clone().sub(_cp2.target).multiplyScalar(0.5);
  36439. cp.target.copy(_cp3.target).add(_tDir);
  36440. } else if (this.controlPoints.length >= 2) {
  36441. var _cp4 = this.controlPoints[index - 1];
  36442. var _cp5 = this.controlPoints[index];
  36443. cp.position.copy(_cp4.position.clone().add(_cp5.position).multiplyScalar(0.5));
  36444. cp.target.copy(_cp4.target.clone().add(_cp5.target).multiplyScalar(0.5));
  36445. }
  36446. // cp.position.copy(viewer.scene.view.position);
  36447. // cp.target.copy(viewer.scene.view.getPivot());
  36448. cp.positionHandle = this.createHandle(cp.position);
  36449. cp.targetHandle = this.createHandle(cp.target);
  36450. this.controlPoints.splice(index, 0, cp);
  36451. this.dispatchEvent({
  36452. type: "controlpoint_added",
  36453. controlpoint: cp
  36454. });
  36455. return cp;
  36456. }
  36457. removeControlPoint(cp) {
  36458. this.controlPoints = this.controlPoints.filter(_cp => _cp !== cp);
  36459. this.dispatchEvent({
  36460. type: "controlpoint_removed",
  36461. controlpoint: cp
  36462. });
  36463. cp.positionHandle.svg.remove();
  36464. cp.targetHandle.svg.remove();
  36465. // TODO destroy cp
  36466. }
  36467. createPath() {
  36468. {
  36469. // position
  36470. var geometry = new LineGeometry();
  36471. var material = new LineMaterial({
  36472. color: 0x00ff00,
  36473. dashSize: 5,
  36474. gapSize: 2,
  36475. linewidth: 2,
  36476. resolution: new Vector2(1000, 1000)
  36477. });
  36478. var line = new Line2(geometry, material);
  36479. this.line = line;
  36480. this.node.add(line);
  36481. }
  36482. {
  36483. // target
  36484. var _geometry = new LineGeometry();
  36485. var _material = new LineMaterial({
  36486. color: 0x0000ff,
  36487. dashSize: 5,
  36488. gapSize: 2,
  36489. linewidth: 2,
  36490. resolution: new Vector2(1000, 1000)
  36491. });
  36492. var _line = new Line2(_geometry, _material);
  36493. this.targetLine = _line;
  36494. this.node.add(_line);
  36495. }
  36496. }
  36497. createFrustum() {
  36498. var f = 0.3;
  36499. var positions = [0, 0, 0, -f, -f, +1, 0, 0, 0, f, -f, +1, 0, 0, 0, f, f, +1, 0, 0, 0, -f, f, +1, -f, -f, +1, f, -f, +1, f, -f, +1, f, f, +1, f, f, +1, -f, f, +1, -f, f, +1, -f, -f, +1];
  36500. var geometry = new LineGeometry();
  36501. geometry.setPositions(positions);
  36502. geometry.verticesNeedUpdate = true;
  36503. geometry.computeBoundingSphere();
  36504. var material = new LineMaterial({
  36505. color: 0xff0000,
  36506. linewidth: 2,
  36507. resolution: new Vector2(1000, 1000)
  36508. });
  36509. var line = new Line2(geometry, material);
  36510. line.computeLineDistances();
  36511. return line;
  36512. }
  36513. updatePath() {
  36514. {
  36515. // positions
  36516. var positions = this.controlPoints.map(cp => cp.position);
  36517. var first = positions[0];
  36518. var curve = new CatmullRomCurve3(positions);
  36519. curve.curveType = this.curveType;
  36520. var n = 100;
  36521. var curvePositions = [];
  36522. for (var k = 0; k <= n; k++) {
  36523. var t = k / n;
  36524. var position = curve.getPoint(t).sub(first);
  36525. curvePositions.push(position.x, position.y, position.z);
  36526. }
  36527. this.line.geometry.setPositions(curvePositions);
  36528. this.line.geometry.verticesNeedUpdate = true;
  36529. this.line.geometry.computeBoundingSphere();
  36530. this.line.position.copy(first);
  36531. this.line.computeLineDistances();
  36532. this.cameraCurve = curve;
  36533. }
  36534. {
  36535. // targets
  36536. var _positions = this.controlPoints.map(cp => cp.target);
  36537. var _first = _positions[0];
  36538. var _curve = new CatmullRomCurve3(_positions);
  36539. _curve.curveType = this.curveType;
  36540. var _n = 100;
  36541. var _curvePositions = [];
  36542. for (var _k = 0; _k <= _n; _k++) {
  36543. var _t = _k / _n;
  36544. var _position = _curve.getPoint(_t).sub(_first);
  36545. _curvePositions.push(_position.x, _position.y, _position.z);
  36546. }
  36547. this.targetLine.geometry.setPositions(_curvePositions);
  36548. this.targetLine.geometry.verticesNeedUpdate = true;
  36549. this.targetLine.geometry.computeBoundingSphere();
  36550. this.targetLine.position.copy(_first);
  36551. this.targetLine.computeLineDistances();
  36552. this.targetCurve = _curve;
  36553. }
  36554. }
  36555. at(t) {
  36556. if (t > 1) {
  36557. t = 1;
  36558. } else if (t < 0) {
  36559. t = 0;
  36560. }
  36561. var camPos = this.cameraCurve.getPointAt(t);
  36562. var target = this.targetCurve.getPointAt(t);
  36563. var frame = {
  36564. position: camPos,
  36565. target: target
  36566. };
  36567. return frame;
  36568. }
  36569. set(t) {
  36570. this.t = t;
  36571. }
  36572. createHandle(vector) {
  36573. var svgns = "http://www.w3.org/2000/svg";
  36574. var svg = document.createElementNS(svgns, "svg");
  36575. svg.setAttribute("width", "2em");
  36576. svg.setAttribute("height", "2em");
  36577. svg.setAttribute("position", "absolute");
  36578. svg.style.left = "50px";
  36579. svg.style.top = "50px";
  36580. svg.style.position = "absolute";
  36581. svg.style.zIndex = "10000";
  36582. var circle = document.createElementNS(svgns, 'circle');
  36583. circle.setAttributeNS(null, 'cx', "1em");
  36584. circle.setAttributeNS(null, 'cy', "1em");
  36585. circle.setAttributeNS(null, 'r', "0.5em");
  36586. circle.setAttributeNS(null, 'style', 'fill: red; stroke: black; stroke-width: 0.2em;');
  36587. svg.appendChild(circle);
  36588. var element = this.viewer.renderer.domElement.parentElement;
  36589. element.appendChild(svg);
  36590. var startDrag = evt => {
  36591. this.selectedElement = svg;
  36592. document.addEventListener("mousemove", drag);
  36593. };
  36594. var endDrag = evt => {
  36595. this.selectedElement = null;
  36596. document.removeEventListener("mousemove", drag);
  36597. };
  36598. var drag = evt => {
  36599. if (this.selectedElement) {
  36600. evt.preventDefault();
  36601. var rect = viewer.renderer.domElement.getBoundingClientRect();
  36602. var x = evt.clientX - rect.x;
  36603. var y = evt.clientY - rect.y;
  36604. var {
  36605. width,
  36606. height
  36607. } = this.viewer.renderer.getSize(new Vector2());
  36608. var camera = this.viewer.scene.getActiveCamera();
  36609. //const cp = this.controlPoints.find(cp => cp.handle.svg === svg);
  36610. var projected = vector.clone().project(camera);
  36611. projected.x = (x / width - 0.5) / 0.5;
  36612. projected.y = (-(y - height) / height - 0.5) / 0.5;
  36613. var unprojected = projected.clone().unproject(camera);
  36614. vector.set(unprojected.x, unprojected.y, unprojected.z);
  36615. }
  36616. };
  36617. svg.addEventListener('mousedown', startDrag);
  36618. svg.addEventListener('mouseup', endDrag);
  36619. var handle = {
  36620. svg: svg
  36621. };
  36622. return handle;
  36623. }
  36624. setVisible(visible) {
  36625. this.node.visible = visible;
  36626. var display = visible ? "" : "none";
  36627. for (var cp of this.controlPoints) {
  36628. cp.positionHandle.svg.style.display = display;
  36629. cp.targetHandle.svg.style.display = display;
  36630. }
  36631. this.visible = visible;
  36632. }
  36633. setDuration(duration) {
  36634. this.duration = duration;
  36635. }
  36636. getDuration(duration) {
  36637. return this.duration;
  36638. }
  36639. play() {
  36640. var tStart = performance.now();
  36641. var duration = this.duration;
  36642. var originalyVisible = this.visible;
  36643. this.setVisible(false);
  36644. var onUpdate = delta => {
  36645. var tNow = performance.now();
  36646. var elapsed = (tNow - tStart) / 1000;
  36647. var t = elapsed / duration;
  36648. this.set(t);
  36649. var frame = this.at(t);
  36650. viewer.scene.view.position.copy(frame.position);
  36651. viewer.scene.view.lookAt(frame.target);
  36652. if (t > 1) {
  36653. this.setVisible(originalyVisible);
  36654. this.viewer.removeEventListener("update", onUpdate);
  36655. }
  36656. };
  36657. this.viewer.addEventListener("update", onUpdate);
  36658. }
  36659. }
  36660. function loadPointCloud(viewer, data) {
  36661. var loadMaterial = target => {
  36662. if (data.material) {
  36663. if (data.material.activeAttributeName != null) {
  36664. target.activeAttributeName = data.material.activeAttributeName;
  36665. }
  36666. if (data.material.ranges != null) {
  36667. for (var range of data.material.ranges) {
  36668. if (range.name === "elevationRange") {
  36669. target.elevationRange = range.value;
  36670. } else if (range.name === "intensityRange") {
  36671. target.intensityRange = range.value;
  36672. } else {
  36673. target.setRange(range.name, range.value);
  36674. }
  36675. }
  36676. }
  36677. if (data.material.size != null) {
  36678. target.size = data.material.size;
  36679. }
  36680. if (data.material.minSize != null) {
  36681. target.minSize = data.material.minSize;
  36682. }
  36683. if (data.material.pointSizeType != null) {
  36684. target.pointSizeType = PointSizeType[data.material.pointSizeType];
  36685. }
  36686. if (data.material.matcap != null) {
  36687. target.matcap = data.material.matcap;
  36688. }
  36689. } else if (data.activeAttributeName != null) {
  36690. target.activeAttributeName = data.activeAttributeName;
  36691. } else {
  36692. // no material data
  36693. }
  36694. };
  36695. var promise = new Promise(resolve => {
  36696. var names = viewer.scene.pointclouds.map(p => p.name);
  36697. var alreadyExists = names.includes(data.name);
  36698. if (alreadyExists) {
  36699. resolve();
  36700. return;
  36701. }
  36702. Potree.loadPointCloud(data.url, data.name, e => {
  36703. var {
  36704. pointcloud
  36705. } = e;
  36706. pointcloud.position.set(...data.position);
  36707. pointcloud.rotation.set(...data.rotation);
  36708. pointcloud.scale.set(...data.scale);
  36709. loadMaterial(pointcloud.material);
  36710. viewer.scene.addPointCloud(pointcloud);
  36711. resolve(pointcloud);
  36712. });
  36713. });
  36714. return promise;
  36715. }
  36716. function loadMeasurement(viewer, data) {
  36717. var duplicate = viewer.scene.measurements.find(measure => measure.uuid === data.uuid);
  36718. if (duplicate) {
  36719. return;
  36720. }
  36721. var measure = new Measure();
  36722. measure.uuid = data.uuid;
  36723. measure.name = data.name;
  36724. measure.showDistances = data.showDistances;
  36725. measure.showCoordinates = data.showCoordinates;
  36726. measure.showArea = data.showArea;
  36727. measure.closed = data.closed;
  36728. measure.showAngles = data.showAngles;
  36729. measure.showHeight = data.showHeight;
  36730. measure.showCircle = data.showCircle;
  36731. measure.showAzimuth = data.showAzimuth;
  36732. measure.showEdges = data.showEdges;
  36733. // color
  36734. for (var point of data.points) {
  36735. var pos = new Vector3(...point);
  36736. measure.addMarker(pos);
  36737. }
  36738. viewer.scene.addMeasurement(measure);
  36739. }
  36740. function loadVolume(viewer, data) {
  36741. var duplicate = viewer.scene.volumes.find(volume => volume.uuid === data.uuid);
  36742. if (duplicate) {
  36743. return;
  36744. }
  36745. var volume = new Potree[data.type]();
  36746. volume.uuid = data.uuid;
  36747. volume.name = data.name;
  36748. volume.position.set(...data.position);
  36749. volume.rotation.set(...data.rotation);
  36750. volume.scale.set(...data.scale);
  36751. volume.visible = data.visible;
  36752. volume.clip = data.clip;
  36753. viewer.scene.addVolume(volume);
  36754. }
  36755. function loadCameraAnimation(viewer, data) {
  36756. var duplicate = viewer.scene.cameraAnimations.find(a => a.uuid === data.uuid);
  36757. if (duplicate) {
  36758. return;
  36759. }
  36760. var animation = new CameraAnimation(viewer);
  36761. animation.uuid = data.uuid;
  36762. animation.name = data.name;
  36763. animation.duration = data.duration;
  36764. animation.t = data.t;
  36765. animation.curveType = data.curveType;
  36766. animation.visible = data.visible;
  36767. animation.controlPoints = [];
  36768. for (var cpdata of data.controlPoints) {
  36769. var cp = animation.createControlPoint();
  36770. cp.position.set(...cpdata.position);
  36771. cp.target.set(...cpdata.target);
  36772. }
  36773. viewer.scene.addCameraAnimation(animation);
  36774. }
  36775. function loadOrientedImages(viewer, images) {
  36776. var {
  36777. cameraParamsPath,
  36778. imageParamsPath
  36779. } = images;
  36780. var duplicate = viewer.scene.orientedImages.find(i => i.imageParamsPath === imageParamsPath);
  36781. if (duplicate) {
  36782. return;
  36783. }
  36784. Potree.OrientedImageLoader.load(cameraParamsPath, imageParamsPath, viewer).then(images => {
  36785. viewer.scene.addOrientedImages(images);
  36786. });
  36787. }
  36788. function loadGeopackage(viewer, geopackage) {
  36789. var path = geopackage.path;
  36790. var duplicate = viewer.scene.geopackages.find(i => i.path === path);
  36791. if (duplicate) {
  36792. return;
  36793. }
  36794. var projection = viewer.getProjection();
  36795. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  36796. proj4.defs("pointcloud", projection);
  36797. var transform = proj4("WGS84", "pointcloud");
  36798. var params = {
  36799. transform: transform
  36800. };
  36801. Potree.GeoPackageLoader.loadUrl(path, params).then(data => {
  36802. viewer.scene.addGeopackage(data);
  36803. });
  36804. }
  36805. function loadSettings(viewer, data) {
  36806. if (!data) {
  36807. return;
  36808. }
  36809. viewer.setPointBudget(data.pointBudget);
  36810. viewer.setFOV(data.fov);
  36811. viewer.setEDLEnabled(data.edlEnabled);
  36812. viewer.setEDLRadius(data.edlRadius);
  36813. viewer.setEDLStrength(data.edlStrength);
  36814. viewer.setBackground(data.background);
  36815. viewer.setMinNodeSize(data.minNodeSize);
  36816. viewer.setShowBoundingBox(data.showBoundingBoxes);
  36817. }
  36818. function loadView(viewer, view) {
  36819. viewer.scene.view.position.set(...view.position);
  36820. viewer.scene.view.lookAt(...view.target);
  36821. }
  36822. function loadAnnotationItem(item) {
  36823. var annotation = new Annotation({
  36824. position: item.position,
  36825. title: item.title,
  36826. cameraPosition: item.cameraPosition,
  36827. cameraTarget: item.cameraTarget
  36828. });
  36829. annotation.description = item.description;
  36830. annotation.uuid = item.uuid;
  36831. if (item.offset) {
  36832. annotation.offset.set(...item.offset);
  36833. }
  36834. return annotation;
  36835. }
  36836. function loadAnnotations(viewer, data) {
  36837. if (!data) {
  36838. return;
  36839. }
  36840. var findDuplicate = item => {
  36841. var duplicate = null;
  36842. viewer.scene.annotations.traverse(a => {
  36843. if (a.uuid === item.uuid) {
  36844. duplicate = a;
  36845. }
  36846. });
  36847. return duplicate;
  36848. };
  36849. var traverse = (item, parent) => {
  36850. var duplicate = findDuplicate(item);
  36851. if (duplicate) {
  36852. return;
  36853. }
  36854. var annotation = loadAnnotationItem(item);
  36855. for (var childItem of item.children) {
  36856. traverse(childItem, annotation);
  36857. }
  36858. parent.add(annotation);
  36859. };
  36860. for (var item of data) {
  36861. traverse(item, viewer.scene.annotations);
  36862. }
  36863. }
  36864. function loadProfile(viewer, data) {
  36865. var {
  36866. name,
  36867. points
  36868. } = data;
  36869. var duplicate = viewer.scene.profiles.find(profile => profile.uuid === data.uuid);
  36870. if (duplicate) {
  36871. return;
  36872. }
  36873. var profile = new Potree.Profile();
  36874. profile.name = name;
  36875. profile.uuid = data.uuid;
  36876. profile.setWidth(data.width);
  36877. for (var point of points) {
  36878. profile.addMarker(new Vector3(...point));
  36879. }
  36880. viewer.scene.addProfile(profile);
  36881. }
  36882. function loadClassification(viewer, data) {
  36883. if (!data) {
  36884. return;
  36885. }
  36886. var classifications = data;
  36887. viewer.setClassifications(classifications);
  36888. }
  36889. function loadProject(_x, _x2) {
  36890. return _loadProject.apply(this, arguments);
  36891. }
  36892. function _loadProject() {
  36893. _loadProject = _asyncToGenerator(function* (viewer, data) {
  36894. if (data.type !== "Potree") {
  36895. console.error("not a valid Potree project");
  36896. return;
  36897. }
  36898. loadSettings(viewer, data.settings);
  36899. loadView(viewer, data.view);
  36900. var pointcloudPromises = [];
  36901. for (var pointcloud of data.pointclouds) {
  36902. var promise = loadPointCloud(viewer, pointcloud);
  36903. pointcloudPromises.push(promise);
  36904. }
  36905. for (var measure of data.measurements) {
  36906. loadMeasurement(viewer, measure);
  36907. }
  36908. for (var volume of data.volumes) {
  36909. loadVolume(viewer, volume);
  36910. }
  36911. for (var animation of data.cameraAnimations) {
  36912. loadCameraAnimation(viewer, animation);
  36913. }
  36914. for (var profile of data.profiles) {
  36915. loadProfile(viewer, profile);
  36916. }
  36917. if (data.orientedImages) {
  36918. for (var images of data.orientedImages) {
  36919. loadOrientedImages(viewer, images);
  36920. }
  36921. }
  36922. loadAnnotations(viewer, data.annotations);
  36923. loadClassification(viewer, data.classification);
  36924. // need to load at least one point cloud that defines the scene projection,
  36925. // before we can load stuff in other projections such as geopackages
  36926. //await Promise.any(pointcloudPromises); // (not yet supported)
  36927. Utils.waitAny(pointcloudPromises).then(() => {
  36928. if (data.geopackages) {
  36929. for (var geopackage of data.geopackages) {
  36930. loadGeopackage(viewer, geopackage);
  36931. }
  36932. }
  36933. });
  36934. yield Promise.all(pointcloudPromises);
  36935. });
  36936. return _loadProject.apply(this, arguments);
  36937. }
  36938. //
  36939. // Algorithm by Christian Boucheny
  36940. // shader code taken and adapted from CloudCompare
  36941. //
  36942. // see
  36943. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  36944. // http://www.kitware.com/source/home/post/9
  36945. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  36946. class EyeDomeLightingMaterial extends RawShaderMaterial {
  36947. //base
  36948. constructor() {
  36949. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  36950. super();
  36951. var uniforms = {
  36952. screenWidth: {
  36953. type: 'f',
  36954. value: 0
  36955. },
  36956. screenHeight: {
  36957. type: 'f',
  36958. value: 0
  36959. },
  36960. edlStrength: {
  36961. type: 'f',
  36962. value: 1.0
  36963. },
  36964. uNear: {
  36965. type: 'f',
  36966. value: 1.0
  36967. },
  36968. uFar: {
  36969. type: 'f',
  36970. value: 1.0
  36971. },
  36972. radius: {
  36973. type: 'f',
  36974. value: 1.0
  36975. },
  36976. neighbours: {
  36977. type: '2fv',
  36978. value: []
  36979. },
  36980. depthMap: {
  36981. type: 't',
  36982. value: null
  36983. },
  36984. uEDLColor: {
  36985. type: 't',
  36986. value: null
  36987. },
  36988. uEDLDepth: {
  36989. type: 't',
  36990. value: null
  36991. },
  36992. opacity: {
  36993. type: 'f',
  36994. value: 1.0
  36995. },
  36996. uProj: {
  36997. type: "Matrix4fv",
  36998. value: []
  36999. }
  37000. };
  37001. this.setValues({
  37002. uniforms: uniforms,
  37003. vertexShader: this.getDefines() + Shaders['edl.vs'],
  37004. fragmentShader: this.getDefines() + Shaders['edl.fs'],
  37005. lights: false
  37006. });
  37007. this.neighbourCount = 8;
  37008. }
  37009. getDefines() {
  37010. var defines = '';
  37011. defines += '#define NEIGHBOUR_COUNT ' + this.neighbourCount + '\n';
  37012. return defines;
  37013. }
  37014. updateShaderSource() {
  37015. var vs = this.getDefines() + Shaders['edl.vs'];
  37016. var fs = this.getDefines() + Shaders['edl.fs'];
  37017. this.setValues({
  37018. vertexShader: vs,
  37019. fragmentShader: fs
  37020. });
  37021. this.uniforms.neighbours.value = this.neighbours;
  37022. this.needsUpdate = true;
  37023. }
  37024. get neighbourCount() {
  37025. return this._neighbourCount;
  37026. }
  37027. set neighbourCount(value) {
  37028. if (this._neighbourCount !== value) {
  37029. //周围八个格子
  37030. this._neighbourCount = value;
  37031. this.neighbours = new Float32Array(this._neighbourCount * 2);
  37032. for (var c = 0; c < this._neighbourCount; c++) {
  37033. this.neighbours[2 * c + 0] = Math.cos(2 * c * Math.PI / this._neighbourCount);
  37034. this.neighbours[2 * c + 1] = Math.sin(2 * c * Math.PI / this._neighbourCount);
  37035. }
  37036. this.updateShaderSource();
  37037. }
  37038. }
  37039. }
  37040. /**
  37041. * laslaz code taken and adapted from plas.io js-laslaz
  37042. * http://plas.io/
  37043. * https://github.com/verma/plasio
  37044. *
  37045. * Thanks to Uday Verma and Howard Butler
  37046. *
  37047. */
  37048. class LasLazLoader {
  37049. constructor(version, extension) {
  37050. if (typeof version === 'string') {
  37051. this.version = new Version(version);
  37052. } else {
  37053. this.version = version;
  37054. }
  37055. this.extension = extension;
  37056. }
  37057. static progressCB() {}
  37058. load(node, callback) {
  37059. if (node.loaded) {
  37060. return;
  37061. }
  37062. var url = node.getURL();
  37063. if (this.version.equalOrHigher('1.4')) {
  37064. url += ".".concat(this.extension);
  37065. }
  37066. var xhr = XHRFactory.createXMLHttpRequest();
  37067. xhr.open('GET', url, true);
  37068. xhr.responseType = 'arraybuffer';
  37069. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  37070. xhr.onreadystatechange = () => {
  37071. if (xhr.readyState === 4) {
  37072. if (xhr.status === 200 || xhr.status === 0) {
  37073. var buffer = xhr.response;
  37074. this.parse(node, buffer, callback);
  37075. } else {
  37076. console.log('Failed to load file! HTTP status: ' + xhr.status + ', file: ' + url);
  37077. }
  37078. }
  37079. };
  37080. xhr.send(null);
  37081. }
  37082. parse(node, buffer, callback) {
  37083. return _asyncToGenerator(function* () {
  37084. //add callback
  37085. var lf = new LASFile(buffer);
  37086. var handler = new LasLazBatcher(node);
  37087. try {
  37088. yield lf.open();
  37089. lf.isOpen = true;
  37090. } catch (e) {
  37091. console.log("failed to open file. :(");
  37092. return;
  37093. }
  37094. var header = yield lf.getHeader();
  37095. var skip = 1;
  37096. var totalRead = 0;
  37097. var totalToRead = skip <= 1 ? header.pointsCount : header.pointsCount / skip;
  37098. var hasMoreData = true;
  37099. while (hasMoreData) {
  37100. var data = yield lf.readData(1000 * 1000, 0, skip);
  37101. handler.push(new LASDecoder(data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, header.mins, header.maxs));
  37102. totalRead += data.count;
  37103. LasLazLoader.progressCB(totalRead / totalToRead);
  37104. hasMoreData = data.hasMoreData;
  37105. }
  37106. header.totalRead = totalRead;
  37107. header.versionAsString = lf.versionAsString;
  37108. header.isCompressed = lf.isCompressed;
  37109. LasLazLoader.progressCB(1);
  37110. try {
  37111. yield lf.close();
  37112. lf.isOpen = false;
  37113. } catch (e) {
  37114. console.error("failed to close las/laz file!!!");
  37115. throw e;
  37116. }
  37117. callback(); //add
  37118. })();
  37119. }
  37120. handle(node, url) {}
  37121. }
  37122. ;
  37123. class LasLazBatcher {
  37124. constructor(node) {
  37125. this.node = node;
  37126. }
  37127. push(lasBuffer) {
  37128. var workerPath = Potree.scriptPath + '/workers/LASDecoderWorker.js';
  37129. var worker = Potree.workerPool.getWorker(workerPath);
  37130. var node = this.node;
  37131. var pointAttributes = node.pcoGeometry.pointAttributes;
  37132. worker.onmessage = e => {
  37133. var geometry = new BufferGeometry();
  37134. var numPoints = lasBuffer.pointsCount;
  37135. var positions = new Float32Array(e.data.position);
  37136. var colors = new Uint8Array(e.data.color);
  37137. var intensities = new Float32Array(e.data.intensity);
  37138. var classifications = new Uint8Array(e.data.classification);
  37139. var returnNumbers = new Uint8Array(e.data.returnNumber);
  37140. var numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  37141. var pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  37142. var indices = new Uint8Array(e.data.indices);
  37143. geometry.setAttribute('position', new BufferAttribute(positions, 3));
  37144. geometry.setAttribute('color', new BufferAttribute(colors, 4, true));
  37145. geometry.setAttribute('intensity', new BufferAttribute(intensities, 1));
  37146. geometry.setAttribute('classification', new BufferAttribute(classifications, 1));
  37147. geometry.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  37148. geometry.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  37149. geometry.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  37150. geometry.setAttribute('indices', new BufferAttribute(indices, 4));
  37151. geometry.attributes.indices.normalized = true;
  37152. var _loop = function _loop(key) {
  37153. var range = e.data.ranges[key];
  37154. var attribute = pointAttributes.attributes.find(a => a.name === key);
  37155. attribute.range[0] = Math.min(attribute.range[0], range[0]);
  37156. attribute.range[1] = Math.max(attribute.range[1], range[1]);
  37157. };
  37158. for (var key in e.data.ranges) {
  37159. _loop(key);
  37160. }
  37161. var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max));
  37162. geometry.boundingBox = this.node.boundingBox;
  37163. this.node.tightBoundingBox = tightBoundingBox;
  37164. this.node.geometry = geometry;
  37165. this.node.numPoints = numPoints;
  37166. this.node.loaded = true;
  37167. this.node.loading = false;
  37168. Potree.numNodesLoading--;
  37169. this.node.mean = new Vector3(...e.data.mean);
  37170. Potree.workerPool.returnWorker(workerPath, worker);
  37171. };
  37172. var message = {
  37173. buffer: lasBuffer.arrayb,
  37174. numPoints: lasBuffer.pointsCount,
  37175. pointSize: lasBuffer.pointSize,
  37176. pointFormatID: 2,
  37177. scale: lasBuffer.scale,
  37178. offset: lasBuffer.offset,
  37179. mins: lasBuffer.mins,
  37180. maxs: lasBuffer.maxs
  37181. };
  37182. worker.postMessage(message, [message.buffer]);
  37183. }
  37184. }
  37185. function parseAttributes(cloudjs) {
  37186. var version = new Version(cloudjs.version);
  37187. var replacements = {
  37188. "COLOR_PACKED": "rgba",
  37189. "RGBA": "rgba",
  37190. "INTENSITY": "intensity",
  37191. "CLASSIFICATION": "classification",
  37192. "GPS_TIME": "gps-time"
  37193. };
  37194. var replaceOldNames = old => {
  37195. if (replacements[old]) {
  37196. return replacements[old];
  37197. } else {
  37198. return old;
  37199. }
  37200. };
  37201. var pointAttributes = [];
  37202. if (version.upTo('1.7')) {
  37203. for (var attributeName of cloudjs.pointAttributes) {
  37204. var oldAttribute = PointAttribute[attributeName];
  37205. var attribute = {
  37206. name: oldAttribute.name,
  37207. size: oldAttribute.byteSize,
  37208. elements: oldAttribute.numElements,
  37209. elementSize: oldAttribute.byteSize / oldAttribute.numElements,
  37210. type: oldAttribute.type.name,
  37211. description: ""
  37212. };
  37213. pointAttributes.push(attribute);
  37214. }
  37215. } else {
  37216. pointAttributes.push(...cloudjs.pointAttributes);
  37217. }
  37218. {
  37219. var attributes = new PointAttributes();
  37220. var typeConversion = {
  37221. int8: PointAttributeTypes.DATA_TYPE_INT8,
  37222. int16: PointAttributeTypes.DATA_TYPE_INT16,
  37223. int32: PointAttributeTypes.DATA_TYPE_INT32,
  37224. int64: PointAttributeTypes.DATA_TYPE_INT64,
  37225. uint8: PointAttributeTypes.DATA_TYPE_UINT8,
  37226. uint16: PointAttributeTypes.DATA_TYPE_UINT16,
  37227. uint32: PointAttributeTypes.DATA_TYPE_UINT32,
  37228. uint64: PointAttributeTypes.DATA_TYPE_UINT64,
  37229. double: PointAttributeTypes.DATA_TYPE_DOUBLE,
  37230. float: PointAttributeTypes.DATA_TYPE_FLOAT
  37231. };
  37232. for (var jsAttribute of pointAttributes) {
  37233. if (jsAttribute.name == void 0) {
  37234. //add 有的是这个,也有的不是(点云编辑页的)
  37235. var attribute_ = PointAttribute[jsAttribute];
  37236. attributes.add(attribute_);
  37237. continue;
  37238. }
  37239. var name = replaceOldNames(jsAttribute.name);
  37240. var type = typeConversion[jsAttribute.type];
  37241. var numElements = jsAttribute.elements;
  37242. var description = jsAttribute.description;
  37243. var _attribute = new PointAttribute(name, type, numElements);
  37244. attributes.add(_attribute);
  37245. }
  37246. {
  37247. // check if it has normals
  37248. var hasNormals = pointAttributes.find(a => a.name === "NormalX") !== undefined && pointAttributes.find(a => a.name === "NormalY") !== undefined && pointAttributes.find(a => a.name === "NormalZ") !== undefined;
  37249. if (hasNormals) {
  37250. var vector = {
  37251. name: "NORMAL",
  37252. attributes: ["NormalX", "NormalY", "NormalZ"]
  37253. };
  37254. attributes.addVector(vector);
  37255. }
  37256. }
  37257. return attributes;
  37258. }
  37259. }
  37260. function lasLazAttributes(fMno) {
  37261. var attributes = new PointAttributes();
  37262. attributes.add(PointAttribute.POSITION_CARTESIAN);
  37263. attributes.add(new PointAttribute("rgba", PointAttributeTypes.DATA_TYPE_UINT8, 4));
  37264. attributes.add(new PointAttribute("intensity", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  37265. attributes.add(new PointAttribute("classification", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  37266. attributes.add(new PointAttribute("gps-time", PointAttributeTypes.DATA_TYPE_DOUBLE, 1));
  37267. attributes.add(new PointAttribute("number of returns", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  37268. attributes.add(new PointAttribute("return number", PointAttributeTypes.DATA_TYPE_UINT8, 1));
  37269. attributes.add(new PointAttribute("source id", PointAttributeTypes.DATA_TYPE_UINT16, 1));
  37270. //attributes.add(new PointAttribute("pointSourceID", PointAttributeTypes.DATA_TYPE_INT8, 4));
  37271. return attributes;
  37272. }
  37273. class POCLoader {
  37274. static load(url, timeStamp, callback) {
  37275. //add timeStamp
  37276. try {
  37277. var pco = new PointCloudOctreeGeometry();
  37278. pco.timeStamp = timeStamp;
  37279. pco.url = url;
  37280. var xhr = XHRFactory.createXMLHttpRequest();
  37281. xhr.open('GET', url + '?m=' + timeStamp, true);
  37282. xhr.onreadystatechange = function () {
  37283. if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
  37284. var fMno = JSON.parse(xhr.responseText);
  37285. var version = new Version(fMno.version);
  37286. // assume octreeDir is absolute if it starts with http
  37287. if (fMno.octreeDir.indexOf('http') === 0) {
  37288. pco.octreeDir = fMno.octreeDir;
  37289. } else {
  37290. pco.octreeDir = url + '/../' + fMno.octreeDir;
  37291. }
  37292. pco.spacing = fMno.spacing;
  37293. pco.hierarchyStepSize = fMno.hierarchyStepSize;
  37294. pco.pointAttributes = fMno.pointAttributes;
  37295. var min = new Vector3(fMno.boundingBox.lx, fMno.boundingBox.ly, fMno.boundingBox.lz);
  37296. var max = new Vector3(fMno.boundingBox.ux, fMno.boundingBox.uy, fMno.boundingBox.uz);
  37297. var boundingBox = new Box3(min, max);
  37298. var tightBoundingBox = boundingBox.clone();
  37299. if (fMno.tightBoundingBox) {
  37300. //这个才是真实的bounding,前面那个bounding的size是个正方体,似乎取了最长边作为边长
  37301. tightBoundingBox.min.copy(new Vector3(fMno.tightBoundingBox.lx, fMno.tightBoundingBox.ly, fMno.tightBoundingBox.lz));
  37302. tightBoundingBox.max.copy(new Vector3(fMno.tightBoundingBox.ux, fMno.tightBoundingBox.uy, fMno.tightBoundingBox.uz));
  37303. }
  37304. var offset = min.clone(); //将成为点云的position,被我用作旋转中心(但在点云中不那么居中,navvis也是这样, 这样可能是为了让模型在这数据的bounding上)
  37305. boundingBox.min.sub(offset); //点云的真实坐标的min都是0,0,0吗(我看案例是,因绕角落旋转,也就是原点)
  37306. boundingBox.max.sub(offset);
  37307. tightBoundingBox.min.sub(offset);
  37308. tightBoundingBox.max.sub(offset);
  37309. //改
  37310. //pco.projection = fMno.projection || "+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs ",
  37311. //"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs" //给地图
  37312. pco.boundingBox = boundingBox;
  37313. pco.tightBoundingBox = tightBoundingBox;
  37314. pco.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  37315. pco.tightBoundingSphere = tightBoundingBox.getBoundingSphere(new Sphere());
  37316. pco.offset = offset;
  37317. if (fMno.pointAttributes === 'LAS') {
  37318. pco.loader = new LasLazLoader(fMno.version, "las");
  37319. pco.pointAttributes = lasLazAttributes(fMno);
  37320. } else if (fMno.pointAttributes === 'LAZ') {
  37321. pco.loader = new LasLazLoader(fMno.version, "laz");
  37322. pco.pointAttributes = lasLazAttributes(fMno);
  37323. } else {
  37324. pco.loader = new BinaryLoader(fMno.version, boundingBox, fMno.scale);
  37325. pco.pointAttributes = parseAttributes(fMno);
  37326. }
  37327. var nodes = {};
  37328. {
  37329. // load root
  37330. var name = 'r';
  37331. var root = new PointCloudOctreeGeometryNode(name, pco, boundingBox);
  37332. root.level = 0;
  37333. root.hasChildren = true;
  37334. root.spacing = pco.spacing;
  37335. if (version.upTo('1.5')) {
  37336. root.numPoints = fMno.hierarchy[0][1];
  37337. } else {
  37338. root.numPoints = 0;
  37339. }
  37340. pco.root = root;
  37341. pco.root.load();
  37342. nodes[name] = root;
  37343. }
  37344. // load remaining hierarchy
  37345. if (version.upTo('1.4')) {
  37346. for (var i = 1; i < fMno.hierarchy.length; i++) {
  37347. var _name = fMno.hierarchy[i][0];
  37348. var numPoints = fMno.hierarchy[i][1];
  37349. var index = parseInt(_name.charAt(_name.length - 1));
  37350. var parentName = _name.substring(0, _name.length - 1);
  37351. var parentNode = nodes[parentName];
  37352. var level = _name.length - 1;
  37353. //let boundingBox = POCLoader.createChildAABB(parentNode.boundingBox, index);
  37354. var _boundingBox = Utils.createChildAABB(parentNode.boundingBox, index);
  37355. var node = new PointCloudOctreeGeometryNode(_name, pco, _boundingBox);
  37356. node.level = level;
  37357. node.numPoints = numPoints;
  37358. node.spacing = pco.spacing / Math.pow(2, level);
  37359. parentNode.addChild(node);
  37360. nodes[_name] = node;
  37361. }
  37362. }
  37363. pco.nodes = nodes;
  37364. callback(pco);
  37365. }
  37366. };
  37367. xhr.send(null);
  37368. } catch (e) {
  37369. console.log("loading failed: '" + url + "'");
  37370. console.log(e);
  37371. callback();
  37372. }
  37373. }
  37374. loadPointAttributes(mno) {
  37375. var fpa = mno.pointAttributes;
  37376. var pa = new PointAttributes();
  37377. for (var i = 0; i < fpa.length; i++) {
  37378. var pointAttribute = PointAttribute[fpa[i]];
  37379. pa.add(pointAttribute);
  37380. }
  37381. return pa;
  37382. }
  37383. createChildAABB(aabb, index) {
  37384. var min = aabb.min.clone();
  37385. var max = aabb.max.clone();
  37386. var size = new Vector3().subVectors(max, min);
  37387. if ((index & 0b0001) > 0) {
  37388. min.z += size.z / 2;
  37389. } else {
  37390. max.z -= size.z / 2;
  37391. }
  37392. if ((index & 0b0010) > 0) {
  37393. min.y += size.y / 2;
  37394. } else {
  37395. max.y -= size.y / 2;
  37396. }
  37397. if ((index & 0b0100) > 0) {
  37398. min.x += size.x / 2;
  37399. } else {
  37400. max.x -= size.x / 2;
  37401. }
  37402. return new Box3(min, max);
  37403. }
  37404. }
  37405. class OctreeGeometry {
  37406. constructor() {
  37407. this.url = null;
  37408. this.spacing = 0;
  37409. this.boundingBox = null;
  37410. this.root = null;
  37411. this.pointAttributes = null;
  37412. this.loader = null;
  37413. }
  37414. }
  37415. ;
  37416. class OctreeGeometryNode {
  37417. constructor(name, octreeGeometry, boundingBox) {
  37418. this.id = OctreeGeometryNode.IDCount++;
  37419. this.name = name;
  37420. this.index = parseInt(name.charAt(name.length - 1));
  37421. this.octreeGeometry = octreeGeometry;
  37422. this.boundingBox = boundingBox;
  37423. this.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  37424. this.children = {};
  37425. this.numPoints = 0;
  37426. this.level = null;
  37427. this.oneTimeDisposeHandlers = [];
  37428. }
  37429. isGeometryNode() {
  37430. return true;
  37431. }
  37432. getLevel() {
  37433. return this.level;
  37434. }
  37435. isTreeNode() {
  37436. return false;
  37437. }
  37438. isLoaded() {
  37439. return this.loaded;
  37440. }
  37441. getBoundingSphere() {
  37442. return this.boundingSphere;
  37443. }
  37444. getBoundingBox() {
  37445. return this.boundingBox;
  37446. }
  37447. getChildren() {
  37448. var children = [];
  37449. for (var i = 0; i < 8; i++) {
  37450. if (this.children[i]) {
  37451. children.push(this.children[i]);
  37452. }
  37453. }
  37454. return children;
  37455. }
  37456. getBoundingBox() {
  37457. return this.boundingBox;
  37458. }
  37459. load() {
  37460. if (Potree.numNodesLoading >= Potree.maxNodesLoading) {
  37461. return;
  37462. }
  37463. this.octreeGeometry.loader.load(this);
  37464. }
  37465. getNumPoints() {
  37466. return this.numPoints;
  37467. }
  37468. dispose() {
  37469. if (this.geometry && this.parent != null) {
  37470. this.geometry.dispose();
  37471. this.geometry = null;
  37472. this.loaded = false;
  37473. // this.dispatchEvent( { type: 'dispose' } );
  37474. for (var i = 0; i < this.oneTimeDisposeHandlers.length; i++) {
  37475. var handler = this.oneTimeDisposeHandlers[i];
  37476. handler();
  37477. }
  37478. this.oneTimeDisposeHandlers = [];
  37479. }
  37480. }
  37481. }
  37482. ;
  37483. OctreeGeometryNode.IDCount = 0;
  37484. // let loadedNodes = new Set();
  37485. class NodeLoader {
  37486. constructor(url) {
  37487. this.url = url;
  37488. }
  37489. load(node) {
  37490. var _this = this;
  37491. return _asyncToGenerator(function* () {
  37492. if (node.loaded || node.loading) {
  37493. return;
  37494. }
  37495. node.loading = true;
  37496. Potree.numNodesLoading++;
  37497. // console.log(node.name, node.numPoints);
  37498. // if(loadedNodes.has(node.name)){
  37499. // // debugger;
  37500. // }
  37501. // loadedNodes.add(node.name);
  37502. try {
  37503. if (node.nodeType === 2) {
  37504. yield _this.loadHierarchy(node);
  37505. }
  37506. var {
  37507. byteOffset,
  37508. byteSize
  37509. } = node;
  37510. var urlOctree = "".concat(_this.url, "/../octree.bin");
  37511. var first = byteOffset;
  37512. var last = byteOffset + byteSize - 1n;
  37513. var buffer;
  37514. if (byteSize === 0n) {
  37515. buffer = new ArrayBuffer(0);
  37516. console.warn("loaded node with 0 bytes: ".concat(node.name));
  37517. } else {
  37518. var response = yield fetch(urlOctree, {
  37519. headers: {
  37520. 'content-type': 'multipart/byteranges',
  37521. 'Range': "bytes=".concat(first, "-").concat(last)
  37522. }
  37523. });
  37524. buffer = yield response.arrayBuffer();
  37525. }
  37526. var workerPath;
  37527. if (_this.metadata.encoding === "BROTLI") {
  37528. workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker_brotli.js';
  37529. } else {
  37530. workerPath = Potree.scriptPath + '/workers/2.0/DecoderWorker.js';
  37531. }
  37532. var worker = Potree.workerPool.getWorker(workerPath);
  37533. worker.onmessage = function (e) {
  37534. var data = e.data;
  37535. var buffers = data.attributeBuffers;
  37536. Potree.workerPool.returnWorker(workerPath, worker);
  37537. var geometry = new BufferGeometry();
  37538. for (var property in buffers) {
  37539. var _buffer = buffers[property].buffer;
  37540. if (property === "position") {
  37541. geometry.setAttribute('position', new BufferAttribute(new Float32Array(_buffer), 3));
  37542. } else if (property === "rgba") {
  37543. geometry.setAttribute('rgba', new BufferAttribute(new Uint8Array(_buffer), 4, true));
  37544. } else if (property === "NORMAL") {
  37545. //geometry.setAttribute('rgba', new THREE.BufferAttribute(new Uint8Array(buffer), 4, true));
  37546. geometry.setAttribute('normal', new BufferAttribute(new Float32Array(_buffer), 3));
  37547. } else if (property === "INDICES") {
  37548. var bufferAttribute = new BufferAttribute(new Uint8Array(_buffer), 4);
  37549. bufferAttribute.normalized = true;
  37550. geometry.setAttribute('indices', bufferAttribute);
  37551. } else {
  37552. var _bufferAttribute = new BufferAttribute(new Float32Array(_buffer), 1);
  37553. var batchAttribute = buffers[property].attribute;
  37554. _bufferAttribute.potree = {
  37555. offset: buffers[property].offset,
  37556. scale: buffers[property].scale,
  37557. preciseBuffer: buffers[property].preciseBuffer,
  37558. range: batchAttribute.range
  37559. };
  37560. geometry.setAttribute(property, _bufferAttribute);
  37561. }
  37562. }
  37563. // indices ??
  37564. node.density = data.density;
  37565. node.geometry = geometry;
  37566. node.loaded = true;
  37567. node.loading = false;
  37568. Potree.numNodesLoading--;
  37569. };
  37570. var pointAttributes = node.octreeGeometry.pointAttributes;
  37571. var scale = node.octreeGeometry.scale;
  37572. var box = node.boundingBox;
  37573. var min = node.octreeGeometry.offset.clone().add(box.min);
  37574. var size = box.max.clone().sub(box.min);
  37575. var max = min.clone().add(size);
  37576. var numPoints = node.numPoints;
  37577. var offset = node.octreeGeometry.loader.offset;
  37578. var message = {
  37579. name: node.name,
  37580. buffer: buffer,
  37581. pointAttributes: pointAttributes,
  37582. scale: scale,
  37583. min: min,
  37584. max: max,
  37585. size: size,
  37586. offset: offset,
  37587. numPoints: numPoints
  37588. };
  37589. worker.postMessage(message, [message.buffer]);
  37590. } catch (e) {
  37591. node.loaded = false;
  37592. node.loading = false;
  37593. Potree.numNodesLoading--;
  37594. console.log("failed to load ".concat(node.name));
  37595. console.log(e);
  37596. console.log("trying again!");
  37597. }
  37598. })();
  37599. }
  37600. parseHierarchy(node, buffer) {
  37601. var view = new DataView(buffer);
  37602. var tStart = performance.now();
  37603. var bytesPerNode = 22;
  37604. var numNodes = buffer.byteLength / bytesPerNode;
  37605. var octree = node.octreeGeometry;
  37606. // let nodes = [node];
  37607. var nodes = new Array(numNodes);
  37608. nodes[0] = node;
  37609. var nodePos = 1;
  37610. for (var i = 0; i < numNodes; i++) {
  37611. var current = nodes[i];
  37612. var type = view.getUint8(i * bytesPerNode + 0);
  37613. var childMask = view.getUint8(i * bytesPerNode + 1);
  37614. var numPoints = view.getUint32(i * bytesPerNode + 2, true);
  37615. var byteOffset = view.getBigInt64(i * bytesPerNode + 6, true);
  37616. var byteSize = view.getBigInt64(i * bytesPerNode + 14, true);
  37617. // if(byteSize === 0n){
  37618. // // debugger;
  37619. // }
  37620. if (current.nodeType === 2) {
  37621. // replace proxy with real node
  37622. current.byteOffset = byteOffset;
  37623. current.byteSize = byteSize;
  37624. current.numPoints = numPoints;
  37625. } else if (type === 2) {
  37626. // load proxy
  37627. current.hierarchyByteOffset = byteOffset;
  37628. current.hierarchyByteSize = byteSize;
  37629. current.numPoints = numPoints;
  37630. } else {
  37631. // load real node
  37632. current.byteOffset = byteOffset;
  37633. current.byteSize = byteSize;
  37634. current.numPoints = numPoints;
  37635. }
  37636. if (current.byteSize === 0n) {
  37637. // workaround for issue #1125
  37638. // some inner nodes erroneously report >0 points even though have 0 points
  37639. // however, they still report a byteSize of 0, so based on that we now set node.numPoints to 0
  37640. current.numPoints = 0;
  37641. }
  37642. current.nodeType = type;
  37643. if (current.nodeType === 2) {
  37644. continue;
  37645. }
  37646. for (var childIndex = 0; childIndex < 8; childIndex++) {
  37647. var childExists = (1 << childIndex & childMask) !== 0;
  37648. if (!childExists) {
  37649. continue;
  37650. }
  37651. var childName = current.name + childIndex;
  37652. var childAABB = createChildAABB(current.boundingBox, childIndex);
  37653. var child = new OctreeGeometryNode(childName, octree, childAABB);
  37654. child.name = childName;
  37655. child.spacing = current.spacing / 2;
  37656. child.level = current.level + 1;
  37657. current.children[childIndex] = child;
  37658. child.parent = current;
  37659. // nodes.push(child);
  37660. nodes[nodePos] = child;
  37661. nodePos++;
  37662. }
  37663. // if((i % 500) === 0){
  37664. // yield;
  37665. // }
  37666. }
  37667. var duration = performance.now() - tStart;
  37668. // if(duration > 20){
  37669. // let msg = `duration: ${duration}ms, numNodes: ${numNodes}`;
  37670. // console.log(msg);
  37671. // }
  37672. }
  37673. loadHierarchy(node) {
  37674. var _this2 = this;
  37675. return _asyncToGenerator(function* () {
  37676. var {
  37677. hierarchyByteOffset,
  37678. hierarchyByteSize
  37679. } = node;
  37680. var hierarchyPath = "".concat(_this2.url, "/../hierarchy.bin");
  37681. var first = hierarchyByteOffset;
  37682. var last = first + hierarchyByteSize - 1n;
  37683. var response = yield fetch(hierarchyPath, {
  37684. headers: {
  37685. 'content-type': 'multipart/byteranges',
  37686. 'Range': "bytes=".concat(first, "-").concat(last)
  37687. }
  37688. });
  37689. var buffer = yield response.arrayBuffer();
  37690. _this2.parseHierarchy(node, buffer);
  37691. // let promise = new Promise((resolve) => {
  37692. // let generator = this.parseHierarchy(node, buffer);
  37693. // let repeatUntilDone = () => {
  37694. // let result = generator.next();
  37695. // if(result.done){
  37696. // resolve();
  37697. // }else{
  37698. // requestAnimationFrame(repeatUntilDone);
  37699. // }
  37700. // };
  37701. // repeatUntilDone();
  37702. // });
  37703. // await promise;
  37704. })();
  37705. }
  37706. }
  37707. var tmpVec3 = new Vector3();
  37708. function createChildAABB(aabb, index) {
  37709. var min = aabb.min.clone();
  37710. var max = aabb.max.clone();
  37711. var size = tmpVec3.subVectors(max, min);
  37712. if ((index & 0b0001) > 0) {
  37713. min.z += size.z / 2;
  37714. } else {
  37715. max.z -= size.z / 2;
  37716. }
  37717. if ((index & 0b0010) > 0) {
  37718. min.y += size.y / 2;
  37719. } else {
  37720. max.y -= size.y / 2;
  37721. }
  37722. if ((index & 0b0100) > 0) {
  37723. min.x += size.x / 2;
  37724. } else {
  37725. max.x -= size.x / 2;
  37726. }
  37727. return new Box3(min, max);
  37728. }
  37729. var typenameTypeattributeMap = {
  37730. "double": PointAttributeTypes.DATA_TYPE_DOUBLE,
  37731. "float": PointAttributeTypes.DATA_TYPE_FLOAT,
  37732. "int8": PointAttributeTypes.DATA_TYPE_INT8,
  37733. "uint8": PointAttributeTypes.DATA_TYPE_UINT8,
  37734. "int16": PointAttributeTypes.DATA_TYPE_INT16,
  37735. "uint16": PointAttributeTypes.DATA_TYPE_UINT16,
  37736. "int32": PointAttributeTypes.DATA_TYPE_INT32,
  37737. "uint32": PointAttributeTypes.DATA_TYPE_UINT32,
  37738. "int64": PointAttributeTypes.DATA_TYPE_INT64,
  37739. "uint64": PointAttributeTypes.DATA_TYPE_UINT64
  37740. };
  37741. class OctreeLoader {
  37742. static parseAttributes(jsonAttributes) {
  37743. var attributes = new PointAttributes();
  37744. var replacements = {
  37745. "rgb": "rgba"
  37746. };
  37747. for (var jsonAttribute of jsonAttributes) {
  37748. var {
  37749. name,
  37750. description,
  37751. size,
  37752. numElements,
  37753. elementSize,
  37754. min,
  37755. max
  37756. } = jsonAttribute;
  37757. var type = typenameTypeattributeMap[jsonAttribute.type];
  37758. var potreeAttributeName = replacements[name] ? replacements[name] : name;
  37759. var attribute = new PointAttribute(potreeAttributeName, type, numElements);
  37760. if (numElements === 1) {
  37761. attribute.range = [min[0], max[0]];
  37762. } else {
  37763. attribute.range = [min, max];
  37764. }
  37765. if (name === "gps-time") {
  37766. // HACK: Guard against bad gpsTime range in metadata, see potree/potree#909
  37767. if (attribute.range[0] === attribute.range[1]) {
  37768. attribute.range[1] += 1;
  37769. }
  37770. }
  37771. attribute.initialRange = attribute.range;
  37772. attributes.add(attribute);
  37773. }
  37774. {
  37775. // check if it has normals
  37776. var hasNormals = attributes.attributes.find(a => a.name === "NormalX") !== undefined && attributes.attributes.find(a => a.name === "NormalY") !== undefined && attributes.attributes.find(a => a.name === "NormalZ") !== undefined;
  37777. if (hasNormals) {
  37778. var vector = {
  37779. name: "NORMAL",
  37780. attributes: ["NormalX", "NormalY", "NormalZ"]
  37781. };
  37782. attributes.addVector(vector);
  37783. }
  37784. }
  37785. return attributes;
  37786. }
  37787. static load(url) {
  37788. return _asyncToGenerator(function* () {
  37789. var response = yield fetch(url);
  37790. var metadata = yield response.json();
  37791. var attributes = OctreeLoader.parseAttributes(metadata.attributes);
  37792. var loader = new NodeLoader(url);
  37793. loader.metadata = metadata;
  37794. loader.attributes = attributes;
  37795. loader.scale = metadata.scale;
  37796. loader.offset = metadata.offset;
  37797. var octree = new OctreeGeometry();
  37798. octree.url = url;
  37799. octree.spacing = metadata.spacing;
  37800. octree.scale = metadata.scale;
  37801. // let aPosition = metadata.attributes.find(a => a.name === "position");
  37802. // octree
  37803. var min = new Vector3(...metadata.boundingBox.min);
  37804. var max = new Vector3(...metadata.boundingBox.max);
  37805. var boundingBox = new Box3(min, max);
  37806. var offset = min.clone();
  37807. boundingBox.min.sub(offset);
  37808. boundingBox.max.sub(offset);
  37809. octree.projection = metadata.projection;
  37810. octree.boundingBox = boundingBox;
  37811. octree.tightBoundingBox = boundingBox.clone();
  37812. octree.boundingSphere = boundingBox.getBoundingSphere(new Sphere());
  37813. octree.tightBoundingSphere = boundingBox.getBoundingSphere(new Sphere());
  37814. octree.offset = offset;
  37815. octree.pointAttributes = OctreeLoader.parseAttributes(metadata.attributes);
  37816. octree.loader = loader;
  37817. var root = new OctreeGeometryNode("r", octree, boundingBox);
  37818. root.level = 0;
  37819. root.nodeType = 2;
  37820. root.hierarchyByteOffset = 0n;
  37821. root.hierarchyByteSize = BigInt(metadata.hierarchy.firstChunkSize);
  37822. root.hasChildren = false;
  37823. root.spacing = octree.spacing;
  37824. root.byteOffset = 0;
  37825. octree.root = root;
  37826. loader.load(root);
  37827. var result = {
  37828. geometry: octree
  37829. };
  37830. return result;
  37831. })();
  37832. }
  37833. }
  37834. ;
  37835. /**
  37836. * @author Connor Manning
  37837. */
  37838. class EptLoader {
  37839. static load(file, callback) {
  37840. return _asyncToGenerator(function* () {
  37841. var response = yield fetch(file);
  37842. var json = yield response.json();
  37843. var url = file.substr(0, file.lastIndexOf('ept.json'));
  37844. var geometry = new Potree.PointCloudEptGeometry(url, json);
  37845. var root = new Potree.PointCloudEptGeometryNode(geometry);
  37846. geometry.root = root;
  37847. geometry.root.load();
  37848. callback(geometry);
  37849. })();
  37850. }
  37851. }
  37852. ;
  37853. class EptBinaryLoader {
  37854. extension() {
  37855. return '.bin';
  37856. }
  37857. workerPath() {
  37858. return Potree.scriptPath + '/workers/EptBinaryDecoderWorker.js';
  37859. }
  37860. load(node) {
  37861. if (node.loaded) return;
  37862. var url = node.url() + this.extension();
  37863. var xhr = XHRFactory.createXMLHttpRequest();
  37864. xhr.open('GET', url, true);
  37865. xhr.responseType = 'arraybuffer';
  37866. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  37867. xhr.onreadystatechange = () => {
  37868. if (xhr.readyState === 4) {
  37869. if (xhr.status === 200) {
  37870. var buffer = xhr.response;
  37871. this.parse(node, buffer);
  37872. } else {
  37873. console.log('Failed ' + url + ': ' + xhr.status);
  37874. }
  37875. }
  37876. };
  37877. try {
  37878. xhr.send(null);
  37879. } catch (e) {
  37880. console.log('Failed request: ' + e);
  37881. }
  37882. }
  37883. parse(node, buffer) {
  37884. var workerPath = this.workerPath();
  37885. var worker = Potree.workerPool.getWorker(workerPath);
  37886. worker.onmessage = function (e) {
  37887. var g = new BufferGeometry();
  37888. var numPoints = e.data.numPoints;
  37889. var position = new Float32Array(e.data.position);
  37890. g.setAttribute('position', new BufferAttribute(position, 3));
  37891. var indices = new Uint8Array(e.data.indices);
  37892. g.setAttribute('indices', new BufferAttribute(indices, 4));
  37893. if (e.data.color) {
  37894. var color = new Uint8Array(e.data.color);
  37895. g.setAttribute('color', new BufferAttribute(color, 4, true));
  37896. }
  37897. if (e.data.intensity) {
  37898. var intensity = new Float32Array(e.data.intensity);
  37899. g.setAttribute('intensity', new BufferAttribute(intensity, 1));
  37900. }
  37901. if (e.data.classification) {
  37902. var classification = new Uint8Array(e.data.classification);
  37903. g.setAttribute('classification', new BufferAttribute(classification, 1));
  37904. }
  37905. if (e.data.returnNumber) {
  37906. var returnNumber = new Uint8Array(e.data.returnNumber);
  37907. g.setAttribute('return number', new BufferAttribute(returnNumber, 1));
  37908. }
  37909. if (e.data.numberOfReturns) {
  37910. var numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  37911. g.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  37912. }
  37913. if (e.data.pointSourceId) {
  37914. var pointSourceId = new Uint16Array(e.data.pointSourceId);
  37915. g.setAttribute('source id', new BufferAttribute(pointSourceId, 1));
  37916. }
  37917. g.attributes.indices.normalized = true;
  37918. var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max));
  37919. node.doneLoading(g, tightBoundingBox, numPoints, new Vector3(...e.data.mean));
  37920. Potree.workerPool.returnWorker(workerPath, worker);
  37921. };
  37922. var toArray = v => [v.x, v.y, v.z];
  37923. var message = {
  37924. buffer: buffer,
  37925. schema: node.ept.schema,
  37926. scale: node.ept.eptScale,
  37927. offset: node.ept.eptOffset,
  37928. mins: toArray(node.key.b.min)
  37929. };
  37930. worker.postMessage(message, [message.buffer]);
  37931. }
  37932. }
  37933. ;
  37934. /**
  37935. * laslaz code taken and adapted from plas.io js-laslaz
  37936. * http://plas.io/
  37937. * https://github.com/verma/plasio
  37938. *
  37939. * Thanks to Uday Verma and Howard Butler
  37940. *
  37941. */
  37942. class EptLaszipLoader {
  37943. load(node) {
  37944. if (node.loaded) return;
  37945. var url = node.url() + '.laz';
  37946. var xhr = XHRFactory.createXMLHttpRequest();
  37947. xhr.open('GET', url, true);
  37948. xhr.responseType = 'arraybuffer';
  37949. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  37950. xhr.onreadystatechange = () => {
  37951. if (xhr.readyState === 4) {
  37952. if (xhr.status === 200) {
  37953. var buffer = xhr.response;
  37954. this.parse(node, buffer);
  37955. } else {
  37956. console.log('Failed ' + url + ': ' + xhr.status);
  37957. }
  37958. }
  37959. };
  37960. xhr.send(null);
  37961. }
  37962. parse(node, buffer) {
  37963. return _asyncToGenerator(function* () {
  37964. var lf = new LASFile(buffer);
  37965. var handler = new EptLazBatcher(node);
  37966. try {
  37967. yield lf.open();
  37968. lf.isOpen = true;
  37969. var header = yield lf.getHeader();
  37970. {
  37971. var i = 0;
  37972. var toArray = v => [v.x, v.y, v.z];
  37973. var mins = toArray(node.key.b.min);
  37974. var maxs = toArray(node.key.b.max);
  37975. var hasMoreData = true;
  37976. while (hasMoreData) {
  37977. var data = yield lf.readData(1000000, 0, 1);
  37978. var d = new LASDecoder(data.buffer, header.pointsFormatId, header.pointsStructSize, data.count, header.scale, header.offset, mins, maxs);
  37979. d.extraBytes = header.extraBytes;
  37980. d.pointsFormatId = header.pointsFormatId;
  37981. handler.push(d);
  37982. i += data.count;
  37983. hasMoreData = data.hasMoreData;
  37984. }
  37985. header.totalRead = i;
  37986. header.versionAsString = lf.versionAsString;
  37987. header.isCompressed = lf.isCompressed;
  37988. yield lf.close();
  37989. lf.isOpen = false;
  37990. }
  37991. } catch (err) {
  37992. console.error('Error reading LAZ:', err);
  37993. if (lf.isOpen) {
  37994. yield lf.close();
  37995. lf.isOpen = false;
  37996. }
  37997. throw err;
  37998. }
  37999. })();
  38000. }
  38001. }
  38002. ;
  38003. class EptLazBatcher {
  38004. constructor(node) {
  38005. this.node = node;
  38006. }
  38007. push(las) {
  38008. var workerPath = Potree.scriptPath + '/workers/EptLaszipDecoderWorker.js';
  38009. var worker = Potree.workerPool.getWorker(workerPath);
  38010. worker.onmessage = e => {
  38011. var g = new BufferGeometry();
  38012. var numPoints = las.pointsCount;
  38013. var positions = new Float32Array(e.data.position);
  38014. var colors = new Uint8Array(e.data.color);
  38015. var intensities = new Float32Array(e.data.intensity);
  38016. var classifications = new Uint8Array(e.data.classification);
  38017. var returnNumbers = new Uint8Array(e.data.returnNumber);
  38018. var numberOfReturns = new Uint8Array(e.data.numberOfReturns);
  38019. var pointSourceIDs = new Uint16Array(e.data.pointSourceID);
  38020. var indices = new Uint8Array(e.data.indices);
  38021. var gpsTime = new Float32Array(e.data.gpsTime);
  38022. g.setAttribute('position', new BufferAttribute(positions, 3));
  38023. g.setAttribute('rgba', new BufferAttribute(colors, 4, true));
  38024. g.setAttribute('intensity', new BufferAttribute(intensities, 1));
  38025. g.setAttribute('classification', new BufferAttribute(classifications, 1));
  38026. g.setAttribute('return number', new BufferAttribute(returnNumbers, 1));
  38027. g.setAttribute('number of returns', new BufferAttribute(numberOfReturns, 1));
  38028. g.setAttribute('source id', new BufferAttribute(pointSourceIDs, 1));
  38029. g.setAttribute('indices', new BufferAttribute(indices, 4));
  38030. g.setAttribute('gpsTime', new BufferAttribute(gpsTime, 1));
  38031. this.node.gpsTime = e.data.gpsMeta;
  38032. g.attributes.indices.normalized = true;
  38033. var tightBoundingBox = new Box3(new Vector3().fromArray(e.data.tightBoundingBox.min), new Vector3().fromArray(e.data.tightBoundingBox.max));
  38034. this.node.doneLoading(g, tightBoundingBox, numPoints, new Vector3(...e.data.mean));
  38035. Potree.workerPool.returnWorker(workerPath, worker);
  38036. };
  38037. var message = {
  38038. buffer: las.arrayb,
  38039. numPoints: las.pointsCount,
  38040. pointSize: las.pointSize,
  38041. pointFormatID: las.pointsFormatId,
  38042. scale: las.scale,
  38043. offset: las.offset,
  38044. mins: las.mins,
  38045. maxs: las.maxs
  38046. };
  38047. worker.postMessage(message, [message.buffer]);
  38048. }
  38049. }
  38050. ;
  38051. class EptZstandardLoader extends EptBinaryLoader {
  38052. extension() {
  38053. return '.zst';
  38054. }
  38055. workerPath() {
  38056. return Potree.scriptPath + '/workers/EptZstandardDecoderWorker.js';
  38057. }
  38058. }
  38059. ;
  38060. class ShapefileLoader {
  38061. constructor() {
  38062. this.transform = null;
  38063. }
  38064. load(path, color) {
  38065. var _this = this;
  38066. return _asyncToGenerator(function* () {
  38067. var matLine = new LineMaterial({
  38068. color: color || 0xff0000,
  38069. lineWidth: 3,
  38070. // in pixels
  38071. resolution: new Vector2(1000, 1000),
  38072. dashed: false
  38073. });
  38074. var features = yield _this.loadShapefileFeatures(path);
  38075. var node = new Object3D();
  38076. var jump = 0;
  38077. for (var feature of features) {
  38078. //5是碎的
  38079. //if(feature.geometry.type!= 'MultiLineString' || ++jump != 5) continue
  38080. var fnode = _this.featureToSceneNode(feature, matLine);
  38081. fnode && node.add(fnode);
  38082. }
  38083. var setResolution = (x, y) => {
  38084. matLine.resolution.set(x, y);
  38085. };
  38086. var result = {
  38087. features: features,
  38088. node: node,
  38089. setResolution: setResolution
  38090. };
  38091. return result;
  38092. })();
  38093. }
  38094. featureToSceneNode(feature, matLine) {
  38095. //console.log(feature)
  38096. var geometry = feature.geometry;
  38097. var color = new Color(1, 1, 1);
  38098. var transform = this.transform;
  38099. if (transform === null) {
  38100. transform = {
  38101. forward: v => v
  38102. };
  38103. }
  38104. if (geometry.type === "Point") {
  38105. var sg = new SphereGeometry(1, 18, 18);
  38106. var sm = new MeshNormalMaterial();
  38107. var s = new Mesh(sg, sm);
  38108. var [long, lat] = geometry.coordinates;
  38109. var pos = transform.forward([long, lat]);
  38110. s.position.set(...pos, 20);
  38111. s.scale.set(10, 10, 10);
  38112. return s;
  38113. } else if (geometry.type === "LineString") {
  38114. var coordinates = [];
  38115. var min = new Vector3(Infinity, Infinity, Infinity);
  38116. for (var i = 0; i < geometry.coordinates.length; i++) {
  38117. var [_long, _lat] = geometry.coordinates[i];
  38118. var _pos = transform.forward([_long, _lat]);
  38119. min.x = Math.min(min.x, _pos[0]);
  38120. min.y = Math.min(min.y, _pos[1]);
  38121. min.z = Math.min(min.z, 20);
  38122. coordinates.push(..._pos, 20);
  38123. if (i > 0 && i < geometry.coordinates.length - 1) {
  38124. coordinates.push(..._pos, 20);
  38125. }
  38126. }
  38127. for (var _i = 0; _i < coordinates.length; _i += 3) {
  38128. coordinates[_i + 0] -= min.x;
  38129. coordinates[_i + 1] -= min.y;
  38130. coordinates[_i + 2] -= min.z;
  38131. }
  38132. var lineGeometry = new LineGeometry();
  38133. lineGeometry.setPositions(coordinates);
  38134. var line = new Line2(lineGeometry, matLine);
  38135. line.computeLineDistances();
  38136. line.scale.set(1, 1, 1);
  38137. line.position.copy(min);
  38138. return line;
  38139. } else if (geometry.type === "MultiLineString") {
  38140. //xzw add 江门的那个文件
  38141. var _coordinates = [];
  38142. //console.warn('MultiLineString') //多组连续线段,组之间不连续
  38143. var _min = new Vector3(Infinity, Infinity, Infinity);
  38144. var _loop = function _loop() {
  38145. var points = geometry.coordinates[_i2]; //有时候是两个点有时候多个
  38146. var coordinateSlice = [];
  38147. points.forEach(point => {
  38148. var [long, lat] = point;
  38149. var pos = transform.forward([long, lat]);
  38150. _min.x = Math.min(_min.x, pos[0]);
  38151. _min.y = Math.min(_min.y, pos[1]);
  38152. _min.z = Math.min(_min.z, 20);
  38153. coordinateSlice.push(new Vector3(pos[0], pos[1], 20));
  38154. });
  38155. _coordinates.push(coordinateSlice);
  38156. };
  38157. for (var _i2 = 0; _i2 < geometry.coordinates.length; _i2++) {
  38158. _loop();
  38159. }
  38160. _coordinates.forEach(coordinateSlice => coordinateSlice.forEach(point => point.sub(_min)));
  38161. var _line = LineDraw.createFatLine(_coordinates, {
  38162. uncontinuous: true,
  38163. mat: matLine
  38164. /* color: 0xff0000,
  38165. dashSize: 0.5,
  38166. gapSize: 0.2,
  38167. lineWidth: config$1.measure.lineWidth, */
  38168. });
  38169. _line.position.copy(_min);
  38170. return _line;
  38171. } else if (geometry.type === "Polygon") {
  38172. for (var pc of geometry.coordinates) {
  38173. var _coordinates2 = [];
  38174. var _min2 = new Vector3(Infinity, Infinity, Infinity);
  38175. for (var _i3 = 0; _i3 < pc.length; _i3++) {
  38176. var [_long2, _lat2] = pc[_i3];
  38177. var _pos2 = transform.forward([_long2, _lat2]);
  38178. _min2.x = Math.min(_min2.x, _pos2[0]);
  38179. _min2.y = Math.min(_min2.y, _pos2[1]);
  38180. _min2.z = Math.min(_min2.z, 20);
  38181. _coordinates2.push(..._pos2, 20);
  38182. if (_i3 > 0 && _i3 < pc.length - 1) {
  38183. _coordinates2.push(..._pos2, 20);
  38184. }
  38185. }
  38186. for (var _i4 = 0; _i4 < _coordinates2.length; _i4 += 3) {
  38187. _coordinates2[_i4 + 0] -= _min2.x;
  38188. _coordinates2[_i4 + 1] -= _min2.y;
  38189. _coordinates2[_i4 + 2] -= _min2.z;
  38190. }
  38191. var _lineGeometry = new LineGeometry();
  38192. _lineGeometry.setPositions(_coordinates2);
  38193. var _line2 = new Line2(_lineGeometry, matLine);
  38194. _line2.computeLineDistances();
  38195. _line2.scale.set(1, 1, 1);
  38196. _line2.position.copy(_min2);
  38197. return _line2;
  38198. }
  38199. } else {
  38200. console.log("unhandled feature: ", geometry.type);
  38201. }
  38202. function getLine(coordinates) {}
  38203. }
  38204. loadShapefileFeatures(file) {
  38205. return _asyncToGenerator(function* () {
  38206. var features = [];
  38207. if (file.split('.').pop() == 'shp') {
  38208. var source = yield shapefile.open(file);
  38209. while (true) {
  38210. var result = yield source.read();
  38211. if (result.done) {
  38212. break;
  38213. }
  38214. if (result.value && result.value.type === 'Feature' && result.value.geometry !== undefined) {
  38215. features.push(result.value);
  38216. }
  38217. }
  38218. return features;
  38219. } else if (file.split('.').pop() == 'json') {
  38220. return new Promise((resolve, reject) => {
  38221. Potree.loadFile(file, {/* returnText:true */}, data => {
  38222. console.log(data);
  38223. resolve(data.features);
  38224. });
  38225. });
  38226. }
  38227. })();
  38228. }
  38229. }
  38230. ;
  38231. var defaultColors = {
  38232. "landuse": [0.5, 0.5, 0.5],
  38233. "natural": [0.0, 1.0, 0.0],
  38234. "places": [1.0, 0.0, 1.0],
  38235. "points": [0.0, 1.0, 1.0],
  38236. "roads": [1.0, 1.0, 0.0],
  38237. "waterways": [0.0, 0.0, 1.0],
  38238. "default": [0.9, 0.6, 0.1]
  38239. };
  38240. function getColor(feature) {
  38241. var color = defaultColors[feature];
  38242. if (!color) {
  38243. color = defaultColors["default"];
  38244. }
  38245. return color;
  38246. }
  38247. class Geopackage$1 {
  38248. constructor() {
  38249. this.path = null;
  38250. this.node = null;
  38251. }
  38252. }
  38253. ;
  38254. class GeoPackageLoader {
  38255. constructor() {}
  38256. static loadUrl(url, params) {
  38257. return _asyncToGenerator(function* () {
  38258. yield Promise.all([Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/geopackage/geopackage.js")), Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.js"))]);
  38259. var result = yield fetch(url);
  38260. var buffer = yield result.arrayBuffer();
  38261. params = params || {};
  38262. params.source = url;
  38263. return GeoPackageLoader.loadBuffer(buffer, params);
  38264. })();
  38265. }
  38266. static loadBuffer(buffer, params) {
  38267. return _asyncToGenerator(function* () {
  38268. yield Promise.all([Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/geopackage/geopackage.js")), Utils.loadScript("".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.js"))]);
  38269. params = params || {};
  38270. var resolver = /*#__PURE__*/function () {
  38271. var _ref = _asyncToGenerator(function* (resolve) {
  38272. var transform = params.transform;
  38273. if (!transform) {
  38274. transform = {
  38275. forward: arg => arg
  38276. };
  38277. }
  38278. var wasmPath = "".concat(Potree.scriptPath, "/lazylibs/sql.js/sql-wasm.wasm");
  38279. var SQL = yield initSqlJs({
  38280. locateFile: filename => wasmPath
  38281. });
  38282. var u8 = new Uint8Array(buffer);
  38283. var data = yield geopackage.open(u8);
  38284. window.data = data;
  38285. var geopackageNode = new Object3D();
  38286. geopackageNode.name = params.source;
  38287. geopackageNode.potree = {
  38288. source: params.source
  38289. };
  38290. var geo = new Geopackage$1();
  38291. geo.path = params.source;
  38292. geo.node = geopackageNode;
  38293. var tables = data.getTables();
  38294. for (var table of tables.features) {
  38295. var dao = data.getFeatureDao(table);
  38296. var boundingBox = dao.getBoundingBox();
  38297. boundingBox = boundingBox.projectBoundingBox(dao.projection, 'EPSG:4326');
  38298. var geoJson = data.queryForGeoJSONFeaturesInTable(table, boundingBox);
  38299. var matLine = new LineMaterial({
  38300. color: new Color().setRGB(...getColor(table)),
  38301. linewidth: 2,
  38302. resolution: new Vector2(1000, 1000),
  38303. dashed: false
  38304. });
  38305. var node = new Object3D();
  38306. node.name = table;
  38307. geo.node.add(node);
  38308. for (var [index, feature] of Object.entries(geoJson)) {
  38309. //const featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, transform);
  38310. var featureNode = GeoPackageLoader.featureToSceneNode(feature, matLine, dao.projection, transform);
  38311. node.add(featureNode);
  38312. }
  38313. }
  38314. resolve(geo);
  38315. });
  38316. return function resolver(_x) {
  38317. return _ref.apply(this, arguments);
  38318. };
  38319. }();
  38320. return new Promise(resolver);
  38321. })();
  38322. }
  38323. static featureToSceneNode(feature, matLine, geopackageProjection, transform) {
  38324. var geometry = feature.geometry;
  38325. var color = new Color(1, 1, 1);
  38326. if (feature.geometry.type === "Point") {
  38327. var sg = new SphereGeometry(1, 18, 18);
  38328. var sm = new MeshNormalMaterial();
  38329. var s = new Mesh(sg, sm);
  38330. var [long, lat] = geometry.coordinates;
  38331. var pos = transform.forward(geopackageProjection.forward([long, lat]));
  38332. s.position.set(...pos, 20);
  38333. s.scale.set(10, 10, 10);
  38334. return s;
  38335. } else if (geometry.type === "LineString") {
  38336. var coordinates = [];
  38337. var min = new Vector3(Infinity, Infinity, Infinity);
  38338. for (var i = 0; i < geometry.coordinates.length; i++) {
  38339. var [_long, _lat] = geometry.coordinates[i];
  38340. var _pos = transform.forward(geopackageProjection.forward([_long, _lat]));
  38341. min.x = Math.min(min.x, _pos[0]);
  38342. min.y = Math.min(min.y, _pos[1]);
  38343. min.z = Math.min(min.z, 20);
  38344. coordinates.push(..._pos, 20);
  38345. if (i > 0 && i < geometry.coordinates.length - 1) {
  38346. coordinates.push(..._pos, 20);
  38347. }
  38348. }
  38349. for (var _i = 0; _i < coordinates.length; _i += 3) {
  38350. coordinates[_i + 0] -= min.x;
  38351. coordinates[_i + 1] -= min.y;
  38352. coordinates[_i + 2] -= min.z;
  38353. }
  38354. var lineGeometry = new LineGeometry();
  38355. lineGeometry.setPositions(coordinates);
  38356. var line = new Line2(lineGeometry, matLine);
  38357. line.computeLineDistances();
  38358. line.scale.set(1, 1, 1);
  38359. line.position.copy(min);
  38360. return line;
  38361. } else if (geometry.type === "Polygon") {
  38362. for (var pc of geometry.coordinates) {
  38363. var _coordinates = [];
  38364. var _min = new Vector3(Infinity, Infinity, Infinity);
  38365. for (var _i2 = 0; _i2 < pc.length; _i2++) {
  38366. var [_long2, _lat2] = pc[_i2];
  38367. var _pos2 = transform.forward(geopackageProjection.forward([_long2, _lat2]));
  38368. _min.x = Math.min(_min.x, _pos2[0]);
  38369. _min.y = Math.min(_min.y, _pos2[1]);
  38370. _min.z = Math.min(_min.z, 20);
  38371. _coordinates.push(..._pos2, 20);
  38372. if (_i2 > 0 && _i2 < pc.length - 1) {
  38373. _coordinates.push(..._pos2, 20);
  38374. }
  38375. }
  38376. for (var _i3 = 0; _i3 < _coordinates.length; _i3 += 3) {
  38377. _coordinates[_i3 + 0] -= _min.x;
  38378. _coordinates[_i3 + 1] -= _min.y;
  38379. _coordinates[_i3 + 2] -= _min.z;
  38380. }
  38381. var _lineGeometry = new LineGeometry();
  38382. _lineGeometry.setPositions(_coordinates);
  38383. var _line = new Line2(_lineGeometry, matLine);
  38384. _line.computeLineDistances();
  38385. _line.scale.set(1, 1, 1);
  38386. _line.position.copy(_min);
  38387. return _line;
  38388. }
  38389. } else {
  38390. console.log("unhandled feature: ", feature);
  38391. }
  38392. }
  38393. }
  38394. ;
  38395. class ClipVolume extends Object3D {
  38396. constructor(args) {
  38397. super();
  38398. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  38399. this.name = "clip_volume_" + this.constructor.counter;
  38400. var alpha = args.alpha || 0;
  38401. var beta = args.beta || 0;
  38402. var gamma = args.gamma || 0;
  38403. this.rotation.x = alpha;
  38404. this.rotation.y = beta;
  38405. this.rotation.z = gamma;
  38406. this.clipOffset = 0.001;
  38407. this.clipRotOffset = 1;
  38408. var boxGeometry = new BoxGeometry(1, 1, 1);
  38409. boxGeometry.computeBoundingBox();
  38410. var boxFrameGeometry = new Geometry();
  38411. {
  38412. // bottom
  38413. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  38414. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  38415. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  38416. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  38417. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  38418. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  38419. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  38420. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  38421. // top
  38422. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  38423. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  38424. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  38425. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  38426. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  38427. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  38428. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  38429. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  38430. // sides
  38431. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  38432. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  38433. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  38434. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  38435. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  38436. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  38437. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  38438. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  38439. boxFrameGeometry.colors.push(new Vector3(1, 1, 1));
  38440. }
  38441. var planeFrameGeometry = new Geometry();
  38442. {
  38443. // middle line
  38444. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  38445. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  38446. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  38447. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  38448. planeFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.0));
  38449. planeFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.0));
  38450. planeFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.0));
  38451. planeFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.0));
  38452. }
  38453. this.dimension = new Vector3(1, 1, 1);
  38454. this.material = new MeshBasicMaterial({
  38455. color: 0x00ff00,
  38456. transparent: true,
  38457. opacity: 0.3,
  38458. depthTest: true,
  38459. depthWrite: false
  38460. });
  38461. this.box = new Mesh(boxGeometry, this.material);
  38462. this.box.geometry.computeBoundingBox();
  38463. this.boundingBox = this.box.geometry.boundingBox;
  38464. this.add(this.box);
  38465. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({
  38466. color: 0x000000
  38467. }));
  38468. this.add(this.frame);
  38469. this.planeFrame = new LineSegments(planeFrameGeometry, new LineBasicMaterial({
  38470. color: 0xff0000
  38471. }));
  38472. this.add(this.planeFrame);
  38473. // set default thickness
  38474. this.setScaleZ(0.1);
  38475. // create local coordinate system
  38476. var createArrow = (name, direction, color) => {
  38477. var material = new MeshBasicMaterial({
  38478. color: color,
  38479. depthTest: false,
  38480. depthWrite: false
  38481. });
  38482. var shaftGeometry = new Geometry();
  38483. shaftGeometry.vertices.push(new Vector3(0, 0, 0));
  38484. shaftGeometry.vertices.push(new Vector3(0, 1, 0));
  38485. var shaftMaterial = new LineBasicMaterial({
  38486. color: color,
  38487. depthTest: false,
  38488. depthWrite: false,
  38489. transparent: true
  38490. });
  38491. var shaft = new Line(shaftGeometry, shaftMaterial);
  38492. shaft.name = name + "_shaft";
  38493. var headGeometry = new CylinderGeometry(0, 0.04, 0.1, 10, 1, false);
  38494. var headMaterial = material;
  38495. var head = new Mesh(headGeometry, headMaterial);
  38496. head.name = name + "_head";
  38497. head.position.y = 1;
  38498. var arrow = new Object3D();
  38499. arrow.name = name;
  38500. arrow.add(shaft);
  38501. arrow.add(head);
  38502. return arrow;
  38503. };
  38504. this.arrowX = createArrow("arrow_x", new Vector3(1, 0, 0), 0xFF0000);
  38505. this.arrowY = createArrow("arrow_y", new Vector3(0, 1, 0), 0x00FF00);
  38506. this.arrowZ = createArrow("arrow_z", new Vector3(0, 0, 1), 0x0000FF);
  38507. this.arrowX.rotation.z = -Math.PI / 2;
  38508. this.arrowZ.rotation.x = Math.PI / 2;
  38509. this.arrowX.visible = false;
  38510. this.arrowY.visible = false;
  38511. this.arrowZ.visible = false;
  38512. this.add(this.arrowX);
  38513. this.add(this.arrowY);
  38514. this.add(this.arrowZ);
  38515. {
  38516. // event listeners
  38517. this.addEventListener("ui_select", e => {
  38518. this.arrowX.visible = true;
  38519. this.arrowY.visible = true;
  38520. this.arrowZ.visible = true;
  38521. });
  38522. this.addEventListener("ui_deselect", e => {
  38523. this.arrowX.visible = false;
  38524. this.arrowY.visible = false;
  38525. this.arrowZ.visible = false;
  38526. });
  38527. this.addEventListener("select", e => {
  38528. var scene_header = $("#" + this.name + " .scene_header");
  38529. if (!scene_header.next().is(":visible")) {
  38530. scene_header.click();
  38531. }
  38532. });
  38533. this.addEventListener("deselect", e => {
  38534. var scene_header = $("#" + this.name + " .scene_header");
  38535. if (scene_header.next().is(":visible")) {
  38536. scene_header.click();
  38537. }
  38538. });
  38539. }
  38540. this.update();
  38541. }
  38542. setClipOffset(offset) {
  38543. this.clipOffset = offset;
  38544. }
  38545. setClipRotOffset(offset) {
  38546. this.clipRotOffset = offset;
  38547. }
  38548. setScaleX(x) {
  38549. this.box.scale.x = x;
  38550. this.frame.scale.x = x;
  38551. this.planeFrame.scale.x = x;
  38552. }
  38553. setScaleY(y) {
  38554. this.box.scale.y = y;
  38555. this.frame.scale.y = y;
  38556. this.planeFrame.scale.y = y;
  38557. }
  38558. setScaleZ(z) {
  38559. this.box.scale.z = z;
  38560. this.frame.scale.z = z;
  38561. this.planeFrame.scale.z = z;
  38562. }
  38563. offset(args) {
  38564. var cs = args.cs || null;
  38565. var axis = args.axis || null;
  38566. var dir = args.dir || null;
  38567. if (!cs || !axis || !dir) return;
  38568. if (axis === "x") {
  38569. if (cs === "local") {
  38570. this.position.add(this.localX.clone().multiplyScalar(dir * this.clipOffset));
  38571. } else if (cs === "global") {
  38572. this.position.x = this.position.x + dir * this.clipOffset;
  38573. }
  38574. } else if (axis === "y") {
  38575. if (cs === "local") {
  38576. this.position.add(this.localY.clone().multiplyScalar(dir * this.clipOffset));
  38577. } else if (cs === "global") {
  38578. this.position.y = this.position.y + dir * this.clipOffset;
  38579. }
  38580. } else if (axis === "z") {
  38581. if (cs === "local") {
  38582. this.position.add(this.localZ.clone().multiplyScalar(dir * this.clipOffset));
  38583. } else if (cs === "global") {
  38584. this.position.z = this.position.z + dir * this.clipOffset;
  38585. }
  38586. }
  38587. this.dispatchEvent({
  38588. "type": "clip_volume_changed",
  38589. "viewer": viewer,
  38590. "volume": this
  38591. });
  38592. }
  38593. rotate(args) {
  38594. var cs = args.cs || null;
  38595. var axis = args.axis || null;
  38596. var dir = args.dir || null;
  38597. if (!cs || !axis || !dir) return;
  38598. if (cs === "local") {
  38599. if (axis === "x") {
  38600. this.rotateOnAxis(new Vector3(1, 0, 0), dir * this.clipRotOffset * Math.PI / 180);
  38601. } else if (axis === "y") {
  38602. this.rotateOnAxis(new Vector3(0, 1, 0), dir * this.clipRotOffset * Math.PI / 180);
  38603. } else if (axis === "z") {
  38604. this.rotateOnAxis(new Vector3(0, 0, 1), dir * this.clipRotOffset * Math.PI / 180);
  38605. }
  38606. } else if (cs === "global") {
  38607. var rotaxis = new Vector4(1, 0, 0, 0);
  38608. if (axis === "y") {
  38609. rotaxis = new Vector4(0, 1, 0, 0);
  38610. } else if (axis === "z") {
  38611. rotaxis = new Vector4(0, 0, 1, 0);
  38612. }
  38613. this.updateMatrixWorld();
  38614. var invM = newthis.matrixWorld.clone().invert();
  38615. rotaxis = rotaxis.applyMatrix4(invM).normalize();
  38616. rotaxis = new Vector3(rotaxis.x, rotaxis.y, rotaxis.z);
  38617. this.rotateOnAxis(rotaxis, dir * this.clipRotOffset * Math.PI / 180);
  38618. }
  38619. this.updateLocalSystem();
  38620. this.dispatchEvent({
  38621. "type": "clip_volume_changed",
  38622. "viewer": viewer,
  38623. "volume": this
  38624. });
  38625. }
  38626. update() {
  38627. this.boundingBox = this.box.geometry.boundingBox;
  38628. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  38629. this.box.visible = false;
  38630. this.updateLocalSystem();
  38631. }
  38632. updateLocalSystem() {
  38633. // extract local coordinate axes
  38634. var rotQuat = this.getWorldQuaternion();
  38635. this.localX = new Vector3(1, 0, 0).applyQuaternion(rotQuat).normalize();
  38636. this.localY = new Vector3(0, 1, 0).applyQuaternion(rotQuat).normalize();
  38637. this.localZ = new Vector3(0, 0, 1).applyQuaternion(rotQuat).normalize();
  38638. }
  38639. raycast(raycaster, intersects) {
  38640. var is = [];
  38641. this.box.raycast(raycaster, is);
  38642. if (is.length > 0) {
  38643. var I = is[0];
  38644. intersects.push({
  38645. distance: I.distance,
  38646. object: this,
  38647. point: I.point.clone()
  38648. });
  38649. }
  38650. }
  38651. }
  38652. ;
  38653. //这个文件只是clipping polygon的,没用到
  38654. class ClippingTool extends EventDispatcher$1 {
  38655. constructor(viewer) {
  38656. super();
  38657. this.viewer = viewer;
  38658. this.maxPolygonVertices = 8;
  38659. this.addEventListener("start_inserting_clipping_volume", e => {
  38660. this.viewer.dispatchEvent({
  38661. type: "cancel_insertions"
  38662. });
  38663. });
  38664. this.sceneMarker = new Scene();
  38665. this.sceneVolume = new Scene();
  38666. this.sceneVolume.name = "scene_clip_volume";
  38667. this.viewer.inputHandler.registerInteractiveScene(this.sceneVolume);
  38668. this.onRemove = e => {
  38669. this.sceneVolume.remove(e.volume);
  38670. };
  38671. this.onAdd = e => {
  38672. this.sceneVolume.add(e.volume);
  38673. };
  38674. this.viewer.inputHandler.addEventListener("delete", e => {
  38675. var volumes = e.selection.filter(e => e instanceof ClipVolume);
  38676. volumes.forEach(e => this.viewer.scene.removeClipVolume(e));
  38677. var polyVolumes = e.selection.filter(e => e instanceof PolygonClipVolume);
  38678. polyVolumes.forEach(e => this.viewer.scene.removePolygonClipVolume(e));
  38679. });
  38680. }
  38681. setScene(scene) {
  38682. if (this.scene === scene) {
  38683. return;
  38684. }
  38685. if (this.scene) {
  38686. this.scene.removeEventListeners("clip_volume_added", this.onAdd);
  38687. this.scene.removeEventListeners("clip_volume_removed", this.onRemove);
  38688. this.scene.removeEventListeners("polygon_clip_volume_added", this.onAdd);
  38689. this.scene.removeEventListeners("polygon_clip_volume_removed", this.onRemove);
  38690. }
  38691. this.scene = scene;
  38692. this.scene.addEventListener("clip_volume_added", this.onAdd);
  38693. this.scene.addEventListener("clip_volume_removed", this.onRemove);
  38694. this.scene.addEventListener("polygon_clip_volume_added", this.onAdd);
  38695. this.scene.addEventListener("polygon_clip_volume_removed", this.onRemove);
  38696. }
  38697. startInsertion() {
  38698. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  38699. var type = args.type || null;
  38700. if (!type) return null;
  38701. var domElement = this.viewer.renderer.domElement;
  38702. var canvasSize = this.viewer.renderer.getSize(new Vector2());
  38703. var svg = $("\n\t\t<svg height=\"".concat(canvasSize.height, "\" width=\"").concat(canvasSize.width, "\" style=\"position:absolute; pointer-events: none\">\n\n\t\t\t<defs>\n\t\t\t\t <marker id=\"diamond\" markerWidth=\"24\" markerHeight=\"24\" refX=\"12\" refY=\"12\"\n\t\t\t\t\t\tmarkerUnits=\"userSpaceOnUse\">\n\t\t\t\t\t<circle cx=\"12\" cy=\"12\" r=\"6\" fill=\"white\" stroke=\"black\" stroke-width=\"3\"/>\n\t\t\t\t</marker>\n\t\t\t</defs>\n\n\t\t\t<polyline fill=\"none\" stroke=\"black\" \n\t\t\t\tstyle=\"stroke:rgb(0, 0, 0);\n\t\t\t\tstroke-width:6;\"\n\t\t\t\tstroke-dasharray=\"9, 6\"\n\t\t\t\tstroke-dashoffset=\"2\"\n\t\t\t\t/>\n\n\t\t\t<polyline fill=\"none\" stroke=\"black\" \n\t\t\t\tstyle=\"stroke:rgb(255, 255, 255);\n\t\t\t\tstroke-width:2;\"\n\t\t\t\tstroke-dasharray=\"5, 10\"\n\t\t\t\tmarker-start=\"url(#diamond)\" \n\t\t\t\tmarker-mid=\"url(#diamond)\" \n\t\t\t\tmarker-end=\"url(#diamond)\" \n\t\t\t\t/>\n\t\t</svg>"));
  38704. $(domElement.parentElement).append(svg);
  38705. var polyClipVol = new PolygonClipVolume(this.viewer.scene.getActiveCamera().clone());
  38706. this.dispatchEvent({
  38707. "type": "start_inserting_clipping_volume"
  38708. });
  38709. this.viewer.scene.addPolygonClipVolume(polyClipVol);
  38710. this.sceneMarker.add(polyClipVol);
  38711. var cancel = {
  38712. callback: null
  38713. };
  38714. var insertionCallback = e => {
  38715. if (e.button === MOUSE.LEFT) {
  38716. polyClipVol.addMarker();
  38717. // SVC Screen Line
  38718. svg.find("polyline").each((index, target) => {
  38719. var newPoint = svg[0].createSVGPoint();
  38720. newPoint.x = e.offsetX;
  38721. newPoint.y = e.offsetY;
  38722. var polyline = target.points.appendItem(newPoint);
  38723. });
  38724. if (polyClipVol.markers.length > this.maxPolygonVertices) {
  38725. cancel.callback();
  38726. }
  38727. this.viewer.inputHandler.startDragging(polyClipVol.markers[polyClipVol.markers.length - 1]);
  38728. } else if (e.button === MOUSE.RIGHT) {
  38729. cancel.callback(e);
  38730. }
  38731. };
  38732. cancel.callback = e => {
  38733. //let first = svg.find("polyline")[0].points[0];
  38734. //svg.find("polyline").each((index, target) => {
  38735. // let newPoint = svg[0].createSVGPoint();
  38736. // newPoint.x = first.x;
  38737. // newPoint.y = first.y;
  38738. // let polyline = target.points.appendItem(newPoint);
  38739. //});
  38740. svg.remove();
  38741. if (polyClipVol.markers.length > 3) {
  38742. polyClipVol.removeLastMarker();
  38743. polyClipVol.initialized = true;
  38744. } else {
  38745. this.viewer.scene.removePolygonClipVolume(polyClipVol);
  38746. }
  38747. this.viewer.renderer.domElement.removeEventListener("mouseup", insertionCallback, true);
  38748. this.viewer.removeEventListener("cancel_insertions", cancel.callback);
  38749. this.viewer.inputHandler.enabled = true;
  38750. };
  38751. this.viewer.addEventListener("cancel_insertions", cancel.callback);
  38752. this.viewer.renderer.domElement.addEventListener("mouseup", insertionCallback, true);
  38753. this.viewer.inputHandler.enabled = false;
  38754. polyClipVol.addMarker();
  38755. this.viewer.inputHandler.startDragging(polyClipVol.markers[polyClipVol.markers.length - 1]);
  38756. return polyClipVol;
  38757. }
  38758. update() {}
  38759. }
  38760. ;
  38761. var GeoTIFF = function (exports) {
  38762. 'use strict';
  38763. var Endianness = new Enum({
  38764. LITTLE: "II",
  38765. BIG: "MM"
  38766. });
  38767. var Type = new Enum({
  38768. BYTE: {
  38769. value: 1,
  38770. bytes: 1
  38771. },
  38772. ASCII: {
  38773. value: 2,
  38774. bytes: 1
  38775. },
  38776. SHORT: {
  38777. value: 3,
  38778. bytes: 2
  38779. },
  38780. LONG: {
  38781. value: 4,
  38782. bytes: 4
  38783. },
  38784. RATIONAL: {
  38785. value: 5,
  38786. bytes: 8
  38787. },
  38788. SBYTE: {
  38789. value: 6,
  38790. bytes: 1
  38791. },
  38792. UNDEFINED: {
  38793. value: 7,
  38794. bytes: 1
  38795. },
  38796. SSHORT: {
  38797. value: 8,
  38798. bytes: 2
  38799. },
  38800. SLONG: {
  38801. value: 9,
  38802. bytes: 4
  38803. },
  38804. SRATIONAL: {
  38805. value: 10,
  38806. bytes: 8
  38807. },
  38808. FLOAT: {
  38809. value: 11,
  38810. bytes: 4
  38811. },
  38812. DOUBLE: {
  38813. value: 12,
  38814. bytes: 8
  38815. }
  38816. });
  38817. var Tag = new Enum({
  38818. IMAGE_WIDTH: 256,
  38819. IMAGE_HEIGHT: 257,
  38820. BITS_PER_SAMPLE: 258,
  38821. COMPRESSION: 259,
  38822. PHOTOMETRIC_INTERPRETATION: 262,
  38823. STRIP_OFFSETS: 273,
  38824. ORIENTATION: 274,
  38825. SAMPLES_PER_PIXEL: 277,
  38826. ROWS_PER_STRIP: 278,
  38827. STRIP_BYTE_COUNTS: 279,
  38828. X_RESOLUTION: 282,
  38829. Y_RESOLUTION: 283,
  38830. PLANAR_CONFIGURATION: 284,
  38831. RESOLUTION_UNIT: 296,
  38832. SOFTWARE: 305,
  38833. COLOR_MAP: 320,
  38834. SAMPLE_FORMAT: 339,
  38835. MODEL_PIXEL_SCALE: 33550,
  38836. // [GeoTIFF] TYPE: double N: 3
  38837. MODEL_TIEPOINT: 33922,
  38838. // [GeoTIFF] TYPE: double N: 6 * NUM_TIEPOINTS
  38839. GEO_KEY_DIRECTORY: 34735,
  38840. // [GeoTIFF] TYPE: short N: >= 4
  38841. GEO_DOUBLE_PARAMS: 34736,
  38842. // [GeoTIFF] TYPE: short N: variable
  38843. GEO_ASCII_PARAMS: 34737 // [GeoTIFF] TYPE: ascii N: variable
  38844. });
  38845. var typeMapping = new Map([[Type.BYTE, Uint8Array], [Type.ASCII, Uint8Array], [Type.SHORT, Uint16Array], [Type.LONG, Uint32Array], [Type.RATIONAL, Uint32Array], [Type.SBYTE, Int8Array], [Type.UNDEFINED, Uint8Array], [Type.SSHORT, Int16Array], [Type.SLONG, Int32Array], [Type.SRATIONAL, Int32Array], [Type.FLOAT, Float32Array], [Type.DOUBLE, Float64Array]]);
  38846. class IFDEntry {
  38847. constructor(tag, type, count, offset, value) {
  38848. this.tag = tag;
  38849. this.type = type;
  38850. this.count = count;
  38851. this.offset = offset;
  38852. this.value = value;
  38853. }
  38854. }
  38855. class Image {
  38856. constructor() {
  38857. this.width = 0;
  38858. this.height = 0;
  38859. this.buffer = null;
  38860. this.metadata = [];
  38861. }
  38862. }
  38863. class Reader {
  38864. constructor() {}
  38865. static read(data) {
  38866. var endiannessTag = String.fromCharCode(...Array.from(data.slice(0, 2)));
  38867. var endianness = Endianness.fromValue(endiannessTag);
  38868. var tiffCheckTag = data.readUInt8(2);
  38869. if (tiffCheckTag !== 42) {
  38870. throw new Error("not a valid tiff file");
  38871. }
  38872. var offsetToFirstIFD = data.readUInt32LE(4);
  38873. console.log("offsetToFirstIFD", offsetToFirstIFD);
  38874. var ifds = [];
  38875. var IFDsRead = false;
  38876. var currentIFDOffset = offsetToFirstIFD;
  38877. var i = 0;
  38878. while (IFDsRead || i < 100) {
  38879. console.log("currentIFDOffset", currentIFDOffset);
  38880. var numEntries = data.readUInt16LE(currentIFDOffset);
  38881. var nextIFDOffset = data.readUInt32LE(currentIFDOffset + 2 + numEntries * 12);
  38882. console.log("next offset: ", currentIFDOffset + 2 + numEntries * 12);
  38883. var entryBuffer = data.slice(currentIFDOffset + 2, currentIFDOffset + 2 + 12 * numEntries);
  38884. for (var _i = 0; _i < numEntries; _i++) {
  38885. var tag = Tag.fromValue(entryBuffer.readUInt16LE(_i * 12));
  38886. var type = Type.fromValue(entryBuffer.readUInt16LE(_i * 12 + 2));
  38887. var count = entryBuffer.readUInt32LE(_i * 12 + 4);
  38888. var offsetOrValue = entryBuffer.readUInt32LE(_i * 12 + 8);
  38889. var valueBytes = type.bytes * count;
  38890. var value = void 0;
  38891. if (valueBytes <= 4) {
  38892. value = offsetOrValue;
  38893. } else {
  38894. var valueBuffer = new Uint8Array(valueBytes);
  38895. valueBuffer.set(data.slice(offsetOrValue, offsetOrValue + valueBytes));
  38896. var ArrayType = typeMapping.get(type);
  38897. value = new ArrayType(valueBuffer.buffer);
  38898. if (type === Type.ASCII) {
  38899. value = String.fromCharCode(...value);
  38900. }
  38901. }
  38902. var ifd = new IFDEntry(tag, type, count, offsetOrValue, value);
  38903. ifds.push(ifd);
  38904. }
  38905. console.log("nextIFDOffset", nextIFDOffset);
  38906. if (nextIFDOffset === 0) {
  38907. break;
  38908. }
  38909. currentIFDOffset = nextIFDOffset;
  38910. i++;
  38911. }
  38912. var ifdForTag = tag => {
  38913. for (var entry of ifds) {
  38914. if (entry.tag === tag) {
  38915. return entry;
  38916. }
  38917. }
  38918. return null;
  38919. };
  38920. var width = ifdForTag(Tag.IMAGE_WIDTH, ifds).value;
  38921. var height = ifdForTag(Tag.IMAGE_HEIGHT, ifds).value;
  38922. var compression = ifdForTag(Tag.COMPRESSION, ifds).value;
  38923. var rowsPerStrip = ifdForTag(Tag.ROWS_PER_STRIP, ifds).value;
  38924. var ifdStripOffsets = ifdForTag(Tag.STRIP_OFFSETS, ifds);
  38925. var ifdStripByteCounts = ifdForTag(Tag.STRIP_BYTE_COUNTS, ifds);
  38926. var numStrips = Math.ceil(height / rowsPerStrip);
  38927. var stripByteCounts = [];
  38928. for (var _i2 = 0; _i2 < ifdStripByteCounts.count; _i2++) {
  38929. var _type = ifdStripByteCounts.type;
  38930. var offset = ifdStripByteCounts.offset + _i2 * _type.bytes;
  38931. var _value = void 0;
  38932. if (_type === Type.SHORT) {
  38933. _value = data.readUInt16LE(offset);
  38934. } else if (_type === Type.LONG) {
  38935. _value = data.readUInt32LE(offset);
  38936. }
  38937. stripByteCounts.push(_value);
  38938. }
  38939. var stripOffsets = [];
  38940. for (var _i3 = 0; _i3 < ifdStripOffsets.count; _i3++) {
  38941. var _type2 = ifdStripOffsets.type;
  38942. var _offset = ifdStripOffsets.offset + _i3 * _type2.bytes;
  38943. var _value2 = void 0;
  38944. if (_type2 === Type.SHORT) {
  38945. _value2 = data.readUInt16LE(_offset);
  38946. } else if (_type2 === Type.LONG) {
  38947. _value2 = data.readUInt32LE(_offset);
  38948. }
  38949. stripOffsets.push(_value2);
  38950. }
  38951. var imageBuffer = new Uint8Array(width * height * 3);
  38952. var linesProcessed = 0;
  38953. for (var _i4 = 0; _i4 < numStrips; _i4++) {
  38954. var stripOffset = stripOffsets[_i4];
  38955. var stripBytes = stripByteCounts[_i4];
  38956. var stripData = data.slice(stripOffset, stripOffset + stripBytes);
  38957. var lineBytes = width * 3;
  38958. for (var y = 0; y < rowsPerStrip; y++) {
  38959. var line = stripData.slice(y * lineBytes, y * lineBytes + lineBytes);
  38960. imageBuffer.set(line, linesProcessed * lineBytes);
  38961. if (line.length === lineBytes) {
  38962. linesProcessed++;
  38963. } else {
  38964. break;
  38965. }
  38966. }
  38967. }
  38968. console.log("width: ".concat(width));
  38969. console.log("height: ".concat(height));
  38970. console.log("numStrips: ".concat(numStrips));
  38971. console.log("stripByteCounts", stripByteCounts.join(", "));
  38972. console.log("stripOffsets", stripOffsets.join(", "));
  38973. var image = new Image();
  38974. image.width = width;
  38975. image.height = height;
  38976. image.buffer = imageBuffer;
  38977. image.metadata = ifds;
  38978. return image;
  38979. }
  38980. }
  38981. class Exporter {
  38982. constructor() {}
  38983. static toTiffBuffer(image) {
  38984. var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  38985. var offsetToFirstIFD = 8;
  38986. var headerBuffer = new Uint8Array([0x49, 0x49, 42, 0, offsetToFirstIFD, 0, 0, 0]);
  38987. var [width, height] = [image.width, image.height];
  38988. var ifds = [new IFDEntry(Tag.IMAGE_WIDTH, Type.SHORT, 1, null, width), new IFDEntry(Tag.IMAGE_HEIGHT, Type.SHORT, 1, null, height), new IFDEntry(Tag.BITS_PER_SAMPLE, Type.SHORT, 4, null, new Uint16Array([8, 8, 8, 8])), new IFDEntry(Tag.COMPRESSION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.PHOTOMETRIC_INTERPRETATION, Type.SHORT, 1, null, 2), new IFDEntry(Tag.ORIENTATION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.SAMPLES_PER_PIXEL, Type.SHORT, 1, null, 4), new IFDEntry(Tag.ROWS_PER_STRIP, Type.LONG, 1, null, height), new IFDEntry(Tag.STRIP_BYTE_COUNTS, Type.LONG, 1, null, width * height * 3), new IFDEntry(Tag.PLANAR_CONFIGURATION, Type.SHORT, 1, null, 1), new IFDEntry(Tag.RESOLUTION_UNIT, Type.SHORT, 1, null, 1), new IFDEntry(Tag.SOFTWARE, Type.ASCII, 6, null, "......"), new IFDEntry(Tag.STRIP_OFFSETS, Type.LONG, 1, null, null), new IFDEntry(Tag.X_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1])), new IFDEntry(Tag.Y_RESOLUTION, Type.RATIONAL, 1, null, new Uint32Array([1, 1]))];
  38989. if (params.ifdEntries) {
  38990. ifds.push(...params.ifdEntries);
  38991. }
  38992. var valueOffset = offsetToFirstIFD + 2 + ifds.length * 12 + 4;
  38993. // create 12 byte buffer for each ifd and variable length buffers for ifd values
  38994. var ifdEntryBuffers = new Map();
  38995. var ifdValueBuffers = new Map();
  38996. for (var ifd of ifds) {
  38997. var entryBuffer = new ArrayBuffer(12);
  38998. var entryView = new DataView(entryBuffer);
  38999. var valueBytes = ifd.type.bytes * ifd.count;
  39000. entryView.setUint16(0, ifd.tag.value, true);
  39001. entryView.setUint16(2, ifd.type.value, true);
  39002. entryView.setUint32(4, ifd.count, true);
  39003. if (ifd.count === 1 && ifd.type.bytes <= 4) {
  39004. entryView.setUint32(8, ifd.value, true);
  39005. } else {
  39006. entryView.setUint32(8, valueOffset, true);
  39007. var valueBuffer = new Uint8Array(ifd.count * ifd.type.bytes);
  39008. if (ifd.type === Type.ASCII) {
  39009. valueBuffer.set(new Uint8Array(ifd.value.split("").map(c => c.charCodeAt(0))));
  39010. } else {
  39011. valueBuffer.set(new Uint8Array(ifd.value.buffer));
  39012. }
  39013. ifdValueBuffers.set(ifd.tag, valueBuffer);
  39014. valueOffset = valueOffset + valueBuffer.byteLength;
  39015. }
  39016. ifdEntryBuffers.set(ifd.tag, entryBuffer);
  39017. }
  39018. var imageBufferOffset = valueOffset;
  39019. new DataView(ifdEntryBuffers.get(Tag.STRIP_OFFSETS)).setUint32(8, imageBufferOffset, true);
  39020. var concatBuffers = buffers => {
  39021. var totalLength = buffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);
  39022. var merged = new Uint8Array(totalLength);
  39023. var offset = 0;
  39024. for (var buffer of buffers) {
  39025. merged.set(new Uint8Array(buffer), offset);
  39026. offset += buffer.byteLength;
  39027. }
  39028. return merged;
  39029. };
  39030. var ifdBuffer = concatBuffers([new Uint16Array([ifds.length]), ...ifdEntryBuffers.values(), new Uint32Array([0])]);
  39031. var ifdValueBuffer = concatBuffers([...ifdValueBuffers.values()]);
  39032. var tiffBuffer = concatBuffers([headerBuffer, ifdBuffer, ifdValueBuffer, image.buffer]);
  39033. return {
  39034. width: width,
  39035. height: height,
  39036. buffer: tiffBuffer
  39037. };
  39038. }
  39039. }
  39040. exports.Tag = Tag;
  39041. exports.Type = Type;
  39042. exports.IFDEntry = IFDEntry;
  39043. exports.Image = Image;
  39044. exports.Reader = Reader;
  39045. exports.Exporter = Exporter;
  39046. return exports;
  39047. }({});
  39048. class Message {
  39049. constructor(content) {
  39050. this.content = content;
  39051. var closeIcon = "".concat(exports.resourcePath, "/icons/close.svg");
  39052. this.element = $("\n\t\t\t<div class=\"potree_message\">\n\t\t\t\t<span name=\"content_container\" style=\"flex-grow: 1; padding: 5px\"></span>\n\t\t\t\t<img name=\"close\" src=\"".concat(closeIcon, "\" class=\"button-icon\" style=\"width: 16px; height: 16px;\">\n\t\t\t</div>"));
  39053. this.elClose = this.element.find("img[name=close]");
  39054. this.elContainer = this.element.find("span[name=content_container]");
  39055. if (typeof content === "string") {
  39056. this.elContainer.append($("<span>".concat(content, "</span>")));
  39057. } else {
  39058. this.elContainer.append(content);
  39059. }
  39060. }
  39061. setMessage(content) {
  39062. this.elContainer.empty();
  39063. if (typeof content === "string") {
  39064. this.elContainer.append($("<span>".concat(content, "</span>")));
  39065. } else {
  39066. this.elContainer.append(content);
  39067. }
  39068. }
  39069. }
  39070. class PointCloudSM {
  39071. constructor(potreeRenderer) {
  39072. this.potreeRenderer = potreeRenderer;
  39073. this.threeRenderer = this.potreeRenderer.threeRenderer;
  39074. this.target = new WebGLRenderTarget(2 * 1024, 2 * 1024, {
  39075. minFilter: LinearFilter,
  39076. magFilter: LinearFilter,
  39077. format: RGBAFormat,
  39078. type: FloatType
  39079. });
  39080. this.target.depthTexture = new DepthTexture();
  39081. this.target.depthTexture.type = UnsignedIntType;
  39082. //this.threeRenderer.setClearColor(0x000000, 1);
  39083. this.threeRenderer.setClearColor(0xff0000, 1);
  39084. //HACK? removed while moving to three.js 109
  39085. //this.threeRenderer.clearTarget(this.target, true, true, true);
  39086. {
  39087. var oldTarget = this.threeRenderer.getRenderTarget();
  39088. this.threeRenderer.setRenderTarget(this.target);
  39089. this.threeRenderer.clear(true, true, true);
  39090. this.threeRenderer.setRenderTarget(oldTarget);
  39091. }
  39092. }
  39093. setLight(light) {
  39094. this.light = light;
  39095. var fov = 180 * light.angle / Math.PI;
  39096. var aspect = light.shadow.mapSize.width / light.shadow.mapSize.height;
  39097. var near = 0.1;
  39098. var far = light.distance === 0 ? 10000 : light.distance;
  39099. this.camera = new PerspectiveCamera(fov, aspect, near, far);
  39100. this.camera.up.set(0, 0, 1);
  39101. this.camera.position.copy(light.position);
  39102. var target = new Vector3().subVectors(light.position, light.getWorldDirection(new Vector3()));
  39103. this.camera.lookAt(target);
  39104. this.camera.updateProjectionMatrix();
  39105. this.camera.updateMatrix();
  39106. this.camera.updateMatrixWorld();
  39107. this.camera.matrixWorldInverse.copy(this.camera.matrixWorld).invert();
  39108. }
  39109. setSize(width, height) {
  39110. if (this.target.width !== width || this.target.height !== height) {
  39111. this.target.dispose();
  39112. }
  39113. this.target.setSize(width, height);
  39114. }
  39115. render(scene, camera) {
  39116. this.threeRenderer.setClearColor(0x000000, 1);
  39117. var oldTarget = this.threeRenderer.getRenderTarget();
  39118. this.threeRenderer.setRenderTarget(this.target);
  39119. this.threeRenderer.clear(true, true, true);
  39120. this.potreeRenderer.render(scene, this.camera, this.target, {});
  39121. this.threeRenderer.setRenderTarget(oldTarget);
  39122. }
  39123. }
  39124. class Label extends EventDispatcher {
  39125. constructor() {
  39126. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  39127. super();
  39128. this.position = o.pos;
  39129. this.text = o.text || '';
  39130. this.elem = $('<div class="hide"><a></a></div>');
  39131. o.className && this.elem.addClass(o.className);
  39132. this.elem.find('a').html(this.text);
  39133. $("#potree_labels").append(this.elem);
  39134. this.pos2d = new Vector3();
  39135. this.dom = o.dom || viewer.renderArea;
  39136. this.camera = o.camera || viewer.scene.getActiveCamera();
  39137. var update = e => {
  39138. this.update(e);
  39139. };
  39140. viewer.addEventListener('camera_changed', update);
  39141. this.addEventListener('dispose', () => {
  39142. viewer.removeEventListener('camera_changed', update);
  39143. this.dispose();
  39144. });
  39145. }
  39146. update() {
  39147. if (!this.position || this.elem.hasClass('unvisible')) return;
  39148. var p = Utils.getPos2d(this.position, viewer.mainViewport, this.dom);
  39149. if (!p.trueSide) {
  39150. this.elem.addClass("hide");
  39151. return;
  39152. }
  39153. this.elem.css({
  39154. left: p.pos.x + 'px',
  39155. top: p.pos.y + 'px'
  39156. });
  39157. this.elem.removeClass("hide");
  39158. this.pos2d = p.vector;
  39159. }
  39160. setVisible(visi) {
  39161. if (!visi) {
  39162. this.elem.addClass("unvisible");
  39163. } else {
  39164. this.elem.removeClass("unvisible");
  39165. this.update();
  39166. }
  39167. }
  39168. setText(text) {
  39169. this.text = text || '';
  39170. this.elem.find('a').html(this.text);
  39171. }
  39172. setPos(pos) {
  39173. this.position = pos;
  39174. }
  39175. dispose() {
  39176. this.elem.remove();
  39177. this.removeAllListeners();
  39178. }
  39179. }
  39180. //THREE.Vector2.name1 = 'ctrlPolygon'
  39181. var verticalLine = new Line3();
  39182. //控制点和边的合集。具有可以拖拽修改的功能,拖拽时能防止线相交。
  39183. class ctrlPolygon extends Object3D {
  39184. constructor(type, prop) {
  39185. super();
  39186. this.type = type;
  39187. this.maxMarkers = Number.MAX_SAFE_INTEGER;
  39188. this.transformData(prop);
  39189. for (var i in prop) {
  39190. this[i] = prop[i];
  39191. }
  39192. if ((this.atPlane || this.showArea) && this.closed && this.dimension == '2d') {
  39193. this.areaPlane = this.createAreaPlane();
  39194. this.add(this.areaPlane);
  39195. }
  39196. //数据--刚开始一定是空的
  39197. this.points = [];
  39198. //mesh 不一定有
  39199. this.markers = [];
  39200. this.edges = [];
  39201. this.center;
  39202. }
  39203. initData(prop) {
  39204. //开始加数据
  39205. prop.dataset_points && (this.dataset_points = prop.dataset_points);
  39206. prop.datasetId && (this.datasetId = prop.datasetId);
  39207. prop.points_datasets && (this.points_datasets = prop.points_datasets);
  39208. if (Potree.settings.editType == 'merge' || this.measureType == 'MulDistance Ring') {
  39209. //融合页面没有地图,measure的不需要指定datasetId,每个点都有各自的datasetId,跟着各自的模型走
  39210. if (this.dataset_points) {
  39211. this.dataset_points = this.dataset_points.map(e => {
  39212. return e && new Vector3().copy(e);
  39213. });
  39214. prop.points = this.dataset_points.map((p, i) => {
  39215. return Potree.Utils.datasetPosTransform({
  39216. fromDataset: true,
  39217. datasetId: this.points_datasets[i],
  39218. position: p
  39219. });
  39220. });
  39221. if (prop.points.some(e => e == void 0)) {
  39222. return false;
  39223. }
  39224. } else {
  39225. this.dataset_points = [];
  39226. }
  39227. }
  39228. if (prop.points) {
  39229. for (var p of prop.points) {
  39230. var pos = new Vector3().copy(p);
  39231. this.addMarker({
  39232. point: pos
  39233. });
  39234. }
  39235. if (Potree.settings.editType != 'merge' && this.measureType != 'MulDistance Ring') {
  39236. if (this.datasetId != void 0) {
  39237. //初始化位置
  39238. if (this.dataset_points) {
  39239. this.dataset_points = this.dataset_points.map(e => {
  39240. return e && new Vector3().copy(e);
  39241. });
  39242. this.transformByPointcloud(); //根据dataset_points和this.datasetId生成points
  39243. }
  39244. } else {
  39245. if (prop.dataset_points && prop.dataset_points.some(e => e != void 0)) {
  39246. console.error('存在测量线的datasetId为空而dataset_points有值,请检查并删除:' + this.sid); //存在过的bug,原因未知,可能是后台处理dataset时替换的错误:http://192.168.0.21/index.php?m=bug&f=view&bugID=23601
  39247. console.log(this);
  39248. }
  39249. }
  39250. }
  39251. this.facePlane = this.getFacePlane();
  39252. this.getPoint2dInfo(this.points);
  39253. this.update({
  39254. ifUpdateMarkers: true
  39255. });
  39256. //this.dragChange(new THREE.Vector3().copy(prop.points[prop.points.length-1]), prop.points.length-1);
  39257. this.setSelected(false);
  39258. this.markers.forEach(marker => {
  39259. marker.dispatchEvent('addHoverEvent');
  39260. });
  39261. return true;
  39262. }
  39263. }
  39264. addMarker() {
  39265. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  39266. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  39267. this.points = [...this.points.slice(0, index), o.point.clone(), ...this.points.slice(index, this.points.length)];
  39268. //this.points.push(o.point);
  39269. if ('dataset_point' in o) {
  39270. //需要增加,可能是null
  39271. this.dataset_points = this.dataset_points ? [...this.dataset_points.slice(0, index), o.dataset_point && o.dataset_point.clone(), ...this.dataset_points.slice(index, this.dataset_points.length)] : null; //如果原本是null,新加的应该也是
  39272. }
  39273. if ('points_dataset' in o) {
  39274. this.points_datasets = [...this.points_datasets.slice(0, index), o.points_dataset, ...this.points_datasets.slice(index, this.points_datasets.length)];
  39275. }
  39276. if (o.marker) {
  39277. this.add(o.marker);
  39278. this.markers = [...this.markers.slice(0, index), o.marker, ...this.markers.slice(index, this.markers.length)];
  39279. this.updateMarker(o.marker, o.point);
  39280. o.marker.addEventListener('drag', this.dragMarker.bind(this), {
  39281. importance: 2
  39282. });
  39283. o.marker.addEventListener('drop', this.dropMarker.bind(this), {
  39284. importance: 2
  39285. });
  39286. o.marker.createTime = Date.now();
  39287. var addHoverEvent = e => {
  39288. var mouseover = e => {
  39289. this.setMarkerSelected(e.object, 'hover', 'single');
  39290. viewer.dispatchEvent({
  39291. type: "CursorChange",
  39292. action: "add",
  39293. name: "markerMove"
  39294. });
  39295. };
  39296. var mouseleave = e => {
  39297. this.setMarkerSelected(e.object, 'unhover', 'single');
  39298. viewer.dispatchEvent({
  39299. type: "CursorChange",
  39300. action: "remove",
  39301. name: "markerMove"
  39302. });
  39303. };
  39304. o.marker.addEventListener('mouseover', mouseover);
  39305. o.marker.addEventListener('mouseleave', mouseleave);
  39306. o.marker.addEventListener('startDragging', e => {
  39307. //for mobile
  39308. this.setMarkerSelected(o.marker, 'hover', 'single');
  39309. this.dispatchEvent('startDragging');
  39310. });
  39311. o.marker.addEventListener('drop', e => {
  39312. //for mobile
  39313. this.setMarkerSelected(o.marker, 'unhover', 'single');
  39314. });
  39315. o.marker.removeEventListener('addHoverEvent', addHoverEvent);
  39316. };
  39317. o.marker.addEventListener('addHoverEvent', addHoverEvent); //当非isNew时才添加事件
  39318. if (!this.isNew) {
  39319. o.marker.dispatchEvent('addHoverEvent');
  39320. }
  39321. }
  39322. if (o.edge) {
  39323. this.add(o.edge);
  39324. this.edges = [...this.edges.slice(0, index), o.edge, ...this.edges.slice(index, this.edges.length)];
  39325. }
  39326. }
  39327. dragMarker(e) {
  39328. var I, atMap;
  39329. if (e.hoverViewport != e.drag.dragViewport) {
  39330. //不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  39331. viewer.dispatchEvent({
  39332. type: "CursorChange",
  39333. action: "add",
  39334. name: "polygon_AtWrongPlace"
  39335. });
  39336. return;
  39337. }
  39338. if (e.drag.pointerDelta.length() == 0 && !this.isNew) {
  39339. //部分设备(华为matePad11)在touchstart后立即执行了touchmove,导致marker立即移动,需要屏蔽..(刚创建时也会是0)
  39340. return;
  39341. }
  39342. viewer.dispatchEvent({
  39343. type: "CursorChange",
  39344. action: "remove",
  39345. name: "polygon_AtWrongPlace"
  39346. });
  39347. atMap = e.drag.dragViewport.name == 'mapViewport';
  39348. if (atMap && this.unableDragAtMap) {
  39349. e.drag.object = null; //取消拖拽
  39350. return;
  39351. }
  39352. e.drag.object.isDragging = true;
  39353. I = e.intersect && (e.intersect.adsorption ? e.intersect.location : e.intersect.orthoIntersect || e.intersect.location);
  39354. if (viewer.inputHandler.pressedKeys[18] || Potree.settings.dragPolyBeyondPoint && !I) {
  39355. //alt dragPolyBeyondPoint可以平移拖拽到无点的地方---测试用
  39356. var i = this.markers.indexOf(e.drag.object);
  39357. I = this.points[i].clone();
  39358. var projected = I.clone().project(e.drag.dragViewport.camera);
  39359. projected.x = e.pointer.x;
  39360. projected.y = e.pointer.y;
  39361. var unprojected = projected.clone().unproject(e.drag.dragViewport.camera);
  39362. I.copy(unprojected);
  39363. }
  39364. if (I) {
  39365. var _i = this.markers.indexOf(e.drag.object);
  39366. if (_i !== -1) {
  39367. this.dragChange(I.clone(), _i, atMap);
  39368. if (this.points_datasets) {
  39369. if (e.intersect) {
  39370. if (e.intersect.pointcloud) this.points_datasets[_i] = e.intersect.pointcloud.dataset_id;else if (e.intersect.object) this.points_datasets[_i] = e.intersect.object.dataset_id;else {
  39371. //地图
  39372. if (this.measureType == 'MulDistance Ring') {
  39373. //因为它的每个point跟着各自的dataset走,而不是整体的dataset
  39374. var pointcloud = viewer.findClosestDatasetOnMap(I) || viewer.scene.pointclouds[0];
  39375. this.points_datasets[_i] = pointcloud.dataset_id;
  39376. } else this.points_datasets[_i] = null;
  39377. }
  39378. }
  39379. }
  39380. }
  39381. this.editStateChange(true);
  39382. return true;
  39383. }
  39384. }
  39385. dragChange(intersectPos, i, atMap) {
  39386. var len = this.markers.length;
  39387. var oldPoint = this.points[i];
  39388. if (atMap) {
  39389. intersectPos.setZ(oldPoint.z); //在地图上拖拽,不改变其高度。
  39390. }
  39391. var location = intersectPos.clone();
  39392. if (this.faceDirection && this.maxMarkers == 2 && len == 2) {
  39393. //add 固定方向的点不直接拖拽
  39394. var p1 = this.markers[0].position;
  39395. if (this.faceDirection == 'horizontal') {
  39396. var projectPos = location.clone().setZ(p1.z);
  39397. } else {
  39398. var projectPos = p1.clone().setZ(location.z);
  39399. }
  39400. //var p2 = p1.clone().add(this.direction)
  39401. //var projectPos = math.getFootPoint(location, p1, p2)
  39402. LineDraw.updateLine(this.guideLine, [location, projectPos]);
  39403. location = projectPos;
  39404. this.guideLine.visible = true;
  39405. } else if (len > 1) {
  39406. var points = this.points.map(e => e.clone());
  39407. points[i].copy(location); //算normal需要提前确认point
  39408. //若为定义了面朝向的矩形
  39409. if (this.faceDirection == 'horizontal') {
  39410. if (len == 2) {
  39411. location.setZ(points[0].z);
  39412. }
  39413. if (!this.facePlane) {
  39414. //一个点就能确定面
  39415. this.facePlane = new Plane().setFromNormalAndCoplanarPoint(new Vector3(0, 0, 1), this.points[0]);
  39416. }
  39417. } else if (this.faceDirection == 'vertical') {
  39418. //当有两个点时, 有两个方向的可能
  39419. if (len == 2) {
  39420. if (this.isRect) {
  39421. var _vec = points[0].clone().sub(location);
  39422. if (Math.sqrt(_vec.x * _vec.x + _vec.y * _vec.y) > Math.abs(_vec.z)) {
  39423. //水平(高度差小于水平距离时)
  39424. location.setZ(points[0].z);
  39425. //this.cannotConfirmNormal = false;//能确定面为水平方向
  39426. } else {
  39427. //垂直 (当两点一样时也属于这种)
  39428. location.setX(points[0].x);
  39429. location.setY(points[0].y);
  39430. //this.cannotConfirmNormal = true; //不能确定面,因第三点可绕着纵轴线自由移动
  39431. }
  39432. }
  39433. } else {
  39434. {
  39435. //判断cannotConfirmNormal. 如果前几段都在竖直线上,就不能固定出面方向。
  39436. this.cannotConfirmNormal = true;
  39437. var max = this.isRect ? 1 : len - 2;
  39438. for (var _i2 = 0; _i2 < max; _i2++) {
  39439. var _p = points[_i2].clone();
  39440. var _p2 = points[_i2 + 1].clone();
  39441. var _vec2 = _p.sub(_p2);
  39442. if (_vec2.x != 0 || _vec2.y != 0) {
  39443. this.cannotConfirmNormal = false;
  39444. break;
  39445. }
  39446. }
  39447. }
  39448. if (!this.facePlane || this.cannotConfirmNormal) {
  39449. //三个点且为水平方向时,计算面
  39450. var points_ = points.map(e => new Vector2(e.x, e.y));
  39451. var points2 = getDifferentPoint(points_, 2);
  39452. if (points2) {
  39453. var normal = math.getNormal2d({
  39454. p1: points2[0],
  39455. p2: points2[1]
  39456. });
  39457. normal = new Vector3(normal.x, normal.y, 0);
  39458. this.facePlane = new Plane().setFromNormalAndCoplanarPoint(normal, this.points[0]);
  39459. }
  39460. }
  39461. }
  39462. }
  39463. if (len > 2) {
  39464. if (!this.faceDirection && this.showArea) {
  39465. if (len == 3 || this.isRect) this.cannotConfirmNormal = true; //当第三个点固定后(有四个点时)才能固定面
  39466. if (!this.facePlane || this.cannotConfirmNormal) {
  39467. var points3 = getDifferentPoint(points, 3); //只有找到三个不同的点算拥有面和area
  39468. if (points3) {
  39469. this.facePlane = new Plane().setFromCoplanarPoints(...points3);
  39470. }
  39471. }
  39472. }
  39473. if (this.atPlane && this.facePlane && !this.cannotConfirmNormal) {
  39474. //之后加的点一定要在面上
  39475. if (atMap) {
  39476. //地图上用垂直线,得到和面的交点。
  39477. verticalLine.set(location.clone().setZ(100000), location.clone().setZ(-100000)); //确保长度范围覆盖所有测量面
  39478. location = this.facePlane.intersectLine(verticalLine, new Vector3());
  39479. if (!location) return;
  39480. } else {
  39481. location = this.facePlane.projectPoint(intersectPos, new Vector3());
  39482. }
  39483. }
  39484. points[i].copy(location); //再copy确认一次
  39485. if (len == 3 && this.faceDirection == 'horizontal' && this.closed) {
  39486. //normal方向还不确定 会影响label在里侧还是外侧
  39487. var facePlane = new Plane().setFromCoplanarPoints(...points);
  39488. if (facePlane.normal.z && facePlane.normal.z * this.facePlane.normal.z < 0) {
  39489. this.facePlane.normal.z *= -1, this.facePlane.constant *= -1;
  39490. //console.log(this.facePlane.normal, this.facePlane.constant)
  39491. }
  39492. }
  39493. if (this.isRect) {
  39494. //是矩形 (即使没有faceDirection也能执行)
  39495. //根据前两个点计算当前和下一个点
  39496. var p1 = points[(i - 2 + len) % len];
  39497. var p2 = points[(i - 1 + len) % len];
  39498. if (p1.equals(p2)) {
  39499. //意外情况:重复点两次 ( bug点,改了好多遍)
  39500. if (this.faceDirection == 'vertical') {
  39501. p2.add(new Vector3(0, 0, 0.0001));
  39502. } else {
  39503. p2.add(new Vector3(0, 0.0001, 0));
  39504. }
  39505. }
  39506. //p3 : location
  39507. var foot = math.getFootPoint(location, p1, p2); //p2 修改p2到垂足的位置
  39508. var vec = foot.clone().sub(location);
  39509. var p4 = p1.clone().sub(vec);
  39510. points[(i - 1 + len) % len].copy(foot);
  39511. points[(i + 1) % len].copy(p4);
  39512. this.setPosition((i - 1 + len) % len, foot); //p2
  39513. this.setPosition((i + 1) % len, p4);
  39514. }
  39515. this.getPoint2dInfo(points);
  39516. var isIntersectSelf = this.atPlane && this.closed && !this.isRect && this.point2dInfo && this.intersectSelf(this.point2dInfo.points2d); //检测相交
  39517. this.isIntersectSelf = isIntersectSelf;
  39518. if (isIntersectSelf) {
  39519. //not-allowed
  39520. if (!this.isNew && isIntersectSelf == 'lastLine') this.isIntersectSelf = 'all'; //已经画好了就不用特别对待最后一条线
  39521. if (this.isIntersectSelf == 'lastLine') {
  39522. Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', false);
  39523. Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', false);
  39524. } else {
  39525. viewer.dispatchEvent({
  39526. type: "CursorChange",
  39527. action: "add",
  39528. name: "polygon_isIntersectSelf"
  39529. });
  39530. return;
  39531. }
  39532. }
  39533. if (!this.isIntersectSelf) {
  39534. this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true);
  39535. this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true);
  39536. }
  39537. if (!this.isIntersectSelf || this.isIntersectSelf == 'lastLine') {
  39538. viewer.dispatchEvent({
  39539. type: "CursorChange",
  39540. action: "remove",
  39541. name: "polygon_isIntersectSelf"
  39542. });
  39543. }
  39544. }
  39545. var showGuideLine = len > 1 && (this.faceDirection || len > 3);
  39546. if (showGuideLine && this.guideLine) {
  39547. LineDraw.updateLine(this.guideLine, [intersectPos, location]);
  39548. this.guideLine.visible = true;
  39549. }
  39550. //console.log(this.points.map(e=>e.toArray()))
  39551. }
  39552. if (this.restrictArea) {
  39553. var holes = this.restrictArea.holes.concat(this.restrictArea.parentHoles);
  39554. var holesPoints = holes.filter(e => e != this && e.points.length > 2).map(e => e.points);
  39555. if (!math.isPointInArea(this.restrictArea.points, holesPoints, location)) {
  39556. viewer.dispatchEvent({
  39557. type: "CursorChange",
  39558. action: "add",
  39559. name: "polygon_AtWrongPlace"
  39560. });
  39561. this.isAtWrongPlace = true;
  39562. return;
  39563. }
  39564. //就不处理相交线了。 有个缺点:floor上的hole可以限制room,但hole不受room限制,会导致room的marker被框在hole里而动不了。只能去调整hole了
  39565. }
  39566. viewer.dispatchEvent({
  39567. type: "CursorChange",
  39568. action: "remove",
  39569. name: "polygon_AtWrongPlace"
  39570. });
  39571. this.isAtWrongPlace = false;
  39572. this.setPosition(i, location);
  39573. this.update({
  39574. index: this.isRect ? null : i
  39575. });
  39576. this.dispatchEvent({
  39577. type: 'dragChange',
  39578. index: i
  39579. });
  39580. }
  39581. dropMarker(e) {
  39582. //console.log('dropMarker')
  39583. if (this.isNew && e.pressDistance > Potree.config.clickMaxDragDis) {
  39584. //拖拽的话返回
  39585. return this.continueDrag(null, e);
  39586. }
  39587. if (e.hoverViewport != e.drag.dragViewport) {
  39588. //copy from dragMarker, for sitemodel, only mapViewport can be dropped
  39589. return this.continueDrag(null, e);
  39590. }
  39591. if (e.isTouch) {
  39592. if (e.hoverViewport != viewer.mainViewport && this.unableDragAtMap) {
  39593. viewer.dispatchEvent({
  39594. type: 'reticule_forbit',
  39595. v: true
  39596. });
  39597. //console.log('reticule_forbit',true)
  39598. return this.continueDrag(null, e);
  39599. } else {
  39600. viewer.dispatchEvent({
  39601. type: 'reticule_forbit',
  39602. v: false
  39603. });
  39604. //console.log('reticule_forbit',false)
  39605. }
  39606. this.isNew && this.dragMarker(e); //isNew触屏点击时必须先更新下点,因为指尖不在屏幕上时没更新。但对已经创建的marker点击时不应该更新
  39607. }
  39608. if (e.button != MOUSE.RIGHT && (
  39609. //右键click的话继续执行,因为会停止
  39610. this.isIntersectSelf == 'all' && this.isNew //有线相交了
  39611. || this.isAtWrongPlace && this.isNew || !e.isAtDomElement && this.isNew //如果是刚添加时在其他dom点击, 不要响应
  39612. || e.hoverViewport != viewer.mainViewport && this.unableDragAtMap //垂直的测量线不允许在地图上放点
  39613. || this.isNew && !getDifferentPoint(this.points, this.points.length) //不允许和之前的点相同, 但这句在点云稀疏时会导致难结束
  39614. )) {
  39615. return this.continueDrag(null, e);
  39616. }
  39617. //console.log('drop marker' )
  39618. var i = this.markers.indexOf(e.drag.object);
  39619. if (i !== -1) {
  39620. this.dispatchEvent({
  39621. 'type': 'marker_dropped',
  39622. 'index': i
  39623. });
  39624. if (this.markers.length > 2 && this.facePlane) this.cannotConfirmNormal = false;
  39625. this.guideLine && (this.guideLine.visible = false);
  39626. }
  39627. this.setMarkerSelected(e.drag.object, 'unhover', 'single');
  39628. this.editStateChange(false);
  39629. e.drag.endDragFun && e.drag.endDragFun(e); // addmarker
  39630. //if(this.changeCallBack)this.changeCallBack()
  39631. return true;
  39632. }
  39633. getFacePlane() {
  39634. //最普通一种get方法,根据顶点。且假设所有点已经共面,且不重合
  39635. if ( /* !this.atPlane || */this.points.length < 3) return;
  39636. /* this.facePlane = new THREE.Plane().setFromCoplanarPoints(...this.points.slice(0,3) ) */
  39637. var facePlane = this.facePlane;
  39638. if (!this.atPlane || !facePlane) {
  39639. //多折线 没有实时更新facePlane所以重新算
  39640. var normal = new Vector3(),
  39641. len = this.points.length - 2;
  39642. for (var i = 0; i < len; i++) {
  39643. //获取normal的顺序方法必须和setFromCoplanarPoints一致
  39644. var vec0 = new Vector3().subVectors(this.points[i + 2], this.points[i + 1]);
  39645. var vec1 = new Vector3().subVectors(this.points[i], this.points[i + 1]);
  39646. var nor = vec0.cross(vec1).normalize();
  39647. normal.add(nor);
  39648. }
  39649. normal.normalize();
  39650. facePlane = new Plane().setFromNormalAndCoplanarPoint(normal, this.points[0]);
  39651. }
  39652. return facePlane;
  39653. }
  39654. getPoint2dInfo(points) {
  39655. //在更新areaplane之前必须更新过point2dInfo (针对所有点在同一平面上的)
  39656. if (this.facePlane && (this.atPlane || Potree.settings.areaAtNotPlane)) {
  39657. var facePlane = this.getFacePlane();
  39658. var originPoint0 = points[0].clone();
  39659. var qua = math.getQuaBetween2Vector(facePlane.normal, new Vector3(0, 0, 1), new Vector3(0, 0, 1));
  39660. var points2d = points.map(e => e.clone().applyQuaternion(qua));
  39661. this.point2dInfo = {
  39662. originPoint0,
  39663. points2d,
  39664. quaInverse: qua.clone().invert()
  39665. };
  39666. }
  39667. }
  39668. setPosition(index, position) {
  39669. //拖拽后设置位置
  39670. var point = this.points[index];
  39671. point.copy(position);
  39672. /* if(this.datasetId){
  39673. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true, datasetId:this.datasetId, position:point.clone()})
  39674. } */
  39675. /* if(Potree.settings.editType == 'merge'){
  39676. this.dataset_points[index] = Potree.Utils.datasetPosTransform({toDataset:true,this.points_datasets[i], position:point.clone()})
  39677. } */
  39678. var marker = this.markers[index];
  39679. this.updateMarker(marker, point);
  39680. }
  39681. updateMarker(marker, pos) {
  39682. marker.position.copy(pos);
  39683. marker.waitUpdate();
  39684. }
  39685. intersectSelf(points2d) {
  39686. //add
  39687. var len = points2d.length;
  39688. for (var i = 0; i < len; i++) {
  39689. for (var j = i + 2; j < len; j++) {
  39690. if (Math.abs(j - len - i) < 2) continue; //不和邻边比
  39691. var p1 = points2d[i];
  39692. var p2 = points2d[i + 1];
  39693. var p3 = points2d[j];
  39694. var p4 = points2d[(j + 1) % len];
  39695. if (p1.equals(p2) || p3.equals(p4) || p1.equals(p3) || p2.equals(p3) || p1.equals(p4) || p2.equals(p4)) continue;
  39696. var line1 = [p1, p2];
  39697. var line2 = [p3, p4];
  39698. var intersect = math.isLineIntersect(line1, line2, false, 0.001);
  39699. if (intersect) {
  39700. if (i == len - 1 || j == len - 1) {
  39701. //最后一条线。如果还没绘制完,最后的线还没定下,可被允许继续绘制,但无法显示面积。
  39702. return 'lastLine';
  39703. } else {
  39704. return 'all';
  39705. }
  39706. break;
  39707. }
  39708. }
  39709. }
  39710. }
  39711. removeMarker(index) {
  39712. this.points.splice(index, 1);
  39713. var marker = this.markers[index];
  39714. //this.remove(marker);
  39715. this.markers.splice(index, 1);
  39716. marker.dispose();
  39717. var edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  39718. var edge = this.edges[edgeIndex];
  39719. if (edge) {
  39720. this.remove(edge);
  39721. this.edges.splice(edgeIndex, 1);
  39722. edge.geometry.dispose();
  39723. }
  39724. this.point2dInfo && this.point2dInfo.points2d.splice(index, 1); //add
  39725. this.dispatchEvent({
  39726. type: 'removeMarker',
  39727. index,
  39728. marker
  39729. });
  39730. }
  39731. createAreaPlane(mat) {
  39732. var geometry = new Geometry();
  39733. var mesh = new Mesh(geometry, mat);
  39734. return mesh;
  39735. }
  39736. updateAreaPlane() {
  39737. this.areaPlane.geometry.dispose();
  39738. if (this.points.length > 2) {
  39739. if (this.isPrism) {
  39740. var z = this.horizonZ || 0;
  39741. var points2d = this.points.map(e => e.clone().setZ(z));
  39742. this.areaPlane.geometry = MeshDraw.getShapeGeo(points2d); //z=0
  39743. var center = math.getCenterOfGravityPoint(points2d); //重心
  39744. this.areaPlaneCenter = new Vector3(center.x, center.y, z);
  39745. this.areaPlane.position.z = z;
  39746. } else if (this.point2dInfo) {
  39747. if (Potree.settings.areaAtNotPlane) {
  39748. //测点不在同一平面的面积. (缺点:容易出现三角缺块, 以及搭错线导致超出理想边界外。在平面上n个点能构成n-2个三角形,但空间中更多个,所以若要指定出类似平面那样n-2个三角形是有多种可能的。故暂不开放。 用d3.Delaunay结果更差) //测试桥面 SG-arqnGgAR7om&formal
  39749. //参考 http://indoor.popsmart.cn:8084/sxswsw-sx/ 找到场景中面积测量线的方法:window.scene.children[18].children[0].material.color.r = 1
  39750. var geometry = new Geometry();
  39751. var faceArray = [],
  39752. triangles = ShapeUtils.triangulateShape(this.point2dInfo.points2d, []); //因为它只关注xy平面,垂直画就容易错,所以用转到平面的points2d来识别三角。
  39753. if (triangles.length == 0) return;
  39754. this._area = 0;
  39755. for (var i = 0; i < triangles.length; i++) {
  39756. faceArray[i] = new Face3(triangles[i][0], triangles[i][1], triangles[i][2]);
  39757. var nor = new Vector3().crossVectors(new Vector3().subVectors(this.points[triangles[i][0]], this.points[triangles[i][2]]), new Vector3().subVectors(this.points[triangles[i][1]], this.points[triangles[i][2]]));
  39758. this._area += nor.length() / 2;
  39759. nor.normalize();
  39760. faceArray[i].normal.copy(nor);
  39761. }
  39762. geometry.vertices = this.points;
  39763. geometry.faces = faceArray;
  39764. this.areaPlane.geometry = new BufferGeometry().fromGeometry(geometry); //不知道为何不转为bufferGeometry显示不出
  39765. //this.center
  39766. //参考getFacePlane 在这里建立_normal?
  39767. } else {
  39768. //if(this.point2dInfo){//旧的。 之前的规定点要在同一平面
  39769. this.areaPlane.geometry = MeshDraw.getShapeGeo(this.point2dInfo.points2d);
  39770. var _center = math.getCenterOfGravityPoint(this.point2dInfo.points2d); //重心
  39771. var firstPos = this.point2dInfo.points2d[0].clone();
  39772. firstPos.z = 0; //因为shape只读取了xy,所以位移下, 再算出最终位置,得到差距
  39773. firstPos.applyQuaternion(this.point2dInfo.quaInverse);
  39774. var vec = this.point2dInfo.originPoint0.clone().sub(firstPos);
  39775. _center = new Vector3(_center.x, _center.y, 0);
  39776. _center.applyQuaternion(this.point2dInfo.quaInverse);
  39777. this.areaPlane.quaternion.copy(this.point2dInfo.quaInverse);
  39778. this.areaPlane.position.copy(vec);
  39779. _center.add(vec);
  39780. this.center = _center;
  39781. //}
  39782. }
  39783. }
  39784. } else {
  39785. this.areaPlane.geometry = new Geometry();
  39786. }
  39787. }
  39788. getIndex(index, add) {
  39789. var lastIndex = this.points.length - 1;
  39790. if (add == -1) return index === 0 ? lastIndex : index - 1;else if (add == 1) return index + 1 > lastIndex ? 0 : index + 1;
  39791. }
  39792. update() {
  39793. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  39794. if (this.points.length === 0) {
  39795. return;
  39796. }
  39797. //performance.mark('measureUpdate-start')
  39798. var lastIndex = this.points.length - 1;
  39799. if (options.index != void 0) {
  39800. //更新第几个点
  39801. this.updateMarker(this.markers[options.index], this.points[options.index]);
  39802. var previousIndex = this.getIndex(options.index, -1);
  39803. var nextIndex = this.getIndex(options.index, +1);
  39804. if (this.closed || nextIndex != 0) LineDraw.updateLine(this.edges[options.index], [this.points[options.index], this.points[nextIndex]]);
  39805. if (this.closed || previousIndex != lastIndex) LineDraw.updateLine(this.edges[previousIndex], [this.points[options.index], this.points[previousIndex]]);
  39806. } else {
  39807. for (var index = 0; index <= lastIndex; index++) {
  39808. var _nextIndex = this.getIndex(index, +1);
  39809. var _previousIndex = this.getIndex(index, -1);
  39810. var point = this.points[index];
  39811. var nextPoint = this.points[_nextIndex];
  39812. var previousPoint = this.points[_previousIndex];
  39813. if (options.ifUpdateMarkers) {
  39814. this.updateMarker(this.markers[index], point);
  39815. }
  39816. if (!this.closed && _nextIndex == 0) break; //add
  39817. {
  39818. var edge = this.edges[index];
  39819. if (edge) {
  39820. LineDraw.updateLine(edge, [point, nextPoint]);
  39821. }
  39822. }
  39823. }
  39824. }
  39825. if (this.areaPlane) {
  39826. this.updateAreaPlane();
  39827. }
  39828. //this.dispatchEvent({type:'update'})
  39829. viewer.dispatchEvent('content_changed');
  39830. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed'); //暂时先这么都通知
  39831. //performance.mark('measureUpdate-end')
  39832. //let measure = performance.measure('measure-','measureUpdate-start', 'measureUpdate-end' );
  39833. //console.log('update-time', measure.duration)
  39834. }
  39835. createPrismLines(color) {
  39836. this.lineMesh = LineDraw.createLine([], {
  39837. color
  39838. });
  39839. this.lineMesh.name = 'PrismLines';
  39840. this.add(this.lineMesh);
  39841. }
  39842. updatePrismLines() {
  39843. if (!this.lineMesh) return;
  39844. var positions = [];
  39845. var length = this.points.length;
  39846. this.points.forEach((point, index) => {
  39847. //竖线:
  39848. positions.push(point.clone().setZ(this.zMin), point.clone().setZ(this.zMax));
  39849. //横线
  39850. var nextPoint = this.points[(index + 1) % length];
  39851. if (!nextPoint) return; //when length==1
  39852. positions.push(point.clone().setZ(this.zMax), nextPoint.clone().setZ(this.zMax)); //上横线
  39853. positions.push(point.clone().setZ(this.zMin), nextPoint.clone().setZ(this.zMin)); //下横线
  39854. });
  39855. LineDraw.moveLine(this.lineMesh, positions);
  39856. viewer.dispatchEvent('content_changed');
  39857. }
  39858. dispose() {
  39859. //add
  39860. this.parent.remove(this);
  39861. this.markers.forEach(e => e.dispose());
  39862. this.edges.forEach(e => e.geometry.dispose());
  39863. }
  39864. reDraw() {
  39865. var restMarkerCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  39866. //重新开始画
  39867. var pointCount = this.points.length - restMarkerCount; // restMarkerCount为需要留下的marker数量
  39868. while (pointCount > 0) {
  39869. this.removeMarker(--pointCount);
  39870. }
  39871. this.point2dInfo = null;
  39872. this.facePlane = null;
  39873. }
  39874. setMarkerSelected() {}
  39875. editStateChange(state) {
  39876. if (!state) {
  39877. viewer.dispatchEvent({
  39878. type: "CursorChange",
  39879. action: "remove",
  39880. name: "polygon_isIntersectSelf"
  39881. });
  39882. viewer.dispatchEvent({
  39883. type: "CursorChange",
  39884. action: "remove",
  39885. name: "polygon_AtWrongPlace"
  39886. });
  39887. viewer.dispatchEvent({
  39888. type: 'reticule_forbit',
  39889. v: false
  39890. });
  39891. this.markers.forEach(e => e.isDragging = false);
  39892. }
  39893. }
  39894. transformData(prop) {
  39895. var pick = (defaul, alternative) => {
  39896. if (defaul != null) {
  39897. return defaul;
  39898. } else {
  39899. return alternative;
  39900. }
  39901. };
  39902. prop.showDistances = prop.showDistances === null ? true : prop.showDistances;
  39903. prop.showArea = pick(prop.showArea, false);
  39904. prop.showAngles = pick(prop.showAngles, false);
  39905. prop.showCoordinates = pick(prop.showCoordinates, false);
  39906. prop.showHeight = pick(prop.showHeight, false);
  39907. prop.showCircle = pick(prop.showCircle, false);
  39908. prop.showAzimuth = pick(prop.showAzimuth, false);
  39909. prop.showEdges = pick(prop.showEdges, true);
  39910. prop.closed = pick(prop.closed, false);
  39911. prop.maxMarkers = pick(prop.maxMarkers, Infinity);
  39912. prop.direction = prop.direction; //add
  39913. prop.type = prop.type;
  39914. prop.showGuideLine = pick(prop.showGuideLine, false);
  39915. prop.isRect = pick(prop.isRect, false);
  39916. }
  39917. setSelected() {}
  39918. continueDrag(marker, e) {
  39919. var object = marker || e.drag.object;
  39920. object.isDragging = true;
  39921. this.editStateChange(true);
  39922. var timer = setTimeout(() => {
  39923. //等 drag=null之后 //右键拖拽结束后需要重新得到drag
  39924. if (this.parent && object.parent && object.isDragging) {
  39925. //console.log('continueDrag')
  39926. viewer.inputHandler.startDragging(object, {
  39927. endDragFun: e.drag.endDragFun,
  39928. notPressMouse: e.drag.notPressMouse,
  39929. dragViewport: e.drag.dragViewport
  39930. });
  39931. }
  39932. }, 1);
  39933. return timer;
  39934. }
  39935. }
  39936. function getDifferentPoint(points, count) {
  39937. //for facePlane
  39938. var result = [];
  39939. for (var i = 0; i < points.length; i++) {
  39940. var p = points[i];
  39941. if (result.find(e => e.equals(p))) continue;else result.push(p);
  39942. if (result.length == count) break;
  39943. }
  39944. if (result.length == count) return result;
  39945. }
  39946. var texLoader$6 = new TextureLoader();
  39947. var defaultColor$1 = new Color(config$1.measure.default.color);
  39948. var highlightColor = new Color(config$1.measure.highlight.color);
  39949. var color = new Color(config$1.measure.color);
  39950. var textColor = new Color(config$1.measure.textColor);
  39951. var markerMats;
  39952. var lineMats;
  39953. var planeMats;
  39954. var textSizeRatio = math.linearClamp(window.outerWidth * window.outerHeight, [360 * 720, 1920 * 1080], [0.7, 1]); //pc字显示大一些 用
  39955. var lineDepthInfo = {
  39956. clipDistance: 15,
  39957. //4,//消失距离
  39958. occlusionDistance: 3 //1,//变为backColor距离
  39959. };
  39960. var markerMapShrink = browser.isMobile() ? 0.4 : 0.8; //触屏需要更大的热区
  39961. var markerSizeInfo = {
  39962. width2d: 18 / markerMapShrink // nearBound : 1.5, farBound : 15,
  39963. };
  39964. /* const markerSizeInfo = {
  39965. minSize : 10 , maxSize : 15 , nearBound : 1.5, farBound : 15,
  39966. } */
  39967. var labelSizeInfo = {
  39968. width2d: 200
  39969. };
  39970. var mainLabelProp = {
  39971. //backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  39972. backgroundColor: {
  39973. r: 0,
  39974. g: 0,
  39975. b: 0,
  39976. a: 0
  39977. },
  39978. textColor: {
  39979. r: textColor.r * 255,
  39980. g: textColor.g * 255,
  39981. b: textColor.b * 255,
  39982. a: 1.0
  39983. },
  39984. textBorderColor: {
  39985. r: 255,
  39986. g: 255,
  39987. b: 255,
  39988. a: 1.0
  39989. },
  39990. textBorderThick: 3,
  39991. fontsize: 15 * textSizeRatio,
  39992. borderRadius: 12,
  39993. margin: {
  39994. x: 20,
  39995. y: 4
  39996. },
  39997. renderOrder: Potree.config.renderOrders.measureLabel,
  39998. pickOrder: Potree.config.renderOrders.measureLabel,
  39999. disToLine: -0.15,
  40000. useDepth: true,
  40001. // 2023.10 尽量不让数字被挡住
  40002. clipDistance: 10,
  40003. //消失距离
  40004. occlusionDistance: 10,
  40005. //变为backColor距离
  40006. maxOcclusionFactor: 0.3,
  40007. maxClipFactor: 0.8
  40008. };
  40009. var subLabelProp = {
  40010. backgroundColor: {
  40011. r: 255,
  40012. g: 255,
  40013. b: 255,
  40014. a: 0
  40015. },
  40016. textColor: {
  40017. r: textColor.r * 255,
  40018. g: textColor.g * 255,
  40019. b: textColor.b * 255,
  40020. a: 1.0
  40021. },
  40022. textBorderColor: {
  40023. r: 255,
  40024. g: 255,
  40025. b: 255,
  40026. a: 1.0
  40027. },
  40028. textBorderThick: 3,
  40029. fontsize: 14 * textSizeRatio,
  40030. renderOrder: Potree.config.renderOrders.measureLabelSub,
  40031. pickOrder: Potree.config.renderOrders.measureLabelSub,
  40032. disToLine: -0.13
  40033. };
  40034. var angle = MathUtils.degToRad(5); //显示水平垂直辅助线的最小角度
  40035. var guideShowMinAngle = {
  40036. min: angle,
  40037. max: Math.PI / 2 - angle
  40038. };
  40039. class Measure$1 extends ctrlPolygon {
  40040. constructor(prop) {
  40041. prop.dimension = '2d';
  40042. super('measure', prop);
  40043. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  40044. this.name = this.measureType + this.constructor.counter; //'Measure_' + this.constructor.counter;
  40045. this.markerLabels = [];
  40046. this.edgeLabels = [];
  40047. this.angleLabels = [];
  40048. this.coordinateLabels = [];
  40049. this.area = {
  40050. value: 0,
  40051. string: ''
  40052. };
  40053. if (this.showArea) {
  40054. this.areaLabel = this.createAreaLabel();
  40055. this.add(this.areaLabel);
  40056. }
  40057. //add:
  40058. if (this.atPlane || this.faceDirection) {
  40059. //是一个平面上的话
  40060. this.createGuideLine();
  40061. }
  40062. if (this.measureType == 'Distance' /* || this.measureType.includes('MulDistance') */) {
  40063. this.createHorVerGuideLine();
  40064. }
  40065. this.selectStates = {};
  40066. this.setUnitSystem(prop.unit || viewer.unitConvert.UnitService.defaultSystem);
  40067. Potree.Utils.setObjectLayers(this, 'measure');
  40068. if (this.measureType == 'MulDistance' || this.measureType == 'Hor MulDistance' || this.measureType == 'Ver MulDistance') {
  40069. //this.showTotalDis = true
  40070. this.totalDisLabel = this.createTotalDisLabel();
  40071. this.add(this.totalDisLabel);
  40072. }
  40073. //addMarkers:
  40074. this.initData(prop);
  40075. this.pointsPos2d = new Map(); //屏幕上的二维坐标
  40076. this.points_datasets || (this.points_datasets = []); //存每个点是哪个数据集
  40077. this.addEventListener('marker_dropped', e => {
  40078. this.updateDatasetBelong(e.index);
  40079. });
  40080. this.addEventListener('isVisible', () => {
  40081. viewer.mapViewer && viewer.mapViewer.dispatchEvent({
  40082. type: 'content_changed'
  40083. });
  40084. });
  40085. this.lastDropTime = 0;
  40086. }
  40087. initData(prop) {
  40088. var makeIt = super.initData(prop);
  40089. if (makeIt) {
  40090. this.edges.forEach(edge => {
  40091. edge.dispatchEvent('addHoverEvent');
  40092. });
  40093. } else {
  40094. this.failBuilded = true;
  40095. }
  40096. }
  40097. updateDatasetBelong(changeIndex) {
  40098. //更新所属数据集
  40099. if (Potree.settings.editType == "merge" || this.measureType == 'MulDistance Ring') {
  40100. //点直接跟着数据集走,不用找整体的datasetId
  40101. this.dataset_points[changeIndex] = Potree.Utils.datasetPosTransform({
  40102. toDataset: true,
  40103. datasetId: this.points_datasets[changeIndex],
  40104. position: this.points[changeIndex].clone()
  40105. });
  40106. return;
  40107. }
  40108. var old = this.datasetId;
  40109. var maxCount = {
  40110. id: null,
  40111. count: 0
  40112. };
  40113. var datasets = {};
  40114. this.points_datasets.forEach(e => {
  40115. if (e == void 0) return;
  40116. if (datasets[e]) {
  40117. datasets[e]++;
  40118. } else {
  40119. datasets[e] = 1;
  40120. }
  40121. });
  40122. for (var i in datasets) {
  40123. if (datasets[i] > maxCount.count) {
  40124. maxCount = {
  40125. id: i,
  40126. count: datasets[i]
  40127. };
  40128. }
  40129. }
  40130. this.datasetId = maxCount.count > 0 ? maxCount.id : null;
  40131. //if(this.datasetId != old){
  40132. //this.dispatchEvent({type:'changeDatasetId'})
  40133. if (this.datasetId == void 0) {
  40134. this.dataset_points = null; //可能为空或[null,null...]
  40135. } else {
  40136. this.dataset_points = this.points.map(e => {
  40137. return Potree.Utils.datasetPosTransform({
  40138. toDataset: true,
  40139. datasetId: this.datasetId,
  40140. position: e.clone()
  40141. });
  40142. });
  40143. }
  40144. //}
  40145. }
  40146. transformByPointcloud() {
  40147. //每次移动点云 or 加载测量线时要获取一下当前position //有地图时
  40148. if (this.datasetId == void 0) return;
  40149. this.points = this.dataset_points.map(e => {
  40150. return Potree.Utils.datasetPosTransform({
  40151. fromDataset: true,
  40152. datasetId: this.datasetId,
  40153. position: e.clone()
  40154. });
  40155. });
  40156. this.getPoint2dInfo(this.points);
  40157. this.update({
  40158. ifUpdateMarkers: true
  40159. });
  40160. this.setSelected(false); //隐藏edgelabel
  40161. }
  40162. update() {
  40163. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  40164. if (options.index == -1) return;
  40165. super.update(options);
  40166. if (this.showCoordinates && this.points.length > 0) {
  40167. var position = this.points[0];
  40168. this.markers[0].position.copy(position);
  40169. {
  40170. // coordinate labels
  40171. var coordinateLabel = this.coordinateLabels[0];
  40172. var pos = [position.toArray()];
  40173. if (viewer.transform) {
  40174. var lonlat = viewer.transform.lonlatToLocal.inverse(position.toArray());
  40175. var EPSG4550 = viewer.transform.lonlatTo4550.forward(lonlat);
  40176. pos.push(lonlat, EPSG4550);
  40177. }
  40178. //let msg = position.toArray().map(p => Utils.addCommas(p.toFixed(2))).join(" / ");
  40179. var msg = pos.map(a => a.map(p => Utils.addCommas(p.toFixed(10))).join(", ")).join("<br>");
  40180. coordinateLabel.setText(msg);
  40181. coordinateLabel.setPos(position);
  40182. coordinateLabel.setVisible(true); //this.showCoordinates;
  40183. }
  40184. return;
  40185. }
  40186. var setEdgeLabel = (label, p1, p2, distance) => {
  40187. //设置label位置和字
  40188. this.setEdgeLabelPos(label, p1, p2);
  40189. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  40190. //var text = viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision, this.unitSystem, 1 , true)//distance要传0.1 这个factor
  40191. var text = this.getConvertString(distance, 'distance');
  40192. label.setText(text);
  40193. return distance;
  40194. };
  40195. /* let setEdgeLabel = (label,p1,p2,distance)=>{//设置label位置和字
  40196. this.setEdgeLabelPos(label,p1,p2)
  40197. distance = distance == void 0 ? p1.distanceTo(p2) : distance;
  40198. var text = this.labelText || viewer.unitConvert.convert(distance, 'distance', Potree.settings.precision , this.unitSystem, 0.001 , true, true)//distance要传0.1 这个factor
  40199. label.setText(text)
  40200. } */
  40201. var lastIndex = this.points.length - 1;
  40202. var setLabel = index => {
  40203. var previousIndex = this.getIndex(index, -1);
  40204. var nextIndex = this.getIndex(index, +1);
  40205. var previousPoint = this.points[previousIndex];
  40206. var point = this.points[index];
  40207. var nextPoint = this.points[nextIndex];
  40208. if (this.showDistances) {
  40209. // edge labels
  40210. var edgeLabel = this.edgeLabels[index];
  40211. var distance = point.distanceTo(nextPoint);
  40212. this.edges[index].distance_ = distance;
  40213. edgeLabel.shouldVisi = (index < lastIndex || this.isRect || this.closed && !this.isNew) && distance > 0;
  40214. //this.closed || edgeLabel.setVisible(edgeLabel.shouldVisi) //closed的在setEdgesDisplay中设置
  40215. Utils.updateVisible(edgeLabel, 'shouldVisi', edgeLabel.shouldVisi, 2);
  40216. if (edgeLabel.shouldVisi) {
  40217. edgeLabel.lineDir = new Vector3().subVectors(point, nextPoint).normalize(); //[point,nextPoint]
  40218. setEdgeLabel(edgeLabel, point, nextPoint, distance);
  40219. }
  40220. }
  40221. };
  40222. if (options.index != void 0) {
  40223. //更新第几个点
  40224. setLabel(options.index);
  40225. var previousIndex = this.getIndex(options.index, -1);
  40226. setLabel(previousIndex);
  40227. } else {
  40228. for (var index = 0; index <= lastIndex; index++) {
  40229. setLabel(index);
  40230. }
  40231. }
  40232. if (Potree.config.measure.mulLabelHideFaraway) {
  40233. this.measureType == 'MulDistance' && this.clearEdgeLabelVisi();
  40234. }
  40235. if (this.measureType == 'Distance' && this.points.length > 1) {
  40236. //设置水平垂直辅助线
  40237. var pTop, pBtm;
  40238. if (this.points[0].z > this.points[1].z) {
  40239. pTop = this.points[0];
  40240. pBtm = this.points[1];
  40241. } else {
  40242. pTop = this.points[1];
  40243. pBtm = this.points[0];
  40244. }
  40245. var projectPos = new Vector3(pTop.x, pTop.y, pBtm.z); //两条guideline的交点
  40246. {
  40247. //倾斜角度太小的时候不显示
  40248. var tan = pTop.distanceTo(projectPos) / pBtm.distanceTo(projectPos);
  40249. var _angle = Math.atan(tan);
  40250. this.shouldShowHorVerGuide = _angle > guideShowMinAngle.min && _angle < guideShowMinAngle.max;
  40251. }
  40252. LineDraw.updateLine(this.verGuideEdge, [pTop, projectPos]);
  40253. LineDraw.updateLine(this.horGuideEdge, [pBtm, projectPos]);
  40254. setEdgeLabel(this.verEdgeLabel, pTop, projectPos);
  40255. setEdgeLabel(this.horEdgeLabel, pBtm, projectPos);
  40256. this.verGuideEdge.visible = this.horGuideEdge.visible = this.shouldShowHorVerGuide;
  40257. this.verEdgeLabel.visible = this.horEdgeLabel.visible = this.shouldShowHorVerGuide;
  40258. }
  40259. if (this.showArea && this.points.length > 2) {
  40260. // update area
  40261. var _msg = this.getArea().string;
  40262. this.areaLabel.setPos(this.getCenter('areaPlaneCenter'));
  40263. this.areaLabel.setText(_msg);
  40264. Utils.updateVisible(this.areaLabel, 'setVisible', true); //this.areaLabel.setVisible(true)
  40265. }
  40266. if (this.totalDisLabel) {
  40267. this.ifShowTotalDis();
  40268. Utils.updateVisible(this.totalDisLabel, 'setVisible', this.showTotalDis);
  40269. this.edgeLabels.forEach(e => Utils.updateVisible(e, 'showTotalDis', !this.showTotalDis));
  40270. if (this.showTotalDis) {
  40271. var dis = this.getTotalDistance();
  40272. var _msg2 = this.getConvertString(dis, 'distance');
  40273. this.center = null;
  40274. this.center = this.getCenter();
  40275. this.totalDisLabel.setPos(this.center);
  40276. this.totalDisLabel.setText(_msg2);
  40277. }
  40278. }
  40279. }
  40280. getArea() {
  40281. var area;
  40282. if (this._area != void 0) {
  40283. area = this._area;
  40284. } else if (this.point2dInfo) {
  40285. area = Math.abs(math.getArea(this.point2dInfo.points2d)); //this.getArea();
  40286. } else {
  40287. //mulDistance Ring 2d面
  40288. area = Math.abs(math.getArea(this.points));
  40289. }
  40290. var msg = this.getConvertString(area, 'area');
  40291. //let msg = viewer.unitConvert.convert(area, 'area', Potree.settings.precision, this.unitSystem/* , 0.1 */ )
  40292. this.area = {
  40293. value: area,
  40294. string: msg
  40295. };
  40296. return this.area;
  40297. }
  40298. getConvertString(num, type) {
  40299. return viewer.unitConvert.convert(num, type, Potree.settings.precision, this.unitSystem, true, {
  40300. 'imperial': {
  40301. minFactor: 0.01
  40302. },
  40303. 'metric': {
  40304. minFactor: 0.01
  40305. }
  40306. });
  40307. }
  40308. ifShowTotalDis() {
  40309. var show = this.points.length > 2;
  40310. if (show) {
  40311. var maxDis = 0.15;
  40312. var lastIndex = this.points.length - 1;
  40313. for (var i = 0; i < lastIndex; i++) {
  40314. var len = this.edges[i].distance_;
  40315. if (len > maxDis) {
  40316. show = false;
  40317. break;
  40318. }
  40319. }
  40320. }
  40321. this.showTotalDis = show;
  40322. /* 连续测量:
  40323. 1. ≥2次测量,单个距离<15cm时,居中显示总长, hover、选中时显示每段长度
  40324. 2. 若连续测量的线段中,大于等于1段超出15cm,所有线段均显示长度
  40325. -------------------
  40326. */
  40327. }
  40328. clearEdgeLabelVisi() {
  40329. //修改点位置后清空,下次render时会自动getEdgeLabelVisi
  40330. var lastIndex = this.points.length - 1;
  40331. for (var index = 0; index <= lastIndex; index++) {
  40332. if (!this.closed && index == lastIndex) continue;
  40333. var edgeLabel = this.edgeLabels[index];
  40334. edgeLabel.visiMap.clear();
  40335. }
  40336. }
  40337. getEdgeLabelVisi(viewport) {
  40338. //获取多折线的edgelabel在不同视图里的可见性。要保证任何时候label能出现的线最小二维长度一致
  40339. var camera = viewport.camera;
  40340. var lastIndex = this.points.length - 1;
  40341. /* let pos2ds = this.points.map(point=> point.clone().project(camera) ) //即使只是旋转也会变动,尤其是转到屏幕外后变为显示。所以不用这种
  40342. let minDis = 0.01; */
  40343. var minDis = 0.02,
  40344. minAngleRatio = 0.07,
  40345. minAngle;
  40346. var vecs;
  40347. var forceShow;
  40348. if (camera.type == 'OrthographicCamera') {
  40349. minDis *= Math.pow(camera.top / camera.zoom, 2);
  40350. //console.log(minDis)
  40351. } else {
  40352. if (Potree.settings.displayMode == 'showPanos' && viewer.images360.zoomLevel == Potree.settings.zoom.max) {
  40353. forceShow = true; //当zoom到最大时强制显示,避免有的线太短永远显示不出长度
  40354. } else {
  40355. vecs = this.points.map(point => new Vector3().subVectors(point, camera.position).normalize());
  40356. minAngleRatio /= viewport.resolution.y / 1000 / textSizeRatio; //角度占fov最小比率
  40357. minAngle = minAngleRatio * MathUtils.degToRad(camera.fov);
  40358. }
  40359. }
  40360. for (var index = 0; index <= lastIndex; index++) {
  40361. if (!this.closed && index == lastIndex) continue;
  40362. var edgeLabel = this.edgeLabels[index];
  40363. var nextIndex = index + 1 > lastIndex ? 0 : index + 1;
  40364. var previousIndex = index === 0 ? lastIndex : index - 1;
  40365. var point = this.points[index];
  40366. var nextPoint = this.points[nextIndex];
  40367. /* let point2d = pos2ds[index];
  40368. let nextPoint2d = pos2ds[nextIndex];
  40369. let dis2d = point2d.distanceToSquared(nextPoint2d)
  40370. let v = dis2d > minDis //可见长度太小,为避免拥挤,不显示
  40371. edgeLabel.visiMap.set(camera, v) */
  40372. var v = void 0;
  40373. if (forceShow) {
  40374. v = true;
  40375. } else if (camera.type == 'OrthographicCamera') {
  40376. var vec = new Vector3().subVectors(point, nextPoint);
  40377. var projVec = vec.projectOnPlane(viewport.view.direction);
  40378. v = projVec.lengthSq() > minDis;
  40379. } else {
  40380. var vec0 = vecs[index];
  40381. var vec1 = vecs[nextIndex];
  40382. v = Math.acos(vec0.dot(vec1)) > minAngle; //角度过小代表可见长度太小,为避免拥挤,不显示
  40383. }
  40384. edgeLabel.visiMap.set(camera, v);
  40385. }
  40386. }
  40387. setEdgeLabelPos(label, p1, p2) {
  40388. //调整label的位置,使倾斜后看起来在线的中心,而不要挡住端点
  40389. var center = new Vector3().addVectors(p1, p2).multiplyScalar(0.5);
  40390. return label.setPos(center);
  40391. if (label.lineDir && label.lineDir.length() > 0) {
  40392. if (viewer.mainViewport.camera.type == 'OrthographicCamera') {
  40393. label.setPos(center);
  40394. } else {
  40395. //根据视线和线的夹角(后又加入相机和两个端点距离差)来决定标签偏移位置。+
  40396. var eyePos = viewer.mainViewport.camera.position;
  40397. var dir = viewer.mainViewport.view.direction; //new THREE.Vector3().subVectors(center,eyePos).normalize()
  40398. /*let centerDir = new THREE.Vector3().subVectors(center,eyePos).normalize()
  40399. if(centerDir.dot(dir)<0){//中点在相机后方,就不设置
  40400. label.setPos(center)
  40401. return
  40402. } */
  40403. var cos = dir.dot(label.lineDir);
  40404. var nearPoint = cos > 0 ? p2 : p1; //近端点。
  40405. var far = cos > 0 ? p1 : p2; //远端点。
  40406. var nearPointDir = new Vector3().subVectors(nearPoint, eyePos); //.normalize()
  40407. //使label在中点和近端点中变化, 近端点可能到了相机后方,需要投影到相机所在平面上
  40408. if (nearPointDir.dot(dir) < 0) {
  40409. //近端点到了相机后方,前移。
  40410. //let hfov = cameraLight.getHFOVForCamera(viewer.mainViewport.camera , true ); //暂且只看水平fov
  40411. //if(nearPointDir.dot(dir)<Math.cos(hfov/2)){//近端点在镜头外,前移。 --但是这个就得把点转化成在镜头边缘而非左右两边(camDirPlane上)
  40412. var ray = new Raycaster();
  40413. ray.set(nearPoint, cos > 0 ? label.lineDir : label.lineDir.clone().negate());
  40414. var camDirPlane = new Plane().setFromNormalAndCoplanarPoint(dir, eyePos);
  40415. nearPoint = ray.ray.intersectPlane(camDirPlane, new Vector3());
  40416. if (!nearPoint) {
  40417. //线是垂直的,视线是水平的时候
  40418. return label.setPos(center);
  40419. }
  40420. }
  40421. //防止离远了之后也偏移很多,但远了之后相机到端点vec和到中点的vec的夹角接近,不需要怎么偏移的。
  40422. var dis1 = nearPoint.distanceToSquared(eyePos);
  40423. var dis2 = far.distanceToSquared(eyePos);
  40424. var diff = Math.abs(dis1 / dis2);
  40425. diff < 1 && (diff = 1 / diff);
  40426. diff = math.linearClamp(diff, [0, 30], [0, 1]);
  40427. var efficiency = 0.7; // 0-1 数值越高,r越容易接近1或-1,label越容易在倾斜后靠近近端点。
  40428. //let r = 0.5*efficiency*cos + 0.5
  40429. var r = 0.5 * efficiency * diff * cos + 0.5;
  40430. r = MathUtils.clamp(r, 0.1, 0.9);
  40431. //视线越接近线的方向,标签应该越往近端点偏移,防止看起来几乎在远端。
  40432. if (cos > 0) {
  40433. center = p1.clone().multiplyScalar(1 - r).add(nearPoint.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心
  40434. } else {
  40435. center = nearPoint.clone().multiplyScalar(1 - r).add(p2.clone().multiplyScalar(r)); //label在线上滑动,使尽量保持在视觉中心
  40436. }
  40437. label.setPos(center);
  40438. }
  40439. //归零
  40440. //this.orient2dInfo = null
  40441. //this.markers.forEach(e=>e.needsUpdate=true)
  40442. } else {
  40443. label.setPos(center);
  40444. }
  40445. }
  40446. cloneMarker(cloneIndex, index) {
  40447. return this.addMarker({
  40448. index,
  40449. point: this.points[cloneIndex],
  40450. dataset_point: this.dataset_points && this.dataset_points[cloneIndex],
  40451. points_dataset: this.points_datasets[cloneIndex]
  40452. });
  40453. }
  40454. addMarker() {
  40455. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  40456. var index = o.index == void 0 ? this.points.length : o.index; //要当第几个
  40457. var marker = new Sprite$2({
  40458. mat: this.getMarkerMaterial('default'),
  40459. sizeInfo: markerSizeInfo,
  40460. name: "measure_point"
  40461. });
  40462. Potree.Utils.setObjectLayers(marker, 'measure');
  40463. marker.pickOrder = marker.renderOrder = Potree.config.renderOrders.measureMarker;
  40464. marker.markerSelectStates = {};
  40465. marker.addEventListener('startDragging', e => {
  40466. /* if(e.drag.dragViewport.name == 'MainView') */viewer.inputHandler.dispatchEvent({
  40467. type: 'measuring',
  40468. v: true,
  40469. cause: 'startDragging',
  40470. situation: 'dragging',
  40471. object: this
  40472. });
  40473. //add for 调试,方便后期增加点
  40474. if (!this.isNew && viewer.inputHandler.pressedKeys['M'.charCodeAt(0)] && this.points.length < this.maxMarkers) {
  40475. viewer.measuringTool.history.beforeChange(this);
  40476. var curIndex = this.markers.indexOf(marker);
  40477. this.cloneMarker(curIndex, curIndex + 1);
  40478. }
  40479. this.isNew || viewer.measuringTool.history.beforeChange(this);
  40480. });
  40481. marker.addEventListener('drop', e => {
  40482. if (e.button != MOUSE.LEFT) return;
  40483. viewer.inputHandler.dispatchEvent({
  40484. type: 'measuring',
  40485. v: false,
  40486. cause: 'stopDragging',
  40487. situation: 'dragging',
  40488. object: this
  40489. });
  40490. this.lastDropTime = Date.now();
  40491. if (Potree.settings.adsorption) {
  40492. this.isNew || viewer.viewports.forEach(viewport => {
  40493. this.getPointsPos2d(viewport, true); //forceUpdate
  40494. });
  40495. }
  40496. this.isNew || viewer.measuringTool.history.afterChange(this);
  40497. });
  40498. marker.addEventListener('click', () => {
  40499. if (viewer.measuringTool.editMode == 'delPoint') {
  40500. /* if(this.points.length == this.minMarkers){//--前端去重绘
  40501. viewer.scene.removeMeasurement(this)
  40502. }else{ */
  40503. viewer.measuringTool.history.beforeChange(this);
  40504. var _index = this.markers.indexOf(marker);
  40505. this.removeMarker(_index);
  40506. viewer.measuringTool.history.afterChange(this);
  40507. this.dispatchEvent('changed');
  40508. //}
  40509. }
  40510. });
  40511. //marker.measure = this
  40512. var edge;
  40513. {
  40514. // edges
  40515. edge = LineDraw.createFatLine([], {
  40516. mat: this.getLineMat('edgeDefault')
  40517. });
  40518. edge.pickOrder = 0;
  40519. Potree.Utils.setObjectLayers(edge, 'measure');
  40520. var addHoverEvent = () => {
  40521. //当非isNew时才添加事件
  40522. var mouseover = e => {
  40523. /* if(this.measureType == 'MulDistance'){
  40524. } */
  40525. this.setSelected(true, 'edge');
  40526. };
  40527. var mouseleave = e => {
  40528. this.setSelected(false, 'edge');
  40529. };
  40530. edge.addEventListener('mouseover', mouseover);
  40531. edge.addEventListener('mouseleave', mouseleave);
  40532. edge.removeEventListener('addHoverEvent', addHoverEvent);
  40533. edge.addEventListener('click', e => {
  40534. var now = Date.now();
  40535. if (now - this.lastDropTime < 100) return; //防止拖拽marker时误触导致focus, 以及点到marker不focus
  40536. if (viewer.measuringTool.editMode == 'addPoint' && this.points.length < this.maxMarkers) {
  40537. viewer.measuringTool.history.beforeChange(this);
  40538. var _index2 = this.edges.indexOf(edge) + 1;
  40539. var nextIndex = _index2 % this.edges.length;
  40540. var point = math.getFootPoint(e.hoveredElement.point, this.points[_index2 - 1], this.points[nextIndex]);
  40541. this.addMarker({
  40542. index: _index2,
  40543. point,
  40544. dataset_point: this.dataset_points && new Vector3(),
  40545. //初始化
  40546. points_dataset: this.points_datasets[_index2 - 1] //使用前一个的
  40547. });
  40548. this.updateDatasetBelong(_index2); //获取dataset_point
  40549. viewer.measuringTool.history.afterChange(this);
  40550. this.dispatchEvent('changed');
  40551. //this.update({})
  40552. } else {
  40553. this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure'); //正在添加测量线时不要focus其他线(容易误触)
  40554. }
  40555. });
  40556. };
  40557. edge.addEventListener('addHoverEvent', addHoverEvent);
  40558. if (!this.isNew) {
  40559. edge.dispatchEvent('addHoverEvent');
  40560. }
  40561. }
  40562. super.addMarker(Object.assign(o, {
  40563. index,
  40564. marker,
  40565. edge
  40566. }));
  40567. if (this.showEdges) {
  40568. // edge labels
  40569. var edgeLabel = this.createEdgeLabel('edgeLabel', !this.closed);
  40570. this.edgeLabels = [...this.edgeLabels.slice(0, index), edgeLabel, ...this.edgeLabels.slice(index, this.edgeLabels.length)];
  40571. }
  40572. if (this.showCoordinates) {
  40573. // coordinate labels
  40574. var coordinateLabel = new Label({
  40575. className: 'measure_pointPos',
  40576. camera: viewer.scene.getActiveCamera()
  40577. });
  40578. coordinateLabel.setVisible(false);
  40579. this.coordinateLabels.push(coordinateLabel);
  40580. }
  40581. var event = {
  40582. type: 'marker_added',
  40583. measurement: this,
  40584. marker: marker
  40585. };
  40586. this.dispatchEvent(event);
  40587. //this.setMarker(this.points.length - 1, point);
  40588. this.update({
  40589. index
  40590. }); //更新一下倒数第二条线
  40591. return marker; //add
  40592. }
  40593. editStateChange(state) {
  40594. //主要针对edgeLabels显示切换,编辑时显示
  40595. super.editStateChange(state);
  40596. if (!state) {
  40597. this.editStateTimer = setTimeout(() => {
  40598. if (!this.isEditing) {
  40599. this.dispatchEvent({
  40600. type: 'editStateChange',
  40601. state: false
  40602. });
  40603. this.setEdgesDisplay(false);
  40604. this.areaPlane && Potree.Utils.updateVisible(this.areaPlane, 'intersectLastLine', true);
  40605. this.areaLabel && Potree.Utils.updateVisible(this.areaLabel, 'intersectLastLine', true);
  40606. }
  40607. }, 100);
  40608. } else {
  40609. if (!this.isEditing) {
  40610. this.dispatchEvent({
  40611. type: 'editStateChange',
  40612. state: true
  40613. });
  40614. this.setEdgesDisplay(true);
  40615. clearTimeout(this.editStateTimer);
  40616. }
  40617. }
  40618. this.isEditing = state;
  40619. }
  40620. setMarkerSelected(marker, state, hoverObject) {
  40621. //console.warn(marker.id , state, hoverObject)
  40622. marker.markerSelectStates[hoverObject] = state;
  40623. var absoluteState = false;
  40624. for (var i in marker.markerSelectStates) {
  40625. if (marker.markerSelectStates[i] == 'hover') {
  40626. absoluteState = true;
  40627. break;
  40628. }
  40629. }
  40630. if (absoluteState) {
  40631. marker.material = this.getMarkerMaterial('select');
  40632. marker.renderOrder = marker.pickOrder = Potree.config.renderOrders.measureMarker + 1;
  40633. } else {
  40634. marker.material = this.getMarkerMaterial('default');
  40635. marker.renderOrder = marker.pickOrder = Potree.config.renderOrders.measureMarker;
  40636. }
  40637. marker.selected = absoluteState;
  40638. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  40639. viewer.dispatchEvent('content_changed');
  40640. }
  40641. setEdgesDisplay(state, ignoreGuideLine) {
  40642. this.closed && this.edgeLabels.forEach(e => Utils.updateVisible(e, 'hover', state));
  40643. if (this.totalDisLabel && !viewer.screenshoting) {
  40644. this.edgeLabels.forEach(e => Utils.updateVisible(e, 'hover', state, 1, state ? 'add' : 'cancel'));
  40645. Utils.updateVisible(this.totalDisLabel, 'hover', !state);
  40646. }
  40647. if (!ignoreGuideLine && this.measureType == 'Distance') {
  40648. this.horEdgeLabel.visible = this.verEdgeLabel.visible = this.horGuideEdge.visible = this.verGuideEdge.visible = !!(state && this.shouldShowHorVerGuide);
  40649. }
  40650. }
  40651. setSelected(state, hoverObject) {
  40652. //add
  40653. //console.log('setSelected',state, hoverObject)
  40654. var absoluteState = !!state;
  40655. if (hoverObject) {
  40656. //如果没有hoverObject且state为false 就强制取消选中态
  40657. this.selectStates[hoverObject] = state;
  40658. for (var i in this.selectStates) {
  40659. if (this.selectStates[i]) {
  40660. absoluteState = true;
  40661. break;
  40662. }
  40663. }
  40664. }
  40665. if (absoluteState) {
  40666. this.markers.forEach(e => this.setMarkerSelected(e, 'hover', 'selectAll'));
  40667. this.edges.forEach(e => {
  40668. e.renderOrder = Potree.config.renderOrders.lines + 1;
  40669. e.material = this.getLineMat('edgeSelect');
  40670. });
  40671. this.areaPlane && (this.areaPlane.material = planeMats.selected);
  40672. //this.areaLabel && this.areaLabel.elem.addClass('highLight')
  40673. //this.closed || this.edgeLabels.forEach(e=>e.elem.addClass('highLight') )
  40674. this.setEdgesDisplay(true, hoverObject == "screenshot");
  40675. this.areaLabel && setLabelHightState(this.areaLabel, true);
  40676. this.closed || this.edgeLabels.forEach(e => setLabelHightState(e, true));
  40677. } else {
  40678. this.markers.forEach(e => this.setMarkerSelected(e, 'unhover', 'selectAll'));
  40679. this.edges.forEach(e => e.material = this.getLineMat('edgeDefault'));
  40680. this.areaPlane && (this.areaPlane.material = planeMats.default);
  40681. this.setEdgesDisplay(false, hoverObject == "screenshot");
  40682. //this.areaLabel && this.areaLabel.elem.removeClass('highLight')
  40683. //this.closed || this.edgeLabels.forEach(e=>e.elem.removeClass('highLight') )
  40684. this.areaLabel && setLabelHightState(this.areaLabel, false);
  40685. this.closed || this.edgeLabels.forEach(e => setLabelHightState(e, false));
  40686. }
  40687. this.selected = absoluteState;
  40688. if (hoverObject != 'byList') {
  40689. //this.bus && this.bus.emit('highlight', this.selected)
  40690. this.dispatchEvent({
  40691. type: 'highlight',
  40692. state: this.selected
  40693. }); //列表高亮
  40694. }
  40695. viewer.dispatchEvent('content_changed');
  40696. viewer.mapViewer && viewer.mapViewer.dispatchEvent('content_changed');
  40697. }
  40698. removeMarker(index) {
  40699. super.removeMarker(index);
  40700. this.points_datasets.splice(index, 1);
  40701. this.dataset_points && this.dataset_points.splice(index, 1);
  40702. this.coordinateLabels.splice(index, 1);
  40703. var edgeIndex = index; //(index === 0) ? 0 : (index - 1);
  40704. if (this.edgeLabels[edgeIndex]) {
  40705. this.edgeLabels[edgeIndex].dispose();
  40706. this.edgeLabels.splice(edgeIndex, 1);
  40707. }
  40708. this.update({
  40709. index: this.getIndex(index, -1)
  40710. });
  40711. this.dispatchEvent({
  40712. type: 'marker_removed',
  40713. measurement: this
  40714. });
  40715. }
  40716. setPosition(index, position) {
  40717. super.setPosition(index, position);
  40718. var event = {
  40719. type: 'marker_moved',
  40720. measure: this,
  40721. index: index,
  40722. position: position.clone()
  40723. };
  40724. this.dispatchEvent(event);
  40725. }
  40726. dispose() {
  40727. //add
  40728. var labels = this.edgeLabels.concat(this.coordinateLabels);
  40729. this.areaLabel && labels.push(this.areaLabel);
  40730. labels.forEach(e => e.dispose());
  40731. super.dispose();
  40732. this.dispatchEvent('disposed');
  40733. }
  40734. getTotalDistance() {
  40735. if (this.points.length === 0) {
  40736. return 0;
  40737. }
  40738. var distance = 0;
  40739. for (var i = 1; i < this.points.length; i++) {
  40740. var prev = this.points[i - 1];
  40741. var curr = this.points[i];
  40742. var d = prev.distanceTo(curr);
  40743. distance += d;
  40744. }
  40745. if (this.closed && this.points.length > 1) {
  40746. var first = this.points[0];
  40747. var last = this.points[this.points.length - 1];
  40748. var _d = last.distanceTo(first);
  40749. distance += _d;
  40750. }
  40751. return distance;
  40752. }
  40753. getAngleBetweenLines(cornerPoint, point1, point2) {
  40754. var v1 = new Vector3().subVectors(point1, cornerPoint);
  40755. var v2 = new Vector3().subVectors(point2, cornerPoint);
  40756. // avoid the error printed by threejs if denominator is 0
  40757. var denominator = Math.sqrt(v1.lengthSq() * v2.lengthSq());
  40758. if (denominator === 0) {
  40759. return 0;
  40760. } else {
  40761. return v1.angleTo(v2);
  40762. }
  40763. }
  40764. getAngle(index) {
  40765. if (this.points.length < 3 || index >= this.points.length) {
  40766. return 0;
  40767. }
  40768. var previous = index === 0 ? this.points[this.points.length - 1] : this.points[index - 1];
  40769. var point = this.points[index];
  40770. var next = this.points[(index + 1) % this.points.length];
  40771. return this.getAngleBetweenLines(point, previous, next);
  40772. }
  40773. getCenter(type) {
  40774. if (this.center) {
  40775. return this.center.clone();
  40776. } else {
  40777. var center = this.points.reduce(function (total, currentValue) {
  40778. return total.add(currentValue);
  40779. }, new Vector3());
  40780. this.points.length && center.multiplyScalar(1 / this.points.length);
  40781. return center; //求不出重心呜呜
  40782. }
  40783. }
  40784. // updateAzimuth(){
  40785. // // if(this.points.length !== 2){
  40786. // // return;
  40787. // // }
  40788. // // const azimuth = this.azimuth;
  40789. // // const [p0, p1] = this.points;
  40790. // // const r = p0.distanceTo(p1);
  40791. // }
  40792. createGuideLine() {
  40793. //add 辅助线
  40794. var guideLine = LineDraw.createFatLine([], {
  40795. mat: this.getLineMat('guide')
  40796. });
  40797. guideLine.visible = false;
  40798. this.guideLine = guideLine;
  40799. this.add(guideLine);
  40800. }
  40801. createHorVerGuideLine() {
  40802. //创建水平与垂直辅助线,仅距离测量有。
  40803. var verGuideEdge = LineDraw.createFatLine([], {
  40804. mat: this.getLineMat('guide')
  40805. });
  40806. verGuideEdge.visible = false;
  40807. this.verGuideEdge = verGuideEdge;
  40808. verGuideEdge.name = 'verGuideEdge';
  40809. var horGuideEdge = LineDraw.createFatLine([], {
  40810. mat: this.getLineMat('guide')
  40811. });
  40812. horGuideEdge.visible = false;
  40813. horGuideEdge.name = 'horGuideEdge';
  40814. this.horGuideEdge = horGuideEdge;
  40815. this.add(this.verGuideEdge);
  40816. this.add(this.horGuideEdge);
  40817. //label:
  40818. this.verEdgeLabel = this.createEdgeLabel('verGuideEdge');
  40819. this.horEdgeLabel = this.createEdgeLabel('horGuideEdge');
  40820. }
  40821. createEdgeLabel(name, hasHoverEvent) {
  40822. var inf = {
  40823. sizeInfo: labelSizeInfo,
  40824. name: name || 'edgeLabel'
  40825. };
  40826. if (name && name.includes('Guide')) {
  40827. inf.fontsize = 12;
  40828. }
  40829. var edgeLabel = new TextSprite$2($.extend({}, hasHoverEvent ? mainLabelProp : subLabelProp, inf));
  40830. if (hasHoverEvent) {
  40831. edgeLabel.addEventListener('mouseover', () => {
  40832. this.setSelected(true, 'edgeLabel');
  40833. });
  40834. edgeLabel.addEventListener('mouseleave', () => {
  40835. this.setSelected(false, 'edgeLabel');
  40836. });
  40837. edgeLabel.addEventListener('click', () => {
  40838. this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure');
  40839. });
  40840. }
  40841. edgeLabel.visible = false;
  40842. edgeLabel.measure = this;
  40843. edgeLabel.sprite.material.depthTestWhenPick = true;
  40844. Potree.Utils.setObjectLayers(edgeLabel, 'measure');
  40845. this.add(edgeLabel);
  40846. if (this.measureType == 'MulDistance') {
  40847. edgeLabel.visiMap = new Map();
  40848. }
  40849. return edgeLabel;
  40850. }
  40851. createAreaLabel() {
  40852. var areaLabel = this.createCenterLabel('areaLabel');
  40853. return areaLabel;
  40854. }
  40855. createTotalDisLabel() {
  40856. var totalDisLabel = this.createCenterLabel('totalDisLabel');
  40857. return totalDisLabel;
  40858. }
  40859. createCenterLabel(name) {
  40860. var centerLabel = new TextSprite$2($.extend({}, mainLabelProp, {
  40861. sizeInfo: labelSizeInfo,
  40862. name,
  40863. disToLine: 0,
  40864. fontsize: 16 * textSizeRatio
  40865. }));
  40866. centerLabel.addEventListener('mouseover', () => {
  40867. this.isNew || this.setSelected(true, 'centerLabel');
  40868. });
  40869. centerLabel.addEventListener('mouseleave', () => {
  40870. this.isNew || this.setSelected(false, 'centerLabel');
  40871. });
  40872. centerLabel.addEventListener('click', () => {
  40873. this.isNew || viewer.measuringTool.isAdding || viewer.focusOnObject(this, 'measure');
  40874. });
  40875. Potree.Utils.setObjectLayers(centerLabel, 'measure');
  40876. Utils.updateVisible(centerLabel, 'setVisible', false);
  40877. return centerLabel;
  40878. }
  40879. getMarkerMaterial(type) {
  40880. if (!markerMats) {
  40881. markerMats = {
  40882. default: new DepthBasicMaterial($.extend({}, lineDepthInfo, {
  40883. transparent: !0,
  40884. opacity: 1,
  40885. map: texLoader$6.load(Potree.resourcePath + '/textures/pic_point_s32.png'),
  40886. useDepth: true,
  40887. mapScale: markerMapShrink
  40888. })),
  40889. select: new MeshBasicMaterial({
  40890. transparent: !0,
  40891. opacity: 1,
  40892. depthTest: false,
  40893. map: texLoader$6.load(Potree.resourcePath + '/textures/pic_point32.png' /* , null, null, { antialias: false } */)
  40894. })
  40895. };
  40896. Measure$1.markerMats = markerMats;
  40897. markerMats.select.map.repeat.set(1 / markerMapShrink, 1 / markerMapShrink);
  40898. markerMats.select.map.offset.set((markerMapShrink - 1) / 2 / markerMapShrink, (markerMapShrink - 1) / 2 / markerMapShrink);
  40899. //markerMats.select.map.offset.set( -1.1 , -1.1 )
  40900. }
  40901. return markerMats[type];
  40902. }
  40903. getLineMat(type) {
  40904. if (!Measure$1.lineMats) {
  40905. Measure$1.lineMats = {
  40906. edgeDefault: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, {
  40907. color: config$1.measure.default.color,
  40908. lineWidth: config$1.measure.lineWidth,
  40909. useDepth: true,
  40910. dashWithDepth: true,
  40911. // 只在被遮住的部分显示虚线,因为实线容易挡住label
  40912. dashed: true,
  40913. dashSize: 0.04,
  40914. gapSize: 0.04,
  40915. transparent: true,
  40916. opacity: config$1.measure.default.opacity,
  40917. depthTestWhenPick: true
  40918. })),
  40919. edgeSelect: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, {
  40920. color: config$1.measure.highlight.color,
  40921. //'#f0ff00',
  40922. dashSize: 0.5,
  40923. gapSize: 0.2,
  40924. lineWidth: config$1.measure.lineWidth,
  40925. transparent: true,
  40926. opacity: config$1.measure.highlight.opacity
  40927. })),
  40928. guide: LineDraw.createFatLineMat($.extend({}, lineDepthInfo, {
  40929. color: config$1.measure.guide.color,
  40930. dashSize: 0.1,
  40931. gapSize: 0.02,
  40932. dashed: true,
  40933. lineWidth: config$1.measure.lineWidth / 2
  40934. }))
  40935. };
  40936. }
  40937. return Measure$1.lineMats[type];
  40938. }
  40939. createAreaPlane() {
  40940. planeMats || (planeMats = {
  40941. default: new DepthBasicMaterial($.extend({}, lineDepthInfo, {
  40942. color: color,
  40943. side: DoubleSide,
  40944. opacity: 0.2,
  40945. transparent: true,
  40946. useDepth: true
  40947. })),
  40948. selected: new MeshBasicMaterial({
  40949. color: color,
  40950. side: DoubleSide,
  40951. opacity: 0.3,
  40952. transparent: true
  40953. //wireframe:true
  40954. })
  40955. }, Measure$1.planeMats = planeMats);
  40956. return super.createAreaPlane(planeMats.default);
  40957. }
  40958. raycast(raycaster, intersects) {
  40959. for (var i = 0; i < this.points.length; i++) {
  40960. var marker = this.markers[i];
  40961. marker.raycast(raycaster, intersects);
  40962. }
  40963. // recalculate distances because they are not necessarely correct
  40964. // for scaled objects.
  40965. // see https://github.com/mrdoob/three.js/issues/5827
  40966. // TODO: remove this once the bug has been fixed
  40967. for (var _i = 0; _i < intersects.length; _i++) {
  40968. var I = intersects[_i];
  40969. I.distance = raycaster.ray.origin.distanceTo(I.point);
  40970. }
  40971. intersects.sort(function (a, b) {
  40972. return a.distance - b.distance;
  40973. });
  40974. }
  40975. getPointsPos2d(viewport, update) {
  40976. //获取屏幕上的二维坐标
  40977. var ps = this.pointsPos2d.get(viewport);
  40978. if (update || !ps) {
  40979. var points = this.points.map(e => {
  40980. var p = Potree.Utils.getPos2d(e, viewport, viewer.renderArea);
  40981. p.pos3d = e.clone(), p.object = this;
  40982. return p;
  40983. });
  40984. this.pointsPos2d.set(viewport, points);
  40985. console.log('updatePointsPos2d', this.uuid, viewport.name);
  40986. }
  40987. return this.pointsPos2d.get(viewport);
  40988. }
  40989. transformData(prop) {
  40990. if (prop.measureType == 'Point') {
  40991. prop.showCoordinates = true, prop.closed = true, prop.maxMarkers = 1, prop.minMarkers = 1;
  40992. } else if (prop.measureType == 'Distance') {
  40993. prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2;
  40994. } else if (prop.measureType == 'MulDistance') {
  40995. prop.showDistances = true, prop.showEdges = true, prop.minMarkers = 2;
  40996. } else if (prop.measureType == 'MulDistance Ring') {
  40997. prop.showDistances = true, prop.showEdges = true, prop.showArea = true, prop.closed = true, prop.minMarkers = 3;
  40998. } else if (prop.measureType == 'Ver MulDistance') {
  40999. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.minMarkers = 2;
  41000. prop.faceDirection = "vertical";
  41001. prop.unableDragAtMap = true;
  41002. } else if (prop.measureType == 'Hor MulDistance') {
  41003. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.minMarkers = 2;
  41004. prop.faceDirection = "horizontal";
  41005. } else if (prop.measureType == 'Ver Distance') {
  41006. prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2, prop.faceDirection = "vertical";
  41007. prop.unableDragAtMap = true;
  41008. } else if (prop.measureType == 'Hor Distance') {
  41009. prop.showDistances = true, prop.showEdges = true, prop.maxMarkers = 2, prop.minMarkers = 2, prop.faceDirection = "horizontal";
  41010. } else if (prop.measureType == 'Area') {
  41011. prop.showDistances = true, Potree.settings.areaAtNotPlane || (prop.atPlane = true);
  41012. prop.showEdges = true, prop.closed = true, prop.minMarkers = 3;
  41013. } else if (prop.measureType == 'Hor Area') {
  41014. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 3;
  41015. prop.faceDirection = "horizontal";
  41016. } else if (prop.measureType == 'Ver Area') {
  41017. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 3;
  41018. prop.faceDirection = "vertical";
  41019. prop.unableDragAtMap = true;
  41020. } else if (prop.measureType == 'Rect Area') {
  41021. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4;
  41022. prop.maxMarkers = 4;
  41023. } else if (prop.measureType == 'Hor Rect Area') {
  41024. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4;
  41025. prop.maxMarkers = 4;
  41026. prop.isRect = true;
  41027. prop.faceDirection = "horizontal";
  41028. } else if (prop.measureType == 'Ver Rect Area') {
  41029. prop.showDistances = true, prop.atPlane = true, prop.showEdges = true, prop.closed = true, prop.minMarkers = 4;
  41030. prop.maxMarkers = 4;
  41031. prop.isRect = true;
  41032. prop.faceDirection = "vertical";
  41033. prop.unableDragAtMap = true;
  41034. }
  41035. if (prop.atPlane && prop.closed) {
  41036. //atPlane在同一平面上
  41037. prop.showArea = true;
  41038. }
  41039. super.transformData(prop);
  41040. }
  41041. setUnitSystem(unitSystem) {
  41042. //console.log(this.name +':' +this.unitSystem)
  41043. if (unitSystem != this.unitSystem) {
  41044. if (unitSystem == "metric") {} else if (unitSystem == 'imperial') {}
  41045. this.unitSystem = unitSystem;
  41046. this.update();
  41047. }
  41048. }
  41049. reDraw() {
  41050. var restMarkerCount = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  41051. //重新开始画
  41052. super.reDraw(restMarkerCount);
  41053. if (this.measureType == 'Distance') {
  41054. this.shouldShowHorVerGuide = false;
  41055. this.setEdgesDisplay(false);
  41056. }
  41057. if (this.showArea) {
  41058. this.area = {
  41059. value: 0
  41060. };
  41061. this.areaLabel && Utils.updateVisible(this.areaLabel, 'setVisible', false);
  41062. }
  41063. if (this.totalDisLabel && this.showTotalDis) {
  41064. Utils.updateVisible(this.totalDisLabel, 'setVisible', false);
  41065. }
  41066. viewer.inputHandler.dispatchEvent({
  41067. type: 'measuring',
  41068. v: true,
  41069. cause: 'reDraw',
  41070. object: this,
  41071. situation: 'dragging'
  41072. });
  41073. }
  41074. }
  41075. function setLabelHightState(label, state) {
  41076. if (state) {
  41077. var _color = new Color(Potree.config.measure.highlight.color);
  41078. //label.sprite.material.opacity = config.measure.highlight.opacity
  41079. //label.setBackgroundColor({r:255*color.r, g:255*color.g, b:255*color.b, a:config.measure.highlight.opacity})
  41080. label.sprite.material.useDepth = false;
  41081. //label.textColor = {r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a: 1}
  41082. } else {
  41083. //label.setBackgroundColor({r: this.color.r*255, g: this.color.g*255, b: this.color.b*255, a:config.measure.default.opacity})
  41084. label.sprite.material.useDepth = true;
  41085. //label.sprite.material.opacity = 0.98
  41086. //label.textColor = {r: 255, g: 255, b: 255, a: 1}
  41087. }
  41088. label.updateTexture();
  41089. }
  41090. /* function setLabelHightState(label, state){
  41091. if(state){
  41092. label.setBackgroundColor({r: highlightColor.r*255, g: highlightColor.g*255, b: highlightColor.b*255, a:config.measure.highlight.labelOpacity})
  41093. label.sprite.material.useDepth = false;
  41094. }else{
  41095. label.setBackgroundColor(mainLabelProp.backgroundColor)
  41096. label.sprite.material.useDepth = true
  41097. }
  41098. label.updateTexture()
  41099. //label.sprite.material.needsUpdate = true
  41100. }
  41101. */
  41102. function createCircleRadiusLabel$1() {
  41103. var circleRadiusLabel = new TextSprite$2("");
  41104. circleRadiusLabel.setTextColor({
  41105. r: 140,
  41106. g: 250,
  41107. b: 140,
  41108. a: 1.0
  41109. });
  41110. circleRadiusLabel.setBorderColor({
  41111. r: 0,
  41112. g: 0,
  41113. b: 0,
  41114. a: 1.0
  41115. });
  41116. circleRadiusLabel.setBackgroundColor({
  41117. r: 0,
  41118. g: 0,
  41119. b: 0,
  41120. a: 1.0
  41121. });
  41122. circleRadiusLabel.fontsize = 16;
  41123. circleRadiusLabel.material.depthTest = false;
  41124. circleRadiusLabel.material.opacity = 1;
  41125. circleRadiusLabel.visible = false;
  41126. return circleRadiusLabel;
  41127. }
  41128. function createCircleRadiusLine$1() {
  41129. /* const lineGeometry = new LineGeometry();
  41130. lineGeometry.setPositions([
  41131. 0, 0, 0,
  41132. 0, 0, 0,
  41133. ]);
  41134. const lineMaterial = new LineMaterial({
  41135. color: 0xff0000,
  41136. lineWidth: 2,
  41137. resolution: new THREE.Vector2(1000, 1000),
  41138. gapSize: 1,
  41139. dashed: true,
  41140. });
  41141. lineMaterial.depthTest = false;
  41142. const circleRadiusLine = new Line2(lineGeometry, lineMaterial);*/
  41143. var circleRadiusLine = LineDraw.createFatLine([], {
  41144. color: 0xff0000,
  41145. dashSize: 0.5,
  41146. gapSize: 0.2,
  41147. lineWidth: config$1.measure.lineWidth
  41148. });
  41149. circleRadiusLine.visible = false;
  41150. return circleRadiusLine;
  41151. }
  41152. function createCircleLine$1() {
  41153. var coordinates = [];
  41154. var n = 128;
  41155. for (var i = 0; i <= n; i++) {
  41156. var u0 = 2 * Math.PI * (i / n);
  41157. var u1 = 2 * Math.PI * (i + 1) / n;
  41158. var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0);
  41159. var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0);
  41160. coordinates.push(p0, p1);
  41161. }
  41162. /* const geometry = new LineGeometry();
  41163. geometry.setPositions(coordinates);
  41164. const material = new LineMaterial({
  41165. color: 0xff0000,
  41166. dashSize: 5,
  41167. gapSize: 2,
  41168. lineWidth: 2,
  41169. resolution: new THREE.Vector2(1000, 1000),
  41170. });
  41171. material.depthTest = false;
  41172. const circleLine = new Line2(geometry, material);
  41173. circleLine.visible = false;
  41174. circleLine.computeLineDistances();*/
  41175. var circleLine = LineDraw.createFatLine(coordinates, {
  41176. color: 0xff0000,
  41177. dashSize: 0.5,
  41178. gapSize: 0.2,
  41179. lineWidth: config$1.measure.lineWidth
  41180. });
  41181. return circleLine;
  41182. }
  41183. /* function createCircleCenter(){
  41184. const sg = new THREE.markerGeometry(1, 32, 32);
  41185. const sm = new THREE.MeshNormalMaterial();
  41186. const circleCenter = new THREE.Mesh(sg, sm);
  41187. circleCenter.visible = false;
  41188. return circleCenter;
  41189. } */
  41190. function createLine$1() {
  41191. var line = LineDraw.createFatLine([], {
  41192. color: 0xff0000,
  41193. dashSize: 0.5,
  41194. gapSize: 0.2,
  41195. lineWidth: config$1.measure.lineWidth
  41196. });
  41197. return line;
  41198. }
  41199. function createCircle$1() {
  41200. var coordinates = [];
  41201. var n = 128;
  41202. for (var i = 0; i <= n; i++) {
  41203. var u0 = 2 * Math.PI * (i / n);
  41204. var u1 = 2 * Math.PI * (i + 1) / n;
  41205. var p0 = new Vector3(Math.cos(u0), Math.sin(u0), 0);
  41206. var p1 = new Vector3(Math.cos(u1), Math.sin(u1), 0);
  41207. coordinates.push(p0, p1);
  41208. }
  41209. var line = LineDraw.createFatLine(coordinates, {
  41210. color: 0xff0000,
  41211. dashSize: 0.5,
  41212. gapSize: 0.2,
  41213. lineWidth: config$1.measure.lineWidth
  41214. });
  41215. return line;
  41216. }
  41217. /* function createAzimuth(){
  41218. const azimuth = {
  41219. label: null,
  41220. center: null,
  41221. target: null,
  41222. north: null,
  41223. centerToNorth: null,
  41224. centerToTarget: null,
  41225. centerToTargetground: null,
  41226. targetgroundToTarget: null,
  41227. circle: null,
  41228. node: null,
  41229. };
  41230. const sg = new THREE.markerGeometry(1, 32, 32);
  41231. const sm = new THREE.MeshNormalMaterial();
  41232. {
  41233. const label = new TextSprite("");
  41234. label.setTextColor({r: 140, g: 250, b: 140, a: 1.0});
  41235. label.setBorderColor({r: 0, g: 0, b: 0, a: 1.0});
  41236. label.setBackgroundColor({r: 0, g: 0, b: 0, a: 1.0});
  41237. label.fontsize = 16;
  41238. label.material.depthTest = false;
  41239. label.material.opacity = 1;
  41240. azimuth.label = label;
  41241. }
  41242. azimuth.center = new THREE.Mesh(sg, sm);
  41243. azimuth.target = new THREE.Mesh(sg, sm);
  41244. azimuth.north = new THREE.Mesh(sg, sm);
  41245. azimuth.centerToNorth = createLine();
  41246. azimuth.centerToTarget = createLine();
  41247. azimuth.centerToTargetground = createLine();
  41248. azimuth.targetgroundToTarget = createLine();
  41249. azimuth.circle = createCircle();
  41250. azimuth.node = new THREE.Object3D();
  41251. azimuth.node.add(
  41252. azimuth.centerToNorth,
  41253. azimuth.centerToTarget,
  41254. azimuth.centerToTargetground,
  41255. azimuth.targetgroundToTarget,
  41256. azimuth.circle,
  41257. azimuth.label,
  41258. azimuth.center,
  41259. azimuth.target,
  41260. azimuth.north,
  41261. );
  41262. return azimuth;
  41263. } */
  41264. /*
  41265. 按alt鼠标滚轮或WS键放慢。
  41266. 按Alt键可以平行屏幕拖拽点。&dragPolyBeyondPoint 后缀在拖拽到无点云区域也是此效果。
  41267. 按M键拖拽点可以复制出当前点
  41268. */
  41269. class History extends EventDispatcher {
  41270. constructor(o) {
  41271. super();
  41272. this.undoList = [];
  41273. this.redoList = [];
  41274. this.applyData = o.applyData; //应用数据的方法
  41275. this.getData = o.getData; //获取数据的方法
  41276. this.dataBefore;
  41277. (o.viewer || viewer).inputHandler.addEventListener('keydown', e => {
  41278. if (e.keyCode == 90 && e.event.ctrlKey) {
  41279. //Z
  41280. this.undo();
  41281. } else if (e.keyCode == 89 && e.event.ctrlKey) {
  41282. //Y
  41283. this.redo();
  41284. }
  41285. });
  41286. }
  41287. undo() {
  41288. //回退
  41289. var length = this.undoList.length;
  41290. if (length > 0) {
  41291. var unExist;
  41292. var last = this.undoList.pop();
  41293. this.applyData && (unExist = !this.applyData(last.before));
  41294. unExist || this.redoList.push(last);
  41295. unExist && this.undo(); //找不到就回退下一个。
  41296. this.dispatchEvent('undo');
  41297. //console.log('undo',last)
  41298. }
  41299. }
  41300. redo() {
  41301. //撤销回退
  41302. var length = this.undoList.length;
  41303. var last = this.redoList.pop();
  41304. if (last) {
  41305. //注意:每行的顺序不能乱
  41306. this.undoList.push(last);
  41307. this.applyData && this.applyData(last.after);
  41308. this.dispatchEvent('redo');
  41309. //console.log('redo',last)
  41310. }
  41311. }
  41312. beforeChange(o) {
  41313. //在变化之前(可能执行好几次直到变化完,但只有第一次有效)。 o的内容完全根据getData怎么定义
  41314. if (!this.dataBefore) {
  41315. var data = this.getData(o);
  41316. data && (this.dataBefore = data);
  41317. }
  41318. }
  41319. afterChange(o) {
  41320. //变化结束,从beforeChange到此算一次操作。
  41321. if (this.dataBefore) {
  41322. this.writeIn({
  41323. before: this.dataBefore,
  41324. after: this.getData(o)
  41325. }); //写入某物体变化前和变化后的状态
  41326. this.dataBefore = null;
  41327. }
  41328. }
  41329. writeIn(data) {
  41330. this.redoList.length = 0; //一旦录入新的操作,就不允许undo了
  41331. this.undoList.push(data);
  41332. //console.log('新增undo', data)
  41333. }
  41334. clear() {
  41335. this.redoList.length = 0;
  41336. this.undoList.length = 0;
  41337. this.dataBefore = null;
  41338. }
  41339. }
  41340. var areaPlaneMats = {};
  41341. class Prism extends Measure$1 {
  41342. constructor(args) {
  41343. super(args);
  41344. this.isPrism = true;
  41345. this.volumeInfo = {};
  41346. this.needsCompute = true;
  41347. /*this.createPrismLines(new THREE.Color('#FFF') )
  41348. this.lineMesh.material.transparent = true
  41349. this.lineMesh.material.opacity = 0.5
  41350. Potree.Utils.setObjectLayers(this.lineMesh, 'measure' ) */
  41351. this.setClipBox();
  41352. this.setTopOrBtm('zMin');
  41353. this.setTopOrBtm('zMax');
  41354. this.setHorizonHeight('btm');
  41355. var update = () => {
  41356. this.setHorizonHeight(this.horizonType, true); //更新
  41357. this.needsCompute = true;
  41358. this.getBound();
  41359. this.dispatchEvent('updated');
  41360. };
  41361. this.addEventListener('marker_dropped' /* 'marker_moved' */, update);
  41362. this.addEventListener('changeByHistory', update);
  41363. this.addEventListener('changed', update);
  41364. /* this.addEventListener('createDone',()=>{
  41365. this.setHorizonHeight()//更新
  41366. this.updateAreaPlane()
  41367. }) */
  41368. this.updateAreaPlane();
  41369. this.getBound();
  41370. this.addEventListener('needsCompute', () => {
  41371. this.needsCompute = true;
  41372. }, 10);
  41373. //Potree.Utils.setObjectLayers(this.lineMesh, 'bothMapAndScene' )
  41374. }
  41375. set needsCompute(state) {
  41376. if (state == 'byVolume') {
  41377. this.needsCompute_ = this.volumeInfo.Vupper == void 0;
  41378. } else {
  41379. this.needsCompute_ = !!state;
  41380. //console.error('needsCompute', state)
  41381. }
  41382. }
  41383. get needsCompute() {
  41384. return this.needsCompute_;
  41385. }
  41386. setHorizonHeight(v) {
  41387. var old = this.horizonZ;
  41388. if (typeof v == 'number') {
  41389. this.horizonType = 'number';
  41390. this.horizonZ = v;
  41391. } else {
  41392. if (v) {
  41393. this.horizonType = v;
  41394. }
  41395. if (!this.horizonType) this.horizonType = 'btm';
  41396. if (this.horizonType == 'number') return;
  41397. var zs = this.points.map(p => p.z).sort((a, b) => a - b);
  41398. this.horizonZ = this.horizonType == 'btm' ? zs[0] : zs[this.points.length - 1];
  41399. }
  41400. //this.horizonZ = THREE.Math.clamp(this.horizonZ, this.zMin, this.zMax )
  41401. if (this.horizonZ != old) {
  41402. this.needsCompute = true;
  41403. this.update(); //update areaPlane and areaLabel pos
  41404. this.dispatchEvent('horizonZChanged');
  41405. }
  41406. //console.log(this.horizonZ)
  41407. }
  41408. setBaseModel(model, modelHaventLoad) {
  41409. //三种状态:使用model、使用基准高度、 什么都没有(不允许计算、不高亮、等待模型上传)
  41410. this.baseModel = model;
  41411. this.modelHaventLoad = modelHaventLoad;
  41412. Potree.Utils.updateVisible(this.areaPlane, 'unuseHorizonH', !model && !modelHaventLoad);
  41413. }
  41414. setClipBox(boxes) {
  41415. //clipBoxes_out
  41416. this.clipBoxes = boxes || [];
  41417. }
  41418. setTopOrBtm(name, v) {
  41419. if (v != void 0) {
  41420. this[name] = v;
  41421. this.updatePrismLines();
  41422. } else {
  41423. this[name] = viewer.bound.boundingBox[name == 'zMin' ? 'min' : 'max'].z;
  41424. }
  41425. this.getBound();
  41426. this.needsCompute = true;
  41427. }
  41428. getBound() {
  41429. var bound = Potree.math.getBound(this.points);
  41430. bound.min.z = this.zMin;
  41431. bound.max.z = this.zMax;
  41432. this.prismBound = bound;
  41433. }
  41434. setVolumeInfo(volumeInfo) {
  41435. this.volumeInfo = volumeInfo;
  41436. this.getVolumeString();
  41437. this.needsCompute = false; //但得到的不一定是对的可能 检查下
  41438. }
  41439. getVolumeString() {
  41440. if (!this.volumeInfo || this.volumeInfo.Vupper == void 0) return;
  41441. this.VupperString = this.getConvertString(this.volumeInfo.Vupper, 'volume', true);
  41442. this.VlowerString = this.getConvertString(this.volumeInfo.Vlower, 'volume', true);
  41443. this.highestString = this.getConvertString(this.volumeInfo.highest, 'distance', true);
  41444. this.lowestString = this.getConvertString(this.volumeInfo.lowest, 'distance', true);
  41445. }
  41446. getConvertString(num, type, restrictUnit) {
  41447. if (!restrictUnit) return super.getConvertString(num, type);
  41448. return viewer.unitConvert.convert(num, type, Potree.settings.precision, this.unitSystem, null, {
  41449. //在pdf里的高度要统一单位
  41450. 'imperial': {
  41451. restrictUnit: 'Foot'
  41452. },
  41453. //ft
  41454. 'metric': {
  41455. restrictUnit: 'Meter'
  41456. }
  41457. });
  41458. }
  41459. setUnitSystem(unitSystem) {
  41460. var old = this.unitSystem;
  41461. super.setUnitSystem(unitSystem);
  41462. if (unitSystem != old) {
  41463. this.getVolumeString();
  41464. }
  41465. }
  41466. getCenter(type) {
  41467. if (type == 'areaPlaneCenter') {
  41468. //areaPlane中心
  41469. return this.areaPlaneCenter;
  41470. }
  41471. return super.getCenter(); //点的中心
  41472. }
  41473. update() {
  41474. super.update.apply(this, arguments);
  41475. this.updatePrismLines();
  41476. }
  41477. getTransformationMatrix(pointcloud) {
  41478. //剪裁矩阵
  41479. var invMatrix = new Matrix4();
  41480. //把当前z移动到-0.5 ~ 0.5所需要的变换
  41481. var minZ = this.zMin; //viewer.bound.boundingBox.min.z
  41482. var maxZ = this.zMax; //viewer.bound.boundingBox.max.z
  41483. var s = 1 / (maxZ - minZ);
  41484. var pos = new Vector3(0, 0, -0.5 - minZ * s),
  41485. scale = new Vector3(1, 1, s);
  41486. invMatrix.compose(pos, new Quaternion(), scale); //先缩放后位移
  41487. return new Matrix4().multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose();
  41488. }
  41489. changeStyleForScreenshot(state) {
  41490. var {
  41491. hideLabel,
  41492. showName
  41493. } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  41494. //截图前变一下外观。根据高度变化颜色
  41495. var config = Potree.settings.prismHeightColor;
  41496. var color; //, lineWidth = this.edges[0].material.lineWidth
  41497. if (this.volumeInfo.Vupper > 0.01 && this.volumeInfo.Vlower > 0.01) {
  41498. color = config.every.color;
  41499. } else if (this.volumeInfo.Vupper > this.volumeInfo.Vlower) {
  41500. for (var i = config.dig.length - 1; i >= 0; i--) {
  41501. if (this.volumeInfo.Vupper >= config.dig[i].min) {
  41502. color = config.dig[i].color;
  41503. break;
  41504. }
  41505. }
  41506. } else {
  41507. for (var _i = config.fill.length - 1; _i >= 0; _i--) {
  41508. if (this.volumeInfo.Vlower >= config.fill[_i].min) {
  41509. color = config.fill[_i].color;
  41510. break;
  41511. }
  41512. }
  41513. }
  41514. color = new Color(color[0] / 255, color[1] / 255, color[2] / 255);
  41515. var name = color.getHexString();
  41516. if (state) {
  41517. Potree.Utils.updateVisible(this.areaPlane, 'screenshot', true, 2, 'add'); //强制显示
  41518. var mat = areaPlaneMats[name];
  41519. if (!mat) {
  41520. mat = new MeshBasicMaterial({
  41521. color,
  41522. transparent: true,
  41523. opacity: 0.6,
  41524. side: DoubleSide
  41525. });
  41526. areaPlaneMats[name] = mat;
  41527. }
  41528. this.oldAreaPlaneMat = this.areaPlane.material;
  41529. this.areaPlane.material = mat;
  41530. if (hideLabel) {
  41531. Potree.Utils.updateVisible(this.areaLabel, 'screenshot-single', false);
  41532. }
  41533. if (showName) {
  41534. this.areaLabel.setText([this.name, this.area.string]);
  41535. /* let btm = this.areaPlaneCenter.clone().setY(this.prismBound.min.y) //置于土方2d块底部
  41536. this.areaLabel.setPos(btm)
  41537. this.areaLabel.sprite.position.y = -0.25 */
  41538. }
  41539. this.markers.forEach(marker => Potree.Utils.updateVisible(marker, 'screenshot-Prism', false));
  41540. this.edges.forEach(edge => Potree.Utils.updateVisible(edge, 'screenshot-Prism', false));
  41541. //Potree.Utils.updateVisible(this.lineMesh,'screenshot-Prism',false)
  41542. this.styleRecover = () => {
  41543. this.areaPlane.material = this.oldAreaPlaneMat;
  41544. if (hideLabel) {
  41545. Potree.Utils.updateVisible(this.areaLabel, 'screenshot-single', true);
  41546. }
  41547. if (showName) {
  41548. this.areaLabel.setText(this.area.string);
  41549. /* this.areaLabel.setPos(this.areaPlaneCenter)
  41550. this.areaLabel.sprite.position.y = 0 */
  41551. }
  41552. this.markers.forEach(marker => Potree.Utils.updateVisible(marker, 'screenshot-Prism', true));
  41553. this.edges.forEach(edge => Potree.Utils.updateVisible(edge, 'screenshot-Prism', true));
  41554. //Potree.Utils.updateVisible(this.lineMesh,'screenshot-Prism',true)
  41555. this.styleRecover = null;
  41556. };
  41557. } else {
  41558. this.styleRecover && this.styleRecover();
  41559. Potree.Utils.updateVisible(this.areaPlane, 'screenshot', false, 2, 'cancel');
  41560. }
  41561. }
  41562. dispose() {
  41563. super.dispose();
  41564. this.clipBoxes.forEach(e => viewer.scene.removeVolume(e));
  41565. }
  41566. setEditState(state) {
  41567. //编辑页面or截图
  41568. state = !!state;
  41569. this.editing = state;
  41570. this.dontHighlight = !state;
  41571. this.clipBoxes.forEach(box => {
  41572. Potree.Utils.updateVisible(box, 'hidden', state), box.clip = state;
  41573. });
  41574. }
  41575. /* {
  41576. fill: [
  41577. {color: [236, 213, 143, 1], min: 0, max: 5},
  41578. {color: [223, 118, 21, 1], min: 5, max: 10},
  41579. // 没有min表示大于
  41580. {color: [186, 57, 57, 1], min: 10}
  41581. ],
  41582. dig: [
  41583. {color: [144, 193, 190, 1], min: 0, max: 5},
  41584. {color: [76, 155, 211, 1], min: 5, max: 10},
  41585. // 没有min表示大于
  41586. {color: [79, 76, 211, 1], min: 10}
  41587. ],
  41588. // 填挖并存
  41589. every: { color: [49, 200, 181, 1] }
  41590. } */
  41591. }
  41592. class MeasuringTool extends EventDispatcher {
  41593. constructor(viewer) {
  41594. super();
  41595. this.viewer = viewer;
  41596. this.renderer = viewer.renderer;
  41597. this.viewer.addEventListener('start_inserting_measurement', e => {
  41598. this.viewer.dispatchEvent({
  41599. type: 'cancel_insertions'
  41600. });
  41601. });
  41602. this.showLabels = true;
  41603. this.scene = new Scene();
  41604. this.scene.name = 'scene_measurement';
  41605. //this.light = new THREE.PointLight(0xffffff, 1.0);
  41606. //this.scene.add(this.light);
  41607. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  41608. this.history = new History({
  41609. applyData: data => {
  41610. if (data.measure.parent && data.measure.visible) {
  41611. data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用
  41612. data.measure.reDraw();
  41613. data.measure.initData(data);
  41614. data.measure.isNew = data.isNew;
  41615. data.measure.dispatchEvent('changeByHistory');
  41616. /* if(data.measure.isPrism){
  41617. data.measure.needsCompute = data.needsCompute
  41618. } */
  41619. data.measure.facePlane = data.facePlane && data.facePlane.clone();
  41620. data.measure.cannotConfirmNormal = data.cannotConfirmNormal;
  41621. return true;
  41622. }
  41623. },
  41624. getData: measure => {
  41625. var data = {
  41626. measure,
  41627. points: measure.points.map(e => e.clone()),
  41628. dataset_points: measure.dataset_points ? measure.dataset_points.map(e => e && e.clone()) : null,
  41629. points_datasets: measure.points_datasets.slice(),
  41630. datasetId: measure.datasetId,
  41631. isNew: measure.isNew,
  41632. facePlane: measure.facePlane && measure.facePlane.clone(),
  41633. cannotConfirmNormal: measure.cannotConfirmNormal
  41634. };
  41635. /* if(measure.isPrism){ //没用
  41636. data.volumeInfo = measure.volumeInfo
  41637. data.needsCompute = measure.needsCompute
  41638. //但不记录其他信息
  41639. } */
  41640. return data;
  41641. }
  41642. }),
  41643. //this.scene = viewer.overlay//
  41644. this.onRemove = e => {
  41645. e.measurement.dispose(); /* this.scene.remove(e.measurement); */
  41646. };
  41647. this.onAdd = e => {
  41648. this.scene.add(e.measurement);
  41649. };
  41650. for (var measurement of viewer.scene.measurements) {
  41651. this.onAdd({
  41652. measurement: measurement
  41653. });
  41654. }
  41655. viewer.addEventListener('camera_changed', this.update.bind(this), {
  41656. importance: 10
  41657. }); //优先级高于sprite
  41658. if (Potree.config.measure.mulLabelHideFaraway) {
  41659. viewer.addEventListener("raycaster", this.beforeDraw.bind(this), {
  41660. importance: 10
  41661. }); //before render
  41662. viewer.addEventListener("render.begin", this.beforeDraw.bind(this), {
  41663. importance: 10
  41664. }); //before render
  41665. viewer.addEventListener("render.begin2", this.beforeDraw.bind(this), {
  41666. importance: 10
  41667. });
  41668. }
  41669. //viewer.addEventListener("update", this.update.bind(this));
  41670. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  41671. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  41672. viewer.scene.addEventListener('measurement_added', this.onAdd);
  41673. viewer.scene.addEventListener('measurement_removed', this.onRemove);
  41674. viewer.addEventListener('resize', this.setSize.bind(this));
  41675. }
  41676. onSceneChange(e) {
  41677. if (e.oldScene) {
  41678. e.oldScene.removeEventListener('measurement_added', this.onAdd);
  41679. e.oldScene.removeEventListener('measurement_removed', this.onRemove);
  41680. }
  41681. e.scene.addEventListener('measurement_added', this.onAdd);
  41682. e.scene.addEventListener('measurement_removed', this.onRemove);
  41683. }
  41684. createMeasureFromData(data) {
  41685. //add
  41686. var measure = data.measureType == 'MulDistance Ring' ? new Prism(data) : new Measure$1(data);
  41687. if (measure.failBuilded) {
  41688. return;
  41689. }
  41690. viewer.scene.addMeasurement(measure);
  41691. if (measure.guideLine) measure.guideLine.visible = false;
  41692. return measure;
  41693. }
  41694. beforeDraw(e) {
  41695. if (e.viewport.name == 'mapViewport' && !viewer.mapViewer.attachedToViewer) return; //no measures
  41696. viewer.scene.measurements.forEach(measure => {
  41697. if (measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length < 4 : measure.points.length < 3)) return;
  41698. var lastIndex = measure.points.length - 1;
  41699. for (var index = 0; index <= lastIndex; index++) {
  41700. if (!measure.closed && index == lastIndex) continue;
  41701. var edgeLabel = measure.edgeLabels[index];
  41702. var v = edgeLabel.visiMap.get(e.viewport.camera);
  41703. if (v == void 0) {
  41704. return measure.getEdgeLabelVisi(e.viewport);
  41705. }
  41706. Potree.Utils.updateVisible(edgeLabel, 'tooFar', v === false ? false : true);
  41707. }
  41708. });
  41709. }
  41710. update(e) {
  41711. /* viewer.scene.measurements.forEach(measure=>{
  41712. if(measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length<4 : measure.points.length<3)) return
  41713. }) */
  41714. if (viewer.inputHandler.measuring && Potree.settings.adsorption) {
  41715. viewer.scene.measurements.forEach(measure => {
  41716. measure.getPointsPos2d(e.viewport, true);
  41717. });
  41718. }
  41719. if (Potree.config.measure.mulLabelHideFaraway) {
  41720. if (e.changeInfo.projectionChanged || e.viewport.camera.type == 'PerspectiveCamera' && e.changeInfo.positionChanged) {
  41721. //for MulDistance
  41722. viewer.scene.measurements.forEach(measure => {
  41723. if (measure.measureType != 'MulDistance' || (measure.isNew ? measure.points.length < 4 : measure.points.length < 3)) return;
  41724. measure.getEdgeLabelVisi(e.viewport);
  41725. return;
  41726. var lastIndex = measure.points.length - 1;
  41727. for (var index = 0; index <= lastIndex; index++) {
  41728. if (!measure.closed && index == lastIndex) continue;
  41729. var nextIndex = index + 1 > lastIndex ? 0 : index + 1;
  41730. var previousIndex = index === 0 ? lastIndex : index - 1;
  41731. var point = measure.points[index];
  41732. var nextPoint = measure.points[nextIndex];
  41733. var previousPoint = measure.points[previousIndex];
  41734. var point2d = new Vector2().copy(pos2ds[index]);
  41735. var nextPoint2d = new Vector2().copy(pos2ds[nextIndex]);
  41736. if (measure.showDistances || measure.labelText) {
  41737. // edge labels
  41738. var edgeLabel = measure.edgeLabels[index];
  41739. if (edgeLabel.visible) {
  41740. measure.setEdgeLabelPos(edgeLabel, point, nextPoint);
  41741. }
  41742. }
  41743. }
  41744. });
  41745. }
  41746. }
  41747. return;
  41748. var camera = this.viewer.scene.getActiveCamera();
  41749. var domElement = this.renderer.domElement;
  41750. var measurements = this.viewer.scene.measurements;
  41751. // make size independant of distance
  41752. var mainLabels = [],
  41753. subLabels = [];
  41754. for (var measure of measurements) {
  41755. measure.lengthUnit = this.viewer.lengthUnit;
  41756. measure.lengthUnitDisplay = this.viewer.lengthUnitDisplay;
  41757. //measure.update();
  41758. updateAzimuth(this.viewer, measure);
  41759. /* [...measure.markers, ...measure.edgeLabels, measure.areaLabel].forEach(e=>{
  41760. e && e.update()
  41761. }); */
  41762. // labels
  41763. /* let labels = measure.edgeLabels.concat(measure.angleLabels);
  41764. for(let label of labels){
  41765. label.update()
  41766. if(label.elem.hasClass('sub')){
  41767. subLabels.push(label)
  41768. }else{
  41769. mainLabels.push(label)
  41770. }
  41771. }
  41772. // coordinate labels
  41773. for (let j = 0; j < measure.coordinateLabels.length; j++) {
  41774. let label = measure.coordinateLabels[j];
  41775. label.update()
  41776. mainLabels.push(label)
  41777. }
  41778. if(measure.showArea){ // area label
  41779. let label = measure.areaLabel;
  41780. label.update()
  41781. mainLabels.push(label)
  41782. } */
  41783. /* if(measure.showCircle){ // radius label
  41784. let label = measure.circleRadiusLabel;
  41785. let distance = label.position.distanceTo(camera.position);
  41786. let pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  41787. let scale = (70 / pr);
  41788. label.scale.set(scale, scale, scale);
  41789. } */
  41790. if (!this.showLabels) {
  41791. var labels = [...measure.sphereLabels, ...measure.angleLabels, measure.circleRadiusLabel];
  41792. for (var label of labels) {
  41793. label.visible = false;
  41794. }
  41795. }
  41796. }
  41797. //this.updateLabelZIndex([{labels:subLabels},{labels:mainLabels}])
  41798. }
  41799. setSize(e) {//e.resolution
  41800. /* if(Measure.lineMats){
  41801. for(var m in Measure.lineMats){
  41802. Measure.lineMats[m].resolution.set(e.canvasWidth, e.canvasHeight);
  41803. }
  41804. }
  41805. if(Measure.sphereMats){
  41806. for(var s in Measure.sphereMats){
  41807. Measure.sphereMats[s].uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  41808. }
  41809. }
  41810. for (let measure of this.viewer.scene.measurements) {
  41811. measure.edgeLabels.concat(measure.areaLabel).forEach(label=>{
  41812. label.sprite.material.uniforms.resolution.value.set(e.canvasWidth, e.canvasHeight);
  41813. })
  41814. } */
  41815. }
  41816. updateLabelZIndex(group) {
  41817. //[{labels:[]},{}] 顺序按照z-index低到高
  41818. group.forEach((e, i) => {
  41819. e.base = group[i - 1] ? group[i - 1].base + group[i - 1].labels.length : 0;
  41820. var labels = e.labels.sort((a, b) => {
  41821. return b.pos2d.z - a.pos2d.z;
  41822. });
  41823. labels.forEach((label, index) => {
  41824. $(label.elem).css('z-index', e.base + index);
  41825. });
  41826. });
  41827. }
  41828. changeEditMode(mode) {
  41829. viewer.dispatchEvent({
  41830. type: "CursorChange",
  41831. action: "remove",
  41832. name: "addPoint"
  41833. });
  41834. viewer.dispatchEvent({
  41835. type: "CursorChange",
  41836. action: "remove",
  41837. name: "delPoint"
  41838. });
  41839. if (mode) {
  41840. if (mode == 'addPoint') {
  41841. viewer.dispatchEvent({
  41842. type: "CursorChange",
  41843. action: "add",
  41844. name: "addPoint"
  41845. });
  41846. } else {
  41847. viewer.dispatchEvent({
  41848. type: "CursorChange",
  41849. action: "add",
  41850. name: "delPoint"
  41851. });
  41852. }
  41853. }
  41854. this.editMode = mode;
  41855. }
  41856. editStateChange(e) {
  41857. //console.log("editStateChange" , e.state)
  41858. var state = e.state;
  41859. if (!state) {
  41860. state = viewer.scene.measurements.some(e => e.isEditing);
  41861. }
  41862. if (state) {
  41863. viewer.dispatchEvent({
  41864. type: "measureMovePoint"
  41865. }); //重新激活reticule状态
  41866. } else {
  41867. viewer.dispatchEvent({
  41868. type: "endMeasureMove"
  41869. });
  41870. }
  41871. //this.editing =
  41872. }
  41873. startInsertion() {
  41874. var _this = this;
  41875. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  41876. var callback = arguments.length > 1 ? arguments[1] : undefined;
  41877. var cancelFun = arguments.length > 2 ? arguments[2] : undefined;
  41878. var domElement = this.viewer.renderer.domElement;
  41879. var measure = args.measureType == 'MulDistance Ring' ? new Prism(args) : new Measure$1(args);
  41880. this.scene.add(measure);
  41881. measure.isNew = true;
  41882. this.viewer.dispatchEvent({
  41883. type: 'start_inserting_measurement',
  41884. measure: measure
  41885. });
  41886. measure.addEventListener('editStateChange', this.editStateChange.bind(this));
  41887. measure.editStateChange(true);
  41888. var timer;
  41889. this.isAdding = true;
  41890. var endDragFun = e => {
  41891. var length = measure.points.length;
  41892. if (e.button == MOUSE.LEFT || e.isTouch) {
  41893. if (length >= measure.maxMarkers) {
  41894. _end({
  41895. finish: true
  41896. });
  41897. } else {
  41898. this.history.beforeChange(measure);
  41899. var marker = measure.cloneMarker(length - 1, length);
  41900. if (args.isRect && measure.markers.length == 3) {
  41901. //marker全可见
  41902. measure.cloneMarker(0, 3);
  41903. } else {
  41904. measure.markers[length].visible = false;
  41905. measure.edges[length].visible = false;
  41906. }
  41907. measure.edges[length - 1].visible = true;
  41908. measure.markers[length - 1].visible = true;
  41909. marker.isDragging = true;
  41910. this.history.afterChange(measure);
  41911. measure.continueDrag(marker, e);
  41912. }
  41913. } else if (e.button === MOUSE.RIGHT) {
  41914. //触屏怎么取消?
  41915. if (e.pressDistance < Potree.config.clickMaxDragDis) {
  41916. //非拖拽的话
  41917. var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0, measure.point2dInfo.points2d.length - 1)); //检测除了最后一个点的相交情况
  41918. if (!isIntersectSelf) _end(e);else measure.continueDrag(null, e);
  41919. } else measure.continueDrag(null, e);
  41920. }
  41921. };
  41922. var _end = function end() {
  41923. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  41924. //确定、结束
  41925. if (!measure.isNew) return;
  41926. if (args.minMarkers != void 0) {
  41927. if (!e.finish && measure.markers.length <= args.minMarkers) {
  41928. //右键 当个数不够时取消
  41929. //this.viewer.scene.removeMeasurement(measure)
  41930. //重新开始画
  41931. if (measure.markers.length > 0) {
  41932. measure.markers[0].removeEventListener('mousedown', _end);
  41933. measure.reDraw();
  41934. _this.viewer.addEventListener('global_click', click, {
  41935. importance: 10
  41936. });
  41937. measure.editStateChange(true);
  41938. }
  41939. return;
  41940. /* if(!Potree.settings.isOfficial) this.viewer.scene.removeMeasurement(measure)
  41941. else if(e.drag){ //正式版本不允许右键退出, 继续
  41942. continueDrag(e.drag.object)
  41943. measure.editStateChange(true)
  41944. return
  41945. } */
  41946. }
  41947. }
  41948. var lastMarker = measure.markers[measure.markers.length - 1];
  41949. if ( /* !e.finish&& */measure.markers.length > args.minMarkers) {
  41950. measure.removeMarker(measure.points.length - 1);
  41951. measure.markers[0].removeEventListener('mouseover', mouseover);
  41952. measure.markers[0].removeEventListener('mouseleave', mouseleave);
  41953. measure.markers[0].removeEventListener('click' /* 'mousedown' */, Exit);
  41954. if (e.byClickMarker && measure.markers.length > args.minMarkers) {
  41955. //通过点击第一个marker而结束的话,会多一个marker。但点击marker后可能会因为和它坐标一致而没有添加成功,就不删,根据添加的时间来判断。
  41956. var delta = Date.now() - lastMarker.createTime;
  41957. //console.log('delta',delta)
  41958. if (delta < 10) {
  41959. //刚生成的,说明点击后新增了一个marker
  41960. measure.removeMarker(measure.points.length - 1);
  41961. }
  41962. }
  41963. }
  41964. measure.isNew = false;
  41965. var length = measure.points.length;
  41966. if (length) {
  41967. measure.markers[length - 1].visible = true;
  41968. measure.edges[length - 1].visible = !!measure.closed;
  41969. measure.markers.forEach(marker => {
  41970. marker.dispatchEvent('addHoverEvent');
  41971. });
  41972. measure.edges.forEach(edge => {
  41973. edge.dispatchEvent('addHoverEvent');
  41974. });
  41975. measure.update(); //update last edgeLabel
  41976. }
  41977. clearTimeout(timer);
  41978. _this.viewer.removeEventListener('cancel_insertions', Exit);
  41979. //pressExit && this.viewer.inputHandler.removeEventListener('keydown', pressExit);
  41980. _this.viewer.removeEventListener('global_click', click);
  41981. _this.viewer.removeEventListener('global_mousemove', ifAtWrongPlace);
  41982. viewer.dispatchEvent({
  41983. type: "CursorChange",
  41984. action: "remove",
  41985. name: "polygon_AtWrongPlace"
  41986. });
  41987. viewer.inputHandler.dispatchEvent({
  41988. type: 'measuring',
  41989. v: false,
  41990. cause: 'stopInsertion',
  41991. situation: 'adding',
  41992. object: measure
  41993. });
  41994. //var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d.slice(0,measure.point2dInfo.points2d.length-1))//检测除了最后一个点的相交情况
  41995. var isIntersectSelf = measure.atPlane && measure.closed && !measure.isRect && measure.point2dInfo && measure.intersectSelf(measure.point2dInfo.points2d);
  41996. if (isIntersectSelf) return cancelFun && cancelFun(); //请求删除,不重建
  41997. e.remove || callback && callback();
  41998. /* this.viewer.dispatchEvent({
  41999. type: 'finish_inserting_measurement',
  42000. measure: measure
  42001. }); */
  42002. _this.isAdding = false;
  42003. measure.dispatchEvent('createDone');
  42004. };
  42005. measure.addEventListener('finish', _end); //完成
  42006. var Exit = e => {
  42007. //强制退出
  42008. if (e.measure && e.measure != measure || !viewer.scene.measurements.includes(measure) || !measure.isNew) {
  42009. return; //若指定了退出的measure但和该measure不一致,就返回
  42010. }
  42011. if (e.remove || e.type == 'cancel_insertions') {
  42012. viewer.scene.removeMeasurement(measure);
  42013. }
  42014. measure.editStateChange(false);
  42015. measure.cannotConfirmNormal = false; //一些dropMarker中的句子
  42016. measure.guideLine && (measure.guideLine.visible = false);
  42017. /*
  42018. if(this.viewer.inputHandler.drag && !e.remove ){//还未触发drop的话
  42019. this.viewer.inputHandler.drag.object.dispatchEvent({ //这句会导致又增一个marker
  42020. type: 'drop',
  42021. drag: this.viewer.inputHandler.drag,
  42022. viewer: this.viewer,
  42023. pressDistance:0,
  42024. button : THREE.MOUSE.RIGHT
  42025. });
  42026. } else {*/ //未结束时添加新的measure时会触发
  42027. _end({
  42028. finish: true,
  42029. remove: e.remove,
  42030. byClickMarker: e.type == 'click'
  42031. });
  42032. //}
  42033. this.viewer.inputHandler.drag && (this.viewer.inputHandler.drag.object = null);
  42034. };
  42035. this.viewer.addEventListener('cancel_insertions', Exit);
  42036. /*let pressExit
  42037. if(!Potree.settings.isOfficial){
  42038. pressExit = (e)=>{
  42039. if(e.keyCode == 27){//Esc
  42040. //Exit()
  42041. //怎么模拟右键???//现由前端发出
  42042. }
  42043. }
  42044. this.viewer.inputHandler.addEventListener('keydown', pressExit)
  42045. } */
  42046. var mouseover = e => {
  42047. measure.setMarkerSelected(e.object, 'hover', 'single');
  42048. };
  42049. var mouseleave = e => {
  42050. measure.setMarkerSelected(e.object, 'unhover', 'single');
  42051. };
  42052. var click = e => {
  42053. //一旦点击就立刻增加两marker
  42054. if (ifAtWrongPlace(e)) return;
  42055. if (e.clickElement) return; //如点击label时focusOnObject
  42056. if (e.button === MOUSE.RIGHT) return;
  42057. //console.log('measure clicked33', !!e.intersectPoint)
  42058. //var I = e.intersectPoint && (e.intersectPoint.orthoIntersect || e.intersectPoint.location)
  42059. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  42060. if (!I) {
  42061. return measure.dispatchEvent('intersectNoPointcloud');
  42062. }
  42063. var atMap = e.drag.dragViewport.name == 'mapViewport';
  42064. //在地图上测量的首个点按楼层高度(暂时先只按mainViewport相机高度吧,但navvis是按楼层,画在楼层的地面上,可能因为平面图显示的是楼层近地面),
  42065. if (atMap) {
  42066. I = I.clone().setZ(viewer.mainViewport.camera.position.z);
  42067. }
  42068. var marker = measure.addMarker({
  42069. point: I
  42070. });
  42071. marker.isDragging = true;
  42072. this.viewer.inputHandler.startDragging(marker, {
  42073. endDragFun,
  42074. notPressMouse: true
  42075. }); //notPressMouse代表不是通过按下鼠标来拖拽
  42076. e.drag = this.viewer.inputHandler.drag;
  42077. /* e.drag.endDragFun = endDragFun
  42078. e.drag.notPressMouse = true */
  42079. //if(!measure.dragMarker(e) || !measure.dropMarker(e))return
  42080. measure.dragMarker(e);
  42081. measure.dropMarker(e);
  42082. if (measure.maxMarkers > 1) {
  42083. measure.markers[1].visible = false;
  42084. measure.edges[1].visible = false;
  42085. }
  42086. if (measure.closed && !measure.isRect) {
  42087. measure.markers[0].addEventListener('mouseover', mouseover);
  42088. measure.markers[0].addEventListener('mouseleave', mouseleave);
  42089. measure.markers[0].addEventListener('click' /* 'mousedown' */, Exit); //点击到第一个marker就结束
  42090. }
  42091. this.viewer.removeEventListener('global_click', click); ///* global_drop */
  42092. //console.log('measure clicked')
  42093. e.consume && e.consume();
  42094. return {
  42095. stopContinue: true
  42096. }; //防止继续执行别的侦听,如flytopano
  42097. };
  42098. //点击第n下拥有n+1个marker, n>0
  42099. viewer.inputHandler.dispatchEvent({
  42100. type: 'measuring',
  42101. v: true,
  42102. cause: 'startInsertion',
  42103. situation: 'adding',
  42104. object: measure
  42105. });
  42106. this.viewer.addEventListener('global_click', click, {
  42107. importance: 10
  42108. }); //add importance
  42109. var ifAtWrongPlace = e => {
  42110. if (measure.unableDragAtMap && e.hoverViewport.name == 'mapViewport') {
  42111. if (e.isTouch) {
  42112. viewer.dispatchEvent({
  42113. type: 'reticule_forbit',
  42114. v: true
  42115. });
  42116. } else {
  42117. viewer.dispatchEvent({
  42118. type: "CursorChange",
  42119. action: "add",
  42120. name: "polygon_AtWrongPlace"
  42121. });
  42122. }
  42123. return true;
  42124. } else {
  42125. if (e.isTouch) {
  42126. viewer.dispatchEvent({
  42127. type: 'reticule_forbit',
  42128. v: false
  42129. });
  42130. } else {
  42131. viewer.dispatchEvent({
  42132. type: "CursorChange",
  42133. action: "remove",
  42134. name: "polygon_AtWrongPlace"
  42135. });
  42136. }
  42137. }
  42138. };
  42139. if (measure.unableDragAtMap) {
  42140. this.viewer.addEventListener('global_mousemove', ifAtWrongPlace);
  42141. }
  42142. var changeByHistory = e => {
  42143. if (!measure.isNew) return;
  42144. var marker = measure.markers[measure.points.length - 1];
  42145. this.viewer.inputHandler.startDragging(marker, {
  42146. endDragFun,
  42147. notPressMouse: true
  42148. });
  42149. var I = viewer.inputHandler.intersect && (viewer.inputHandler.intersect.orthoIntersect || viewer.inputHandler.intersect.location);
  42150. if (I) {
  42151. measure.dragChange(I.clone(), measure.points.length - 1); //使最后一个点在鼠标处
  42152. }
  42153. /* if(measure.markers.length == 1){
  42154. Common.updateVisible(marker, ,false)
  42155. } */
  42156. args.isRect || (measure.edges[measure.points.length - 1].visible = false);
  42157. //measure.continueDrag(measure.markers[measure.points.length-1], o )
  42158. };
  42159. measure.addEventListener('changeByHistory', changeByHistory);
  42160. this.viewer.scene.addMeasurement(measure);
  42161. return measure;
  42162. }
  42163. render() {
  42164. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  42165. if (this.scene.children.filter(e => e.visible).length == 0) return;
  42166. var renderer = o.renderer || this.viewer.renderer;
  42167. Potree.Utils.setCameraLayers(o.camera, ['measure']);
  42168. /* if(o.screenshot && this.viewer.fxaaPass.enabled){ //抗锯齿
  42169. this.viewer.ssaaRenderPass.sampleLevel = 4
  42170. this.viewer.composer.render(this.scene, o.camera );
  42171. }else{ */
  42172. viewer.dispatchEvent({
  42173. type: "render.begin2",
  42174. name: 'measure',
  42175. viewport: o.viewport,
  42176. renderer: o.renderer
  42177. });
  42178. renderer.render(this.scene, o.camera);
  42179. //}
  42180. }
  42181. }
  42182. ;
  42183. function updateAzimuth(viewer, measure) {
  42184. if (!measure.showAzimuth) return;
  42185. var azimuth = measure.azimuth;
  42186. var isOkay = measure.points.length === 2;
  42187. azimuth.node.visible = isOkay;
  42188. if (!azimuth.node.visible) {
  42189. return;
  42190. }
  42191. var camera = viewer.scene.getActiveCamera();
  42192. var renderAreaSize = viewer.renderer.getSize(new Vector2());
  42193. var width = renderAreaSize.width;
  42194. var height = renderAreaSize.height;
  42195. var [p0, p1] = measure.points;
  42196. var r = p0.position.distanceTo(p1.position);
  42197. var northVec = Utils.getNorthVec(p0.position, r, viewer.getProjection());
  42198. var northPos = p0.position.clone().add(northVec);
  42199. azimuth.center.position.copy(p0.position);
  42200. azimuth.center.scale.set(2, 2, 2);
  42201. azimuth.center.visible = false;
  42202. // azimuth.target.visible = false;
  42203. {
  42204. // north
  42205. azimuth.north.position.copy(northPos);
  42206. azimuth.north.scale.set(2, 2, 2);
  42207. var _distance = azimuth.north.position.distanceTo(camera.position);
  42208. var _pr = Utils.projectedRadius(1, camera, _distance, width, height);
  42209. var _scale = 5 / _pr;
  42210. azimuth.north.scale.set(_scale, _scale, _scale);
  42211. }
  42212. {
  42213. // target
  42214. azimuth.target.position.copy(p1.position);
  42215. azimuth.target.position.z = azimuth.north.position.z;
  42216. var _distance2 = azimuth.target.position.distanceTo(camera.position);
  42217. var _pr2 = Utils.projectedRadius(1, camera, _distance2, width, height);
  42218. var _scale2 = 5 / _pr2;
  42219. azimuth.target.scale.set(_scale2, _scale2, _scale2);
  42220. }
  42221. azimuth.circle.position.copy(p0.position);
  42222. azimuth.circle.scale.set(r, r, r);
  42223. azimuth.circle.material.resolution.set(width, height);
  42224. // to target
  42225. azimuth.centerToTarget.geometry.setPositions([0, 0, 0, ...p1.position.clone().sub(p0.position).toArray()]);
  42226. azimuth.centerToTarget.position.copy(p0.position);
  42227. azimuth.centerToTarget.geometry.verticesNeedUpdate = true;
  42228. azimuth.centerToTarget.geometry.computeBoundingSphere();
  42229. azimuth.centerToTarget.computeLineDistances();
  42230. azimuth.centerToTarget.material.resolution.set(width, height);
  42231. // to target ground
  42232. azimuth.centerToTargetground.geometry.setPositions([0, 0, 0, p1.position.x - p0.position.x, p1.position.y - p0.position.y, 0]);
  42233. azimuth.centerToTargetground.position.copy(p0.position);
  42234. azimuth.centerToTargetground.geometry.verticesNeedUpdate = true;
  42235. azimuth.centerToTargetground.geometry.computeBoundingSphere();
  42236. azimuth.centerToTargetground.computeLineDistances();
  42237. azimuth.centerToTargetground.material.resolution.set(width, height);
  42238. // to north
  42239. azimuth.centerToNorth.geometry.setPositions([0, 0, 0, northPos.x - p0.position.x, northPos.y - p0.position.y, 0]);
  42240. azimuth.centerToNorth.position.copy(p0.position);
  42241. azimuth.centerToNorth.geometry.verticesNeedUpdate = true;
  42242. azimuth.centerToNorth.geometry.computeBoundingSphere();
  42243. azimuth.centerToNorth.computeLineDistances();
  42244. azimuth.centerToNorth.material.resolution.set(width, height);
  42245. // label
  42246. var radians = Utils.computeAzimuth(p0.position, p1.position, viewer.getProjection());
  42247. var degrees = MathUtils.radToDeg(radians);
  42248. if (degrees < 0) {
  42249. degrees = 360 + degrees;
  42250. }
  42251. var txtDegrees = "".concat(degrees.toFixed(2), "\xB0");
  42252. var labelDir = northPos.clone().add(p1.position).multiplyScalar(0.5).sub(p0.position);
  42253. if (labelDir.length() > 0) {
  42254. labelDir.z = 0;
  42255. labelDir.normalize();
  42256. var labelVec = labelDir.clone().multiplyScalar(r);
  42257. var labelPos = p0.position.clone().add(labelVec);
  42258. azimuth.label.position.copy(labelPos);
  42259. }
  42260. azimuth.label.setText(txtDegrees);
  42261. var distance = azimuth.label.position.distanceTo(camera.position);
  42262. var pr = Utils.projectedRadius(1, camera, distance, width, height);
  42263. var scale = 70 / pr;
  42264. azimuth.label.scale.set(scale, scale, scale);
  42265. }
  42266. class ProfileTool extends EventDispatcher$1 {
  42267. constructor(viewer) {
  42268. super();
  42269. this.viewer = viewer;
  42270. this.renderer = viewer.renderer;
  42271. this.addEventListener('start_inserting_profile', e => {
  42272. this.viewer.dispatchEvent({
  42273. type: 'cancel_insertions'
  42274. });
  42275. });
  42276. this.scene = new Scene();
  42277. this.scene.name = 'scene_profile';
  42278. this.light = new PointLight(0xffffff, 1.0);
  42279. this.scene.add(this.light);
  42280. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  42281. this.onRemove = e => this.scene.remove(e.profile);
  42282. this.onAdd = e => this.scene.add(e.profile);
  42283. for (var profile of viewer.scene.profiles) {
  42284. this.onAdd({
  42285. profile: profile
  42286. });
  42287. }
  42288. viewer.addEventListener("update", this.update.bind(this));
  42289. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  42290. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  42291. viewer.scene.addEventListener('profile_added', this.onAdd);
  42292. viewer.scene.addEventListener('profile_removed', this.onRemove);
  42293. }
  42294. onSceneChange(e) {
  42295. if (e.oldScene) {
  42296. e.oldScene.removeEventListeners('profile_added', this.onAdd);
  42297. e.oldScene.removeEventListeners('profile_removed', this.onRemove);
  42298. }
  42299. e.scene.addEventListener('profile_added', this.onAdd);
  42300. e.scene.addEventListener('profile_removed', this.onRemove);
  42301. }
  42302. startInsertion() {
  42303. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  42304. var domElement = this.viewer.renderer.domElement;
  42305. var profile = new Profile();
  42306. profile.name = args.name || 'Profile';
  42307. this.dispatchEvent({
  42308. type: 'start_inserting_profile',
  42309. profile: profile
  42310. });
  42311. this.scene.add(profile);
  42312. var cancel = {
  42313. callback: null
  42314. };
  42315. var insertionCallback = e => {
  42316. if (e.button === MOUSE.LEFT) {
  42317. if (profile.points.length <= 1) {
  42318. var camera = this.viewer.scene.getActiveCamera();
  42319. var distance = camera.position.distanceTo(profile.points[0]);
  42320. var clientSize = this.viewer.renderer.getSize(new Vector2());
  42321. var pr = Utils.projectedRadius(1, camera, distance, clientSize.width, clientSize.height);
  42322. var width = 10 / pr;
  42323. profile.setWidth(width);
  42324. }
  42325. profile.addMarker(profile.points[profile.points.length - 1].clone());
  42326. this.viewer.inputHandler.startDragging(profile.spheres[profile.spheres.length - 1]);
  42327. } else if (e.button === MOUSE.RIGHT) {
  42328. cancel.callback();
  42329. }
  42330. };
  42331. cancel.callback = e => {
  42332. profile.removeMarker(profile.points.length - 1);
  42333. domElement.removeEventListener('mouseup', insertionCallback, false);
  42334. this.viewer.removeEventListener('cancel_insertions', cancel.callback);
  42335. };
  42336. this.viewer.addEventListener('cancel_insertions', cancel.callback);
  42337. domElement.addEventListener('mouseup', insertionCallback, false);
  42338. profile.addMarker(new Vector3(0, 0, 0));
  42339. this.viewer.inputHandler.startDragging(profile.spheres[profile.spheres.length - 1]);
  42340. this.viewer.scene.addProfile(profile);
  42341. return profile;
  42342. }
  42343. update() {
  42344. var camera = this.viewer.scene.getActiveCamera();
  42345. var profiles = this.viewer.scene.profiles;
  42346. var renderAreaSize = this.viewer.renderer.getSize(new Vector2());
  42347. var clientWidth = renderAreaSize.width;
  42348. var clientHeight = renderAreaSize.height;
  42349. this.light.position.copy(camera.position);
  42350. // make size independant of distance
  42351. for (var profile of profiles) {
  42352. for (var sphere of profile.spheres) {
  42353. var distance = camera.position.distanceTo(sphere.getWorldPosition(new Vector3()));
  42354. var pr = Utils.projectedRadius(1, camera, distance, clientWidth, clientHeight);
  42355. var scale = 15 / pr;
  42356. sphere.scale.set(scale, scale, scale);
  42357. }
  42358. }
  42359. }
  42360. render() {
  42361. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  42362. }
  42363. }
  42364. class ScreenBoxSelectTool extends EventDispatcher$1 {
  42365. constructor(viewer) {
  42366. super();
  42367. this.viewer = viewer;
  42368. this.scene = new Scene();
  42369. viewer.addEventListener("update", this.update.bind(this));
  42370. viewer.addEventListener("render.pass.perspective_overlay", this.render.bind(this));
  42371. viewer.addEventListener("scene_changed", this.onSceneChange.bind(this));
  42372. }
  42373. onSceneChange(scene) {
  42374. console.log("scene changed");
  42375. }
  42376. startInsertion() {
  42377. var domElement = this.viewer.renderer.domElement;
  42378. var volume = new BoxVolume();
  42379. volume.position.set(12345, 12345, 12345);
  42380. volume.showVolumeLabel = false;
  42381. volume.visible = false;
  42382. volume.update();
  42383. this.viewer.scene.addVolume(volume);
  42384. this.importance = 10;
  42385. var selectionBox = $("<div style=\"position: absolute; border: 2px solid white; pointer-events: none; border-style:dashed\"></div>");
  42386. $(domElement.parentElement).append(selectionBox);
  42387. selectionBox.css("right", "10px");
  42388. selectionBox.css("bottom", "10px");
  42389. var drag = e => {
  42390. volume.visible = true;
  42391. var mStart = e.drag.start;
  42392. var mEnd = e.drag.end;
  42393. var box2D = new Box2();
  42394. box2D.expandByPoint(mStart);
  42395. box2D.expandByPoint(mEnd);
  42396. selectionBox.css("left", "".concat(box2D.min.x, "px"));
  42397. selectionBox.css("top", "".concat(box2D.min.y, "px"));
  42398. selectionBox.css("width", "".concat(box2D.max.x - box2D.min.x, "px"));
  42399. selectionBox.css("height", "".concat(box2D.max.y - box2D.min.y, "px"));
  42400. var camera = e.viewer.scene.getActiveCamera();
  42401. var size = e.viewer.renderer.getSize(new Vector2());
  42402. var frustumSize = new Vector2(camera.right - camera.left, camera.top - camera.bottom);
  42403. var screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  42404. var ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height);
  42405. var diff = new Vector2().subVectors(e.drag.end, e.drag.start);
  42406. diff.divide(size).multiply(frustumSize);
  42407. volume.position.copy(ray.origin);
  42408. volume.up.copy(camera.up);
  42409. volume.rotation.copy(camera.rotation);
  42410. volume.scale.set(diff.x, diff.y, 1000 * 100);
  42411. e.consume();
  42412. };
  42413. var drop = e => {
  42414. this.importance = 0;
  42415. $(selectionBox).remove();
  42416. this.viewer.inputHandler.deselectAll();
  42417. this.viewer.inputHandler.toggleSelection(volume);
  42418. var camera = e.viewer.scene.getActiveCamera();
  42419. var size = e.viewer.renderer.getSize(new Vector2());
  42420. var screenCentroid = new Vector2().addVectors(e.drag.end, e.drag.start).multiplyScalar(0.5);
  42421. var ray = Utils.mouseToRay(screenCentroid, camera, size.width, size.height);
  42422. var line = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  42423. this.removeEventListener("drag", drag);
  42424. this.removeEventListener("drop", drop);
  42425. var allPointsNear = [];
  42426. var allPointsFar = [];
  42427. // TODO support more than one point cloud
  42428. for (var pointcloud of this.viewer.scene.pointclouds) {
  42429. if (!pointcloud.visible) {
  42430. continue;
  42431. }
  42432. var volCam = camera.clone();
  42433. volCam.left = -volume.scale.x / 2;
  42434. volCam.right = +volume.scale.x / 2;
  42435. volCam.top = +volume.scale.y / 2;
  42436. volCam.bottom = -volume.scale.y / 2;
  42437. volCam.near = -volume.scale.z / 2;
  42438. volCam.far = +volume.scale.z / 2;
  42439. volCam.rotation.copy(volume.rotation);
  42440. volCam.position.copy(volume.position);
  42441. volCam.updateMatrix();
  42442. volCam.updateMatrixWorld();
  42443. volCam.updateProjectionMatrix();
  42444. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  42445. var _ray = new Ray(volCam.getWorldPosition(new Vector3()), volCam.getWorldDirection(new Vector3()));
  42446. var rayInverse = new Ray(_ray.origin.clone().add(_ray.direction.clone().multiplyScalar(volume.scale.z)), _ray.direction.clone().multiplyScalar(-1));
  42447. var pickerSettings = {
  42448. width: 8,
  42449. height: 8,
  42450. pickWindowSize: 8,
  42451. all: true,
  42452. pickClipped: true,
  42453. pointSizeType: PointSizeType.FIXED,
  42454. pointSize: 1
  42455. };
  42456. var pointsNear = pointcloud.pick(viewer, volCam, _ray, pickerSettings);
  42457. volCam.rotateX(Math.PI);
  42458. volCam.updateMatrix();
  42459. volCam.updateMatrixWorld();
  42460. volCam.updateProjectionMatrix();
  42461. volCam.matrixWorldInverse.copy(volCam.matrixWorld).invert();
  42462. var pointsFar = pointcloud.pick(viewer, volCam, rayInverse, pickerSettings);
  42463. allPointsNear.push(...pointsNear);
  42464. allPointsFar.push(...pointsFar);
  42465. }
  42466. if (allPointsNear.length > 0 && allPointsFar.length > 0) {
  42467. var viewLine = new Line3(ray.origin, new Vector3().addVectors(ray.origin, ray.direction));
  42468. var closestOnLine = allPointsNear.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  42469. var closest = closestOnLine.sort((a, b) => ray.origin.distanceTo(a) - ray.origin.distanceTo(b))[0];
  42470. var farthestOnLine = allPointsFar.map(p => viewLine.closestPointToPoint(p.position, false, new Vector3()));
  42471. var farthest = farthestOnLine.sort((a, b) => ray.origin.distanceTo(b) - ray.origin.distanceTo(a))[0];
  42472. var distance = closest.distanceTo(farthest);
  42473. var centroid = new Vector3().addVectors(closest, farthest).multiplyScalar(0.5);
  42474. volume.scale.z = distance * 1.1;
  42475. volume.position.copy(centroid);
  42476. }
  42477. volume.clip = true;
  42478. };
  42479. this.addEventListener("drag", drag);
  42480. this.addEventListener("drop", drop);
  42481. viewer.inputHandler.addInputListener(this);
  42482. return volume;
  42483. }
  42484. update(e) {
  42485. //console.log(e.delta)
  42486. }
  42487. render() {
  42488. this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  42489. }
  42490. }
  42491. class SpotLightHelper$1 extends Object3D {
  42492. constructor(light, color) {
  42493. super();
  42494. this.light = light;
  42495. this.color = color;
  42496. //this.up.set(0, 0, 1);
  42497. this.updateMatrix();
  42498. this.updateMatrixWorld();
  42499. {
  42500. // SPHERE
  42501. var sg = new SphereGeometry(1, 32, 32);
  42502. var sm = new MeshNormalMaterial();
  42503. this.sphere = new Mesh(sg, sm);
  42504. this.sphere.scale.set(0.5, 0.5, 0.5);
  42505. this.add(this.sphere);
  42506. }
  42507. {
  42508. // LINES
  42509. var positions = new Float32Array([+0, +0, +0, +0, +0, -1, +0, +0, +0, -1, -1, -1, +0, +0, +0, +1, -1, -1, +0, +0, +0, +1, +1, -1, +0, +0, +0, -1, +1, -1, -1, -1, -1, +1, -1, -1, +1, -1, -1, +1, +1, -1, +1, +1, -1, -1, +1, -1, -1, +1, -1, -1, -1, -1]);
  42510. var geometry = new BufferGeometry();
  42511. geometry.setAttribute("position", new BufferAttribute(positions, 3));
  42512. var material = new LineBasicMaterial();
  42513. this.frustum = new LineSegments(geometry, material);
  42514. this.add(this.frustum);
  42515. }
  42516. this.update();
  42517. }
  42518. update() {
  42519. this.light.updateMatrix();
  42520. this.light.updateMatrixWorld();
  42521. var position = this.light.position;
  42522. var target = new Vector3().addVectors(this.light.position, this.light.getWorldDirection(new Vector3()).multiplyScalar(-1));
  42523. var quat = new Quaternion().setFromRotationMatrix(new Matrix4().lookAt(position, target, new Vector3(0, 0, 1)));
  42524. this.setRotationFromQuaternion(quat);
  42525. this.position.copy(position);
  42526. var coneLength = this.light.distance > 0 ? this.light.distance : 1000;
  42527. var coneWidth = coneLength * Math.tan(this.light.angle * 0.5);
  42528. this.frustum.scale.set(coneWidth, coneWidth, coneLength);
  42529. }
  42530. }
  42531. //问题:如何转换到世界坐标?(缩放方向有bug。)
  42532. //add-------------------------------------
  42533. var OpaWhenNotSelect = 0.6;
  42534. var ScaleRatio = 3;
  42535. var OutlineColor = 0x666666;
  42536. //----------------------------------------
  42537. var hideFocusHandles = true; //add
  42538. class TransformationTool extends EventDispatcher {
  42539. constructor(viewer) {
  42540. super();
  42541. this.viewer = viewer;
  42542. this.modesEnabled = {}; //add
  42543. this.style = 'singleMode'; //建mesh时按照singleModes建的
  42544. this.scene = new Scene();
  42545. this.selection = [];
  42546. this.pivot = new Vector3();
  42547. this.dragging = false;
  42548. this.showPickVolumes = false;
  42549. this.viewer.inputHandler.registerInteractiveScene(this.scene);
  42550. this.viewer.inputHandler.addEventListener('selection_changed', e => {
  42551. /* for(let selected of this.selection){ //若不删除,应该会穿过选中的物体选到别的而不是取消选择
  42552. this.viewer.inputHandler.blacklist.delete(selected);
  42553. } */
  42554. this.selection = e.selection;
  42555. /* for(let selected of this.selection){
  42556. this.viewer.inputHandler.blacklist.add(selected);
  42557. } */
  42558. });
  42559. this.viewer.addEventListener('global_touchstart', e => {
  42560. //add
  42561. this.update();
  42562. });
  42563. this.viewer.addEventListener('global_mousemove', e => {
  42564. //add
  42565. this.onPointerMove();
  42566. });
  42567. var red = Potree.config.axis.x.color;
  42568. var green = Potree.config.axis.y.color;
  42569. var blue = Potree.config.axis.z.color;
  42570. var white = Potree.config.axis.xyz.color;
  42571. this.activeHandle = null;
  42572. this.scaleHandles = {
  42573. "scale.x+": {
  42574. name: "scale.x+",
  42575. node: new Object3D(),
  42576. color: red,
  42577. alignment: [+1, +0, +0]
  42578. },
  42579. "scale.x-": {
  42580. name: "scale.x-",
  42581. node: new Object3D(),
  42582. color: red,
  42583. alignment: [-1, +0, +0]
  42584. },
  42585. "scale.y+": {
  42586. name: "scale.y+",
  42587. node: new Object3D(),
  42588. color: green,
  42589. alignment: [+0, +1, +0]
  42590. },
  42591. "scale.y-": {
  42592. name: "scale.y-",
  42593. node: new Object3D(),
  42594. color: green,
  42595. alignment: [+0, -1, +0]
  42596. },
  42597. "scale.z+": {
  42598. name: "scale.z+",
  42599. node: new Object3D(),
  42600. color: blue,
  42601. alignment: [+0, +0, +1]
  42602. },
  42603. "scale.z-": {
  42604. name: "scale.z-",
  42605. node: new Object3D(),
  42606. color: blue,
  42607. alignment: [+0, +0, -1]
  42608. },
  42609. "lines": {
  42610. name: 'lines',
  42611. node: new Object3D(),
  42612. dontScale: true
  42613. } //add
  42614. };
  42615. this.focusHandles = {
  42616. "focus.x+": {
  42617. name: "focus.x+",
  42618. node: new Object3D(),
  42619. color: red,
  42620. alignment: [+1, +0, +0]
  42621. },
  42622. "focus.x-": {
  42623. name: "focus.x-",
  42624. node: new Object3D(),
  42625. color: red,
  42626. alignment: [-1, +0, +0]
  42627. },
  42628. "focus.y+": {
  42629. name: "focus.y+",
  42630. node: new Object3D(),
  42631. color: green,
  42632. alignment: [+0, +1, +0]
  42633. },
  42634. "focus.y-": {
  42635. name: "focus.y-",
  42636. node: new Object3D(),
  42637. color: green,
  42638. alignment: [+0, -1, +0]
  42639. },
  42640. "focus.z+": {
  42641. name: "focus.z+",
  42642. node: new Object3D(),
  42643. color: blue,
  42644. alignment: [+0, +0, +1]
  42645. },
  42646. "focus.z-": {
  42647. name: "focus.z-",
  42648. node: new Object3D(),
  42649. color: blue,
  42650. alignment: [+0, +0, -1]
  42651. }
  42652. };
  42653. this.translationHandles = {
  42654. "translation.x": {
  42655. name: "translation.x",
  42656. node: new Object3D(),
  42657. color: red,
  42658. alignment: [1, 0, 0]
  42659. },
  42660. "translation.y": {
  42661. name: "translation.y",
  42662. node: new Object3D(),
  42663. color: green,
  42664. alignment: [0, 1, 0]
  42665. },
  42666. "translation.z": {
  42667. name: "translation.z",
  42668. node: new Object3D(),
  42669. color: blue,
  42670. alignment: [0, 0, 1]
  42671. },
  42672. //add
  42673. 'translation.xyz': {
  42674. name: "translation.xyz",
  42675. node: new Object3D(),
  42676. color: white,
  42677. alignment: [0, 0, 0],
  42678. alignment2: [1, 1, 1]
  42679. },
  42680. 'translation.plane.xy': {
  42681. name: "translation.plane.xy",
  42682. node: new Object3D(),
  42683. color: blue,
  42684. alignment: [0, 0, 1],
  42685. alignment2: [1, 1, 0]
  42686. },
  42687. 'translation.plane.yz': {
  42688. name: "translation.plane.yz",
  42689. node: new Object3D(),
  42690. color: red,
  42691. alignment: [1, 0, 0],
  42692. alignment2: [0, 1, 1]
  42693. },
  42694. 'translation.plane.xz': {
  42695. name: "translation.plane.xz",
  42696. node: new Object3D(),
  42697. color: green,
  42698. alignment: [0, 1, 0],
  42699. alignment2: [1, 0, 1]
  42700. }
  42701. };
  42702. this.rotationHandles = {
  42703. "rotation.x": {
  42704. name: "rotation.x",
  42705. node: new Object3D(),
  42706. color: red,
  42707. alignment: [1, 0, 0]
  42708. },
  42709. "rotation.y": {
  42710. name: "rotation.y",
  42711. node: new Object3D(),
  42712. color: green,
  42713. alignment: [0, 1, 0]
  42714. },
  42715. "rotation.z": {
  42716. name: "rotation.z",
  42717. node: new Object3D(),
  42718. color: blue,
  42719. alignment: [0, 0, 1]
  42720. }
  42721. };
  42722. this.handles = Object.assign({}, this.scaleHandles, hideFocusHandles ? {} : this.focusHandles, this.translationHandles, this.rotationHandles);
  42723. this.pickVolumes = [];
  42724. this.initializeScaleHandles();
  42725. this.initializeFocusHandles();
  42726. this.initializeTranslationHandles();
  42727. this.initializeRotationHandles();
  42728. var boxFrameGeometry = new Geometry();
  42729. {
  42730. // bottom
  42731. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  42732. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  42733. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  42734. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  42735. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  42736. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  42737. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  42738. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  42739. // top
  42740. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  42741. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  42742. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  42743. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  42744. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  42745. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  42746. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  42747. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  42748. // sides
  42749. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, 0.5));
  42750. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, 0.5));
  42751. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, 0.5));
  42752. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, 0.5));
  42753. boxFrameGeometry.vertices.push(new Vector3(0.5, -0.5, -0.5));
  42754. boxFrameGeometry.vertices.push(new Vector3(0.5, 0.5, -0.5));
  42755. boxFrameGeometry.vertices.push(new Vector3(-0.5, -0.5, -0.5));
  42756. boxFrameGeometry.vertices.push(new Vector3(-0.5, 0.5, -0.5));
  42757. }
  42758. this.frame = new LineSegments(boxFrameGeometry, new LineBasicMaterial({
  42759. color: 0xffff00
  42760. }));
  42761. this.scene.add(this.frame);
  42762. //------------------add-----------------------
  42763. this.setModeEnable(['scale', 'translation', 'rotation']);
  42764. Potree.Utils.setObjectLayers(this.scene, 'transformationTool');
  42765. this.scene.traverse(e => {
  42766. e.pickDontCheckDis = true; //pick时不需要识别是否在点云之上
  42767. });
  42768. {
  42769. var exist = object => {
  42770. //是否没被删除(暂时不考虑换了parent)
  42771. while (object.parent) {
  42772. object = object.parent;
  42773. }
  42774. if (object instanceof Scene) {
  42775. return true;
  42776. }
  42777. };
  42778. this.history = new History({
  42779. //也可以写到全局,但需要加个判断物品是否存在的函数
  42780. applyData: data => {
  42781. if (exist(data.object)) {
  42782. //viewer.scene.volumes.includes(data.box) //或许还要识别是否matrixAuto
  42783. data.matrix.decompose(data.object.position, data.object.quaternion, data.object.scale);
  42784. this.dispatchEvent('changeByHistory');
  42785. viewer.dispatchEvent('content_changed');
  42786. return true;
  42787. }
  42788. },
  42789. getData: data => {
  42790. return data;
  42791. }
  42792. });
  42793. this.addEventListener('transformed', e => {
  42794. var object = viewer.transformationTool.selection[0];
  42795. this.history.beforeChange({
  42796. object,
  42797. matrix: e.matrixBefore.clone()
  42798. });
  42799. this.viewer.dispatchEvent('content_changed');
  42800. });
  42801. this.addEventListener('stopDrag', e => {
  42802. var object = viewer.transformationTool.selection[0];
  42803. object && this.history.afterChange({
  42804. object,
  42805. matrix: object.matrix.clone()
  42806. });
  42807. });
  42808. /* viewer.inputHandler.addEventListener('keydown', (e)=>{
  42809. if(e.keyCode == 90 && e.event.ctrlKey){//Z
  42810. this.history.undo()
  42811. }else if(e.keyCode == 89 && e.event.ctrlKey){//Y
  42812. this.history.redo()
  42813. }
  42814. }) */
  42815. }
  42816. }
  42817. setModeEnable() {
  42818. var enableModes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  42819. //xzw add
  42820. var length = 0;
  42821. ['translation', 'scale', 'rotation'].forEach(mode => {
  42822. var handels = this[mode + 'Handles'];
  42823. var enable = enableModes.includes(mode);
  42824. for (var o in handels) {
  42825. Potree.Utils.updateVisible(handels[o].node, 'modeForce', !!enable);
  42826. }
  42827. this.modesEnabled[mode] = !!enable;
  42828. enable && length++;
  42829. });
  42830. if (this.style == 'singleMode' && length > 1) {
  42831. this.changeStyle('mixedModes');
  42832. } else if (this.style == 'mixedModes' && length == 1) {
  42833. this.changeStyle('singleMode');
  42834. }
  42835. }
  42836. changeStyle(style) {
  42837. // 切换单个mode & 多个mode混合 风格(因多个混合比较拥挤,需要做调整)
  42838. var s1 = style == 'singleMode' ? 30 : 25;
  42839. var s2 = style == 'singleMode' ? 15 : 10;
  42840. ['x', 'y', 'z'].forEach(axis => {
  42841. this.translationHandles['translation.' + axis].node.children.forEach(mesh => {
  42842. if (mesh.name.includes('arrow')) {
  42843. Potree.Utils.updateVisible(mesh, 'modeStyle', style == 'singleMode');
  42844. } else if (mesh.name.includes('handle')) {
  42845. mesh.material.lineWidth = style == 'singleMode' ? 5 : 7;
  42846. }
  42847. });
  42848. this.rotationHandles['rotation.' + axis].translateNode.scale.set(s1, s1, s1);
  42849. });
  42850. ['xy', 'yz', 'xz'].forEach(axis => {
  42851. var handle = this.translationHandles['translation.plane.' + axis];
  42852. handle.node.children[0].scale.set(s2, s2, s2);
  42853. handle.node.children[0].position.fromArray(handle.alignment2).multiplyScalar(s2 * 1.5);
  42854. });
  42855. Potree.Utils.updateVisible(this.scaleHandles['lines'].node, 'modeStyle', style == 'singleMode');
  42856. this.style = style;
  42857. }
  42858. initializeTranslationHandles() {
  42859. var _this = this;
  42860. //大改
  42861. var boxGeometry = new BoxGeometry(1, 1, 1);
  42862. var length = 100,
  42863. arrowRadius = 4,
  42864. arrowHeight = 10;
  42865. var arrowGeometry = new CylinderBufferGeometry(0, arrowRadius, arrowHeight, 12, 1, false); //add 箭头朝(0,1,0)
  42866. var arrowInitialQua = new Quaternion().setFromAxisAngle(new Vector3(1, 0, 0), -Math.PI / 2); //先将qua旋转到朝向0,0,-1, 因为一般quaternion不设置时默认表示朝向0,0,-1,
  42867. var octahedronGeometry = new OctahedronBufferGeometry(5, 0);
  42868. var planeGeometry = new PlaneBufferGeometry(1, 1);
  42869. var _loop = function _loop(handleName) {
  42870. var handle = _this.handles[handleName];
  42871. var node = handle.node;
  42872. _this.scene.add(node);
  42873. node.name = handleName; //add
  42874. var alignment = new Vector3(...handle.alignment);
  42875. var geometry,
  42876. mesh,
  42877. pickVolume,
  42878. meshScale,
  42879. pickScale,
  42880. rotation,
  42881. position,
  42882. lookAtPoint,
  42883. hasPick = true,
  42884. meshPickable = false,
  42885. renderOrder;
  42886. var matProp = {
  42887. color: handle.color,
  42888. opacity: OpaWhenNotSelect,
  42889. transparent: true,
  42890. side: handleName.includes('plane') ? DoubleSide : FrontSide
  42891. };
  42892. var material = new MeshBasicMaterial(matProp);
  42893. var pickMaterial = new MeshNormalMaterial({
  42894. opacity: 0.2,
  42895. transparent: true,
  42896. visible: _this.showPickVolumes
  42897. });
  42898. if (handleName.includes('xyz')) {
  42899. geometry = octahedronGeometry;
  42900. meshPickable = true;
  42901. renderOrder = 12;
  42902. } else if (handleName.includes('plane')) {
  42903. geometry = planeGeometry;
  42904. meshPickable = true;
  42905. position = new Vector3(...handle.alignment2);
  42906. lookAtPoint = alignment;
  42907. if (handleName.includes('xy')) {} else if (handleName.includes('yz')) {} else if (handleName.includes('xz')) {}
  42908. } else {
  42909. geometry = boxGeometry;
  42910. var point = new Vector3(0, 0, length / 2); //new THREE.Vector3().copy(alignment).multiplyScalar(length/2)
  42911. mesh = LineDraw.createFatLine([point, point.clone().negate()], {
  42912. lineWidth: 6,
  42913. mat: new LineDraw.createFatLineMat(matProp)
  42914. });
  42915. lookAtPoint = alignment;
  42916. renderOrder = 10;
  42917. pickScale = new Vector3(4, 4, length + arrowHeight * 2); //pickScale = new THREE.Vector3(4, 4, 1.2)
  42918. {
  42919. var arrow = new Mesh(arrowGeometry, material);
  42920. arrow.name = "".concat(handleName, ".arrow");
  42921. arrow.renderOrder = 11;
  42922. arrow.position.set(...handle.alignment).multiplyScalar(length / 2 + arrowHeight / 2);
  42923. arrow.lookAt(0, 0, 0);
  42924. node.add(arrow);
  42925. var arrow2 = arrow.clone();
  42926. arrow2.position.negate();
  42927. arrow2.lookAt(0, 0, 0);
  42928. node.add(arrow2);
  42929. arrow.quaternion.multiply(arrowInitialQua); //乘上初始旋转
  42930. arrow2.quaternion.multiply(arrowInitialQua);
  42931. }
  42932. }
  42933. mesh || (mesh = new Mesh(geometry, material));
  42934. mesh.name = "".concat(handleName, ".handle");
  42935. node.add(mesh);
  42936. renderOrder && (mesh.renderOrder = renderOrder);
  42937. meshScale && mesh.scale.copy(meshScale);
  42938. rotation && mesh.rotation.copy(rotation);
  42939. lookAtPoint && mesh.lookAt(lookAtPoint);
  42940. position && mesh.position.copy(position);
  42941. if (!meshPickable && hasPick) {
  42942. pickVolume = new Mesh(geometry, pickMaterial);
  42943. pickScale && pickVolume.scale.copy(pickScale);
  42944. } else if (hasPick && meshPickable) {
  42945. pickVolume = mesh;
  42946. }
  42947. if (pickVolume) {
  42948. if (mesh != pickVolume) {
  42949. mesh.add(pickVolume);
  42950. pickVolume.name = "".concat(handleName, ".pick_volume");
  42951. } else {
  42952. pickVolume.name += ' & pick_volume';
  42953. }
  42954. pickVolume.handle = handleName;
  42955. _this.pickVolumes.push(pickVolume);
  42956. }
  42957. node.setOpacity = target => {
  42958. if (handleName.includes('plane')) {
  42959. var more = 1.5; //减掉更多,使min更低,max还是1
  42960. target = 1 - (1 - target) * more;
  42961. }
  42962. var opacity = {
  42963. x: material.opacity
  42964. };
  42965. var t = new TWEEN.Tween(opacity).to({
  42966. x: target
  42967. }, 0);
  42968. t.onUpdate(() => {
  42969. mesh.visible = opacity.x > 0;
  42970. pickVolume && (pickVolume.visible = opacity.x > 0);
  42971. material.opacity = opacity.x;
  42972. mesh.material.opacity = opacity.x;
  42973. //outlineMaterial.opacity = opacity.x;
  42974. pickMaterial.opacity = opacity.x * 0.5;
  42975. });
  42976. t.start();
  42977. };
  42978. pickVolume.addEventListener("drag", e => {
  42979. _this.dragTranslationHandle(e);
  42980. });
  42981. pickVolume.addEventListener("drop", e => {
  42982. _this.dropTranslationHandle(e);
  42983. });
  42984. };
  42985. for (var handleName of Object.keys(this.translationHandles)) {
  42986. _loop(handleName);
  42987. }
  42988. }
  42989. initializeScaleHandles() {
  42990. var _this2 = this;
  42991. var sgSphere = new SphereGeometry(1, 32, 32);
  42992. var sgLowPolySphere = new SphereGeometry(1, 16, 16);
  42993. var _loop2 = function _loop2() {
  42994. var handle = _this2.scaleHandles[handleName];
  42995. var node = handle.node;
  42996. node.name = handleName; //add
  42997. _this2.scene.add(node);
  42998. if (handleName == 'lines') {
  42999. //add
  43000. ['x', 'y', 'z'].forEach(axis => {
  43001. var handle1_ = _this2.scaleHandles['scale.' + axis + '+'];
  43002. var handle2_ = _this2.scaleHandles['scale.' + axis + '-'];
  43003. var line = LineDraw.createFatLine([new Vector3().fromArray(handle1_.alignment).multiplyScalar(0.5), new Vector3().fromArray(handle2_.alignment).multiplyScalar(0.5)], {
  43004. color: handle1_.color,
  43005. lineWidth: 4
  43006. } // , dontAlwaysSeen:true
  43007. );
  43008. node.add(line);
  43009. });
  43010. node.setOpacity = opacity => {
  43011. opacity *= 0.6;
  43012. node.children.forEach(e => e.material.opacity = opacity);
  43013. };
  43014. return 1; // continue
  43015. }
  43016. node.position.set(...handle.alignment).multiplyScalar(0.5);
  43017. var material = new MeshBasicMaterial({
  43018. color: handle.color,
  43019. side: DoubleSide,
  43020. //xzw add
  43021. opacity: OpaWhenNotSelect,
  43022. transparent: true
  43023. });
  43024. var outlineMaterial = new MeshBasicMaterial({
  43025. color: OutlineColor,
  43026. side: BackSide,
  43027. opacity: OpaWhenNotSelect,
  43028. transparent: true
  43029. });
  43030. var pickMaterial = new MeshNormalMaterial({
  43031. opacity: 0.2,
  43032. transparent: true,
  43033. side: DoubleSide,
  43034. //xzw add for orthoCam, 缩小画面时因球体放大导致到相机背面去了而看不到球体正面
  43035. visible: _this2.showPickVolumes
  43036. });
  43037. var sphere = new Mesh(sgSphere, material);
  43038. sphere.scale.set(5, 5, 5);
  43039. sphere.name = "".concat(handleName, ".handle");
  43040. node.add(sphere);
  43041. sphere.renderOrder = 10;
  43042. /* let outline = new THREE.Mesh(sgSphere, outlineMaterial);
  43043. outline.scale.set(1.1, 1.1, 1.1);
  43044. outline.name = `${handleName}.outline`;
  43045. sphere.add(outline); */
  43046. var pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  43047. pickSphere.name = "".concat(handleName, ".pick_volume");
  43048. pickSphere.scale.set(1.5, 1.5, 1.5);
  43049. sphere.add(pickSphere);
  43050. pickSphere.handle = handleName;
  43051. _this2.pickVolumes.push(pickSphere);
  43052. node.setOpacity = target => {
  43053. var opacity = {
  43054. x: material.opacity
  43055. };
  43056. var t = new TWEEN.Tween(opacity).to({
  43057. x: target
  43058. }, 0); //xzw改 原100毫秒,因为太慢容易选错
  43059. t.onUpdate(() => {
  43060. sphere.visible = opacity.x > 0;
  43061. pickSphere.visible = opacity.x > 0;
  43062. material.opacity = opacity.x;
  43063. outlineMaterial.opacity = opacity.x;
  43064. pickSphere.material.opacity = opacity.x * 0.5;
  43065. });
  43066. t.start();
  43067. };
  43068. pickSphere.addEventListener("drag", e => _this2.dragScaleHandle(e));
  43069. pickSphere.addEventListener("drop", e => _this2.dropScaleHandle(e));
  43070. pickSphere.addEventListener("mouseover", e => {
  43071. //node.setOpacity(1);
  43072. });
  43073. pickSphere.addEventListener("click", e => {
  43074. //e.consume();
  43075. });
  43076. pickSphere.addEventListener("mouseleave", e => {
  43077. //node.setOpacity(OpaWhenNotSelect);
  43078. });
  43079. };
  43080. for (var handleName of Object.keys(this.scaleHandles)) {
  43081. if (_loop2()) continue;
  43082. }
  43083. }
  43084. initializeRotationHandles() {
  43085. var _this3 = this;
  43086. var boldAdjust = 2.3;
  43087. var torusGeometry = new TorusGeometry(1.3, boldAdjust * 0.015, 8, 64, Math.PI / 2);
  43088. //let outlineGeometry = new THREE.TorusGeometry(1, boldAdjust * 0.018, 8, 64, Math.PI / 2);
  43089. var pickGeometry = new TorusGeometry(1.3, boldAdjust * 0.06, 6, 4, Math.PI / 2);
  43090. var _loop3 = function _loop3() {
  43091. var handle = _this3.handles[handleName];
  43092. var node = handle.node;
  43093. _this3.scene.add(node);
  43094. node.name = handleName; //add
  43095. var material = new MeshBasicMaterial({
  43096. color: handle.color,
  43097. opacity: OpaWhenNotSelect,
  43098. transparent: true
  43099. });
  43100. /* let outlineMaterial = new THREE.MeshBasicMaterial({
  43101. color: OutlineColor,
  43102. side: THREE.BackSide,
  43103. opacity: OpaWhenNotSelect,
  43104. transparent: true
  43105. }); */
  43106. var pickMaterial = new MeshNormalMaterial({
  43107. opacity: 0.2,
  43108. transparent: true,
  43109. visible: _this3.showPickVolumes
  43110. });
  43111. var box = new Mesh(torusGeometry, material);
  43112. box.name = "".concat(handleName, ".handle");
  43113. box.scale.set(30, 30, 30);
  43114. box.lookAt(new Vector3(...handle.alignment));
  43115. node.add(box);
  43116. handle.translateNode = box;
  43117. /* let outline = new THREE.Mesh(outlineGeometry, outlineMaterial);
  43118. outline.name = `${handleName}.outline`;
  43119. outline.scale.set(1, 1, 1);
  43120. outline.renderOrder = 0;
  43121. box.add(outline);
  43122. */
  43123. var pickVolume = new Mesh(pickGeometry, pickMaterial);
  43124. pickVolume.name = "".concat(handleName, ".pick_volume");
  43125. pickVolume.scale.set(1, 1, 1);
  43126. pickVolume.handle = handleName;
  43127. box.add(pickVolume);
  43128. _this3.pickVolumes.push(pickVolume);
  43129. node.setOpacity = target => {
  43130. var opacity = {
  43131. x: material.opacity
  43132. };
  43133. var t = new TWEEN.Tween(opacity).to({
  43134. x: target
  43135. }, 0);
  43136. t.onUpdate(() => {
  43137. box.visible = opacity.x > 0;
  43138. pickVolume.visible = opacity.x > 0;
  43139. material.opacity = opacity.x;
  43140. //outlineMaterial.opacity = opacity.x;
  43141. pickMaterial.opacity = opacity.x * 0.5;
  43142. });
  43143. t.start();
  43144. };
  43145. //pickVolume.addEventListener("mouseover", (e) => {
  43146. // //let a = this.viewer.scene.getActiveCamera().getWorldDirection(new THREE.Vector3()).dot(pickVolume.getWorldDirection(new THREE.Vector3()));
  43147. // console.log(pickVolume.getWorldDirection(new THREE.Vector3()));
  43148. //});
  43149. pickVolume.addEventListener("drag", e => {
  43150. _this3.dragRotationHandle(e);
  43151. });
  43152. pickVolume.addEventListener("drop", e => {
  43153. _this3.dropRotationHandle(e);
  43154. });
  43155. };
  43156. for (var handleName of Object.keys(this.rotationHandles)) {
  43157. _loop3();
  43158. }
  43159. }
  43160. initializeFocusHandles() {
  43161. var _this4 = this;
  43162. if (hideFocusHandles) return; //add
  43163. //let sgBox = new THREE.BoxGeometry(1, 1, 1);
  43164. var sgPlane = new PlaneGeometry(4, 4, 1, 1);
  43165. var sgLowPolySphere = new SphereGeometry(1, 16, 16);
  43166. var texture = new TextureLoader().load("".concat(exports.resourcePath, "/icons/eye_2.png"));
  43167. var _loop4 = function _loop4() {
  43168. var handle = _this4.focusHandles[handleName];
  43169. var node = handle.node;
  43170. _this4.scene.add(node);
  43171. var align = handle.alignment;
  43172. node.name = handleName; //add
  43173. //node.lookAt(new THREE.Vector3().addVectors(node.position, new THREE.Vector3(...align)));
  43174. node.lookAt(new Vector3(...align));
  43175. var off = 0.8;
  43176. if (align[0] === 1) {
  43177. node.position.set(1, off, -off).multiplyScalar(0.5);
  43178. node.rotation.z = Math.PI / 2;
  43179. } else if (align[0] === -1) {
  43180. node.position.set(-1, -off, -off).multiplyScalar(0.5);
  43181. node.rotation.z = Math.PI / 2;
  43182. } else if (align[1] === 1) {
  43183. node.position.set(-off, 1, -off).multiplyScalar(0.5);
  43184. node.rotation.set(Math.PI / 2, Math.PI, 0.0);
  43185. } else if (align[1] === -1) {
  43186. node.position.set(off, -1, -off).multiplyScalar(0.5);
  43187. node.rotation.set(Math.PI / 2, 0.0, 0.0);
  43188. } else if (align[2] === 1) {
  43189. node.position.set(off, off, 1).multiplyScalar(0.5);
  43190. } else if (align[2] === -1) {
  43191. node.position.set(-off, off, -1).multiplyScalar(0.5);
  43192. }
  43193. var material = new MeshBasicMaterial({
  43194. color: handle.color,
  43195. opacity: 0,
  43196. transparent: true,
  43197. map: texture
  43198. });
  43199. //let outlineMaterial = new THREE.MeshBasicMaterial({
  43200. // color: 0x000000,
  43201. // side: THREE.BackSide,
  43202. // opacity: 0,
  43203. // transparent: true});
  43204. var pickMaterial = new MeshNormalMaterial({
  43205. //opacity: 0,
  43206. transparent: true,
  43207. visible: _this4.showPickVolumes
  43208. });
  43209. var box = new Mesh(sgPlane, material);
  43210. box.name = "".concat(handleName, ".handle");
  43211. box.scale.set(1.5, 1.5, 1.5);
  43212. box.position.set(0, 0, 0);
  43213. box.visible = false;
  43214. node.add(box);
  43215. //handle.focusNode = box;
  43216. //let outline = new THREE.Mesh(sgPlane, outlineMaterial);
  43217. //outline.scale.set(1.4, 1.4, 1.4);
  43218. //outline.name = `${handleName}.outline`;
  43219. //box.add(outline);
  43220. var pickSphere = new Mesh(sgLowPolySphere, pickMaterial);
  43221. pickSphere.name = "".concat(handleName, ".pick_volume");
  43222. pickSphere.scale.set(2, 2, 2);
  43223. box.add(pickSphere);
  43224. pickSphere.handle = handleName;
  43225. _this4.pickVolumes.push(pickSphere);
  43226. node.setOpacity = target => {
  43227. var opacity = {
  43228. x: material.opacity
  43229. };
  43230. var t = new TWEEN.Tween(opacity).to({
  43231. x: target
  43232. }, 0);
  43233. t.onUpdate(() => {
  43234. pickSphere.visible = opacity.x > 0;
  43235. box.visible = opacity.x > 0;
  43236. material.opacity = opacity.x;
  43237. //outlineMaterial.opacity = opacity.x;
  43238. pickSphere.material.opacity = opacity.x * 0.5;
  43239. });
  43240. t.start();
  43241. };
  43242. //pickSphere.addEventListener("drag", e => {});
  43243. pickSphere.addEventListener("mouseup", e => {
  43244. //e.consume();
  43245. });
  43246. pickSphere.addEventListener("mousedown", e => {
  43247. //e.consume();
  43248. });
  43249. pickSphere.addEventListener("click", e => {
  43250. //e.consume();
  43251. var selected = _this4.selection[0];
  43252. var maxScale = Math.max(...selected.scale.toArray());
  43253. var minScale = Math.min(...selected.scale.toArray());
  43254. var handleLength = Math.abs(selected.scale.dot(new Vector3(...handle.alignment)));
  43255. var alignment = new Vector3(...handle.alignment).multiplyScalar(2 * maxScale / handleLength);
  43256. alignment.applyMatrix4(selected.matrixWorld);
  43257. var newCamPos = alignment;
  43258. var newCamTarget = selected.getWorldPosition(new Vector3());
  43259. Utils.moveTo(_this4.viewer.scene, newCamPos, newCamTarget);
  43260. });
  43261. pickSphere.addEventListener("mouseover", e => {
  43262. //box.setOpacity(1);
  43263. });
  43264. pickSphere.addEventListener("mouseleave", e => {
  43265. //box.setOpacity(OpaWhenNotSelect);
  43266. });
  43267. };
  43268. for (var handleName of Object.keys(this.focusHandles)) {
  43269. _loop4();
  43270. }
  43271. }
  43272. dragRotationHandle(e) {
  43273. var drag = e.drag;
  43274. var handle = this.activeHandle;
  43275. var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera();
  43276. if (!handle || !handle.name.includes('rotation')) {
  43277. return;
  43278. }
  43279. ;
  43280. var localNormal = new Vector3(...handle.alignment);
  43281. var n = new Vector3();
  43282. n.copy(new Vector4(...localNormal.toArray(), 0).applyMatrix4(handle.node.matrixWorld));
  43283. n.normalize();
  43284. if (!drag.intersectionStart) {
  43285. //this.viewer.scene.scene.remove(this.debug);
  43286. //this.debug = new THREE.Object3D();
  43287. //this.viewer.scene.scene.add(this.debug);
  43288. //Utils.debugSphere(this.debug, drag.location, 3, 0xaaaaaa);
  43289. //let debugEnd = drag.location.clone().add(n.clone().multiplyScalar(20));
  43290. //Utils.debugLine(this.debug, drag.location, debugEnd, 0xff0000);
  43291. drag.intersectionStart = drag.location;
  43292. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  43293. drag.handle = handle;
  43294. var plane = new Plane().setFromNormalAndCoplanarPoint(n, drag.intersectionStart);
  43295. drag.dragPlane = plane;
  43296. drag.pivot = drag.intersectionStart;
  43297. } else {
  43298. handle = drag.handle;
  43299. }
  43300. if (!drag.dragPlane) return; //xzw add 因有时候没有
  43301. this.dragging = true;
  43302. var pointer = this.viewer.inputHandler.pointer;
  43303. var domElement = this.viewer.renderer.domElement;
  43304. var ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  43305. var I = ray.intersectPlane(drag.dragPlane, new Vector3());
  43306. if (I) {
  43307. var center = this.scene.getWorldPosition(new Vector3()); //bounding中心
  43308. var from = drag.pivot;
  43309. var to = I;
  43310. var v1 = from.clone().sub(center).normalize();
  43311. var v2 = to.clone().sub(center).normalize();
  43312. var angle = Math.acos(v1.dot(v2));
  43313. var sign = Math.sign(v1.cross(v2).dot(n));
  43314. angle = angle * sign;
  43315. if (Number.isNaN(angle)) {
  43316. return;
  43317. }
  43318. var matrixBefore = this.selection[0].matrix.clone();
  43319. var normal = new Vector3(...handle.alignment);
  43320. for (var selection of this.selection) {
  43321. //直接修改matrix,使整体绕boundingBox中心旋转。 xzw
  43322. var quaternion = selection.quaternion.clone();
  43323. var diffQua = new Quaternion().setFromAxisAngle(normal, angle); //变化量,参考 selection.rotateOnAxis(normal, angle);
  43324. var moveToZero = new Matrix4().setPosition(center.clone().negate()); //先将boundingBox中心(整体)移动到原点
  43325. var rotM = new Matrix4().makeRotationFromQuaternion(quaternion.clone().inverse().premultiply(diffQua).premultiply(quaternion)); //再旋转。根据selection.rotateOnAxis,应该是旧的qua 右乘 diffQua,所以先用invert消掉旧的qua
  43326. var moveBack = new Matrix4().setPosition(center.clone()); //移动回去,使boundingBox中心位置还原
  43327. selection.matrix.premultiply(moveToZero).premultiply(rotM).premultiply(moveBack);
  43328. selection.matrix.decompose(selection.position, selection.quaternion, selection.scale); //记录 (scale基本不变)
  43329. selection.updateMatrixWorld(); //xzw add 保险起见立即update
  43330. selection.dispatchEvent({
  43331. type: "orientation_changed",
  43332. object: selection
  43333. });
  43334. selection.dispatchEvent({
  43335. //当boundingBox中心不在原点时
  43336. type: "position_changed",
  43337. object: selection
  43338. });
  43339. }
  43340. this.dispatchEvent({
  43341. type: 'transformed',
  43342. changeType: ['orientation'],
  43343. matrixBefore
  43344. }); //add
  43345. drag.pivot = I;
  43346. }
  43347. }
  43348. dropRotationHandle(e) {
  43349. this.dragging = false;
  43350. this.setActiveHandle(null);
  43351. this.dispatchEvent({
  43352. type: 'stopDrag',
  43353. handle: 'rotation'
  43354. }); //add
  43355. }
  43356. dragTranslationHandle(e) {
  43357. //---大改,参考transformControls,为了加上xyz xy yz xz 这四个方向的变换。 (但感觉好像plane上有丢丢延迟?是因为drag延迟还是worldmatrix没更新)
  43358. var drag = e.drag;
  43359. var handle = this.activeHandle;
  43360. var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera();
  43361. if (handle && handle.name.includes('translation') && this.selection[0]) {
  43362. var posWorld = this.scene.getWorldPosition(new Vector3()); //bounding中心
  43363. if (!drag.intersectionStart) {
  43364. drag.intersectionStart = drag.location;
  43365. drag.worldPositionStart = this.selection[0].getWorldPosition(new Vector3());
  43366. drag.objectQua = this.selection[0].quaternion.clone(); //不考虑父级
  43367. drag.objectQuaInv = drag.objectQua.clone().invert();
  43368. this.dragging = true;
  43369. }
  43370. if (drag.intersectionStart) {
  43371. var pointer = this.viewer.inputHandler.pointer;
  43372. var ray = Utils.mouseToRay(pointer, camera);
  43373. //方向滑动所在面
  43374. var normal;
  43375. var axisName = handle.name.split('.').pop();
  43376. if (axisName == 'xyz') {
  43377. // 平行于屏幕滑动
  43378. normal = viewer.mainViewport.view.direction;
  43379. } else {
  43380. var alignVector = new Vector3();
  43381. normal = new Vector3();
  43382. var unitX = new Vector3(1, 0, 0).applyQuaternion(drag.objectQua);
  43383. var unitY = new Vector3(0, 1, 0).applyQuaternion(drag.objectQua);
  43384. var unitZ = new Vector3(0, 0, 1).applyQuaternion(drag.objectQua);
  43385. switch (axisName) {
  43386. case 'x':
  43387. alignVector.copy(viewer.mainViewport.view.direction).cross(unitX);
  43388. normal.copy(unitX).cross(alignVector);
  43389. break;
  43390. case 'y':
  43391. alignVector.copy(viewer.mainViewport.view.direction).cross(unitY);
  43392. normal.copy(unitY).cross(alignVector);
  43393. break;
  43394. case 'z':
  43395. alignVector.copy(viewer.mainViewport.view.direction).cross(unitZ);
  43396. normal.copy(unitZ).cross(alignVector);
  43397. break;
  43398. case 'xy':
  43399. normal.copy(unitZ);
  43400. break;
  43401. case 'yz':
  43402. normal.copy(unitX);
  43403. break;
  43404. case 'xz':
  43405. normal.copy(unitY);
  43406. break;
  43407. } //参考transformControls.使跟手
  43408. }
  43409. drag.dragPlane = new Plane().setFromNormalAndCoplanarPoint(normal, posWorld /* drag.worldPositionStart */); //过center的与视线垂直的平面
  43410. var I = ray.intersectPlane(drag.dragPlane, new Vector3());
  43411. if (I) {
  43412. var offset = new Vector3().subVectors(I, drag.worldPositionStart);
  43413. //let offset = new THREE.Vector3().subVectors(iOnLine, drag.worldPositionStart);
  43414. if (!drag.pointStart) {
  43415. drag.pointStart = offset;
  43416. } else {
  43417. drag.pointEnd = offset;
  43418. var diff = new Vector3().subVectors(drag.pointEnd, drag.pointStart);
  43419. diff.applyQuaternion(drag.objectQuaInv); // 得到在该物体local空间上的offset
  43420. if (!handle.name.includes('x')) diff.x = 0;
  43421. if (!handle.name.includes('y')) diff.y = 0;
  43422. if (!handle.name.includes('z')) diff.z = 0;
  43423. //恢复为world offset
  43424. diff.applyQuaternion(drag.objectQua);
  43425. //-------------
  43426. var matrixBefore = this.selection[0].matrix.clone();
  43427. this.selection[0].position.copy(diff).add(drag.worldPositionStart);
  43428. for (var selection of this.selection) {
  43429. selection.updateMatrixWorld(); //xzw add 保险起见立即update
  43430. selection.dispatchEvent({
  43431. type: "position_changed",
  43432. object: selection
  43433. });
  43434. }
  43435. this.dispatchEvent({
  43436. type: 'transformed',
  43437. changeType: ['position'],
  43438. matrixBefore
  43439. }); //add
  43440. }
  43441. }
  43442. }
  43443. }
  43444. }
  43445. dropTranslationHandle(e) {
  43446. this.dragging = false;
  43447. this.setActiveHandle(null);
  43448. this.dispatchEvent({
  43449. type: 'stopDrag',
  43450. handle: 'translation'
  43451. }); //add
  43452. }
  43453. dropScaleHandle(e) {
  43454. this.dragging = false;
  43455. this.setActiveHandle(null);
  43456. this.dispatchEvent({
  43457. type: 'stopDrag',
  43458. handle: 'scale'
  43459. }); //add
  43460. }
  43461. dragScaleHandle(e) {
  43462. var drag = e.drag;
  43463. var handle = this.activeHandle;
  43464. if (!handle || !handle.name.includes('scale')) return;
  43465. var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera();
  43466. if (!drag.intersectionStart) {
  43467. drag.intersectionStart = drag.location;
  43468. drag.objectStart = drag.object.getWorldPosition(new Vector3());
  43469. drag.handle = handle;
  43470. var start = drag.intersectionStart;
  43471. var dir = new Vector4(...handle.alignment, 0).applyMatrix4(this.scene.matrixWorld);
  43472. var end = new Vector3().addVectors(start, dir);
  43473. var line = new Line3(start.clone(), end.clone());
  43474. drag.line = line;
  43475. var normal;
  43476. if (camera.type == 'OrthographicCamera') {
  43477. //xzw add
  43478. normal = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
  43479. } else {
  43480. var camOnLine = line.closestPointToPoint(camera.position, false, new Vector3());
  43481. normal = new Vector3().subVectors(camera.position, camOnLine);
  43482. }
  43483. var plane = new Plane().setFromNormalAndCoplanarPoint(normal, drag.intersectionStart); //过轴线的一个能铺满屏幕的平面
  43484. drag.dragPlane = plane;
  43485. drag.pivot = drag.intersectionStart;
  43486. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  43487. } else {
  43488. handle = drag.handle;
  43489. }
  43490. this.dragging = true;
  43491. if (drag.dragPlane) {
  43492. //xzw add 因有时候没有
  43493. var pointer = this.viewer.inputHandler.pointer;
  43494. var domElement = this.viewer.renderer.domElement;
  43495. var ray = Utils.mouseToRay(pointer, camera, domElement.clientWidth, domElement.clientHeight);
  43496. var I = ray.intersectPlane(drag.dragPlane, new Vector3());
  43497. if (I) {
  43498. var iOnLine = drag.line.closestPointToPoint(I, false, new Vector3());
  43499. var direction = handle.alignment.reduce((a, v) => a + v, 0);
  43500. var toObjectSpace = this.selection[0].matrixWorld.clone().invert();
  43501. var iOnLineOS = iOnLine.clone().applyMatrix4(toObjectSpace);
  43502. var pivotOS = drag.pivot.clone().applyMatrix4(toObjectSpace);
  43503. var diffOS = new Vector3().subVectors(iOnLineOS, pivotOS);
  43504. var dragDirectionOS = diffOS.clone().normalize();
  43505. if (iOnLine.distanceTo(drag.pivot) === 0) {
  43506. dragDirectionOS.set(0, 0, 0);
  43507. }
  43508. var dragDirection = dragDirectionOS.dot(new Vector3(...handle.alignment));
  43509. var alignment = new Vector3(...handle.alignment);
  43510. var diff = new Vector3().subVectors(iOnLine, drag.pivot);
  43511. var diffScale = alignment.clone().multiplyScalar(diff.length() * direction * dragDirection);
  43512. //let diffPosition = diff.clone().multiplyScalar(0.5); //这个仅当bound包含原点才准确。
  43513. var matrixBefore = this.selection[0].matrix.clone();
  43514. for (var selection of this.selection) {
  43515. //xzw 改:否则不跟手
  43516. var {
  43517. min,
  43518. max
  43519. } = selection.boundingBox;
  43520. var fixPoint = alignment.x != 0 ? (alignment.x > 0 ? min : max).clone().setY(0).setZ(0) :
  43521. //要保证另一边不能移动
  43522. alignment.y != 0 ? (alignment.y > 0 ? min : max).clone().setX(0).setZ(0) : (alignment.z > 0 ? min : max).clone().setX(0).setY(0);
  43523. var fixPointBefore = fixPoint.clone().applyMatrix4(selection.matrixWorld);
  43524. var size = selection.boundingBox.getSize(new Vector3());
  43525. var diffScale_ = diffScale.clone().divide(size);
  43526. size.x == 0 && (diffScale_.x = 0); //add 若为0,不改此轴大小
  43527. size.y == 0 && (diffScale_.y = 0);
  43528. size.z == 0 && (diffScale_.z = 0);
  43529. selection.scale.add(diffScale_);
  43530. selection.scale.max(new Vector3(0.1, 0.1, 0.1));
  43531. //selection.position.add(diffPosition);
  43532. selection.updateMatrixWorld();
  43533. var fixPointAfter = fixPoint.clone().applyMatrix4(this.selection[0].matrixWorld);
  43534. selection.position.sub(new Vector3().subVectors(fixPointAfter, fixPointBefore)); //保证另一边不能移动所需要的位移
  43535. selection.updateMatrixWorld(); //xzw add 保险起见立即update
  43536. selection.dispatchEvent({
  43537. type: "position_changed",
  43538. object: selection
  43539. });
  43540. selection.dispatchEvent({
  43541. type: "scale_changed",
  43542. object: selection
  43543. });
  43544. }
  43545. this.dispatchEvent({
  43546. type: 'transformed',
  43547. changeType: ['position', 'scale'],
  43548. matrixBefore
  43549. }); //add
  43550. drag.pivot.copy(iOnLine);
  43551. //Utils.debugSphere(viewer.scene.scene, drag.pivot, 0.05);
  43552. }
  43553. }
  43554. }
  43555. setActiveHandle(handle) {
  43556. if (this.dragging) {
  43557. return;
  43558. }
  43559. if (this.activeHandle === handle) {
  43560. return;
  43561. }
  43562. this.activeHandle = handle;
  43563. if (handle === null) {
  43564. for (var handleName of Object.keys(this.handles)) {
  43565. var _handle = this.handles[handleName];
  43566. _handle.node.setOpacity(0);
  43567. }
  43568. }
  43569. viewer.dispatchEvent({
  43570. type: 'CursorChange',
  43571. action: this.activeHandle ? 'add' : 'remove',
  43572. name: 'hoverTranHandle'
  43573. });
  43574. if (!hideFocusHandles) {
  43575. for (var _handleName of Object.keys(this.focusHandles)) {
  43576. var _handle2 = this.focusHandles[_handleName];
  43577. if (this.activeHandle === _handle2) {
  43578. _handle2.node.setOpacity(1.0);
  43579. } else {
  43580. _handle2.node.setOpacity(OpaWhenNotSelect);
  43581. }
  43582. }
  43583. }
  43584. for (var _handleName2 of Object.keys(this.translationHandles)) {
  43585. var _handle3 = this.translationHandles[_handleName2];
  43586. if (this.activeHandle === _handle3) {
  43587. _handle3.node.setOpacity(1.0);
  43588. } else {
  43589. _handle3.node.setOpacity(OpaWhenNotSelect);
  43590. }
  43591. }
  43592. for (var _handleName3 of Object.keys(this.rotationHandles)) {
  43593. var _handle4 = this.rotationHandles[_handleName3];
  43594. //if(this.activeHandle === handle){
  43595. // handle.node.setOpacity(1.0);
  43596. //}else{
  43597. // handle.node.setOpacity(OpaWhenNotSelect)
  43598. //}
  43599. _handle4.node.setOpacity(OpaWhenNotSelect);
  43600. }
  43601. for (var _handleName4 of Object.keys(this.scaleHandles)) {
  43602. var _handle5 = this.scaleHandles[_handleName4];
  43603. if (this.activeHandle === _handle5) {
  43604. _handle5.node.setOpacity(1.0);
  43605. if (!hideFocusHandles) {
  43606. var relatedFocusHandle = this.focusHandles[_handle5.name.replace("scale", "focus")];
  43607. var relatedFocusNode = relatedFocusHandle.node;
  43608. relatedFocusNode.setOpacity(OpaWhenNotSelect);
  43609. }
  43610. for (var translationHandleName of Object.keys(this.translationHandles)) {
  43611. var translationHandle = this.translationHandles[translationHandleName];
  43612. translationHandle.node.setOpacity(OpaWhenNotSelect);
  43613. }
  43614. //let relatedTranslationHandle = this.translationHandles[
  43615. // handle.name.replace("scale", "translation").replace(/[+-]/g, "")];
  43616. //let relatedTranslationNode = relatedTranslationHandle.node;
  43617. //relatedTranslationNode.setOpacity(OpaWhenNotSelect);
  43618. } else {
  43619. _handle5.node.setOpacity(OpaWhenNotSelect);
  43620. }
  43621. }
  43622. if (handle) {
  43623. handle.node.setOpacity(1.0);
  43624. }
  43625. viewer.dispatchEvent('content_changed');
  43626. }
  43627. update() {
  43628. if (this.selection.length === 1) {
  43629. this.scene.visible = true;
  43630. this.scene.updateMatrix();
  43631. this.scene.updateMatrixWorld();
  43632. var selected = this.selection[0];
  43633. //selected.updateMatrixWorld();//add 否则scale的sphere抖动
  43634. var world = selected.matrixWorld;
  43635. var camera = this.viewer.mainViewport.camera; //this.viewer.scene.getActiveCamera();
  43636. var domElement = this.viewer.renderer.domElement;
  43637. var center = selected.boundingBox.getCenter(new Vector3()).clone().applyMatrix4(selected.matrixWorld);
  43638. var scale = selected.boundingBox.getSize(new Vector3()).multiply(selected.scale);
  43639. scale.max(new Vector3(.1, .1, .1)); //xzw add 如果是plane,没有厚度,会导致该tool消失
  43640. this.scene.scale.copy(scale);
  43641. this.scene.position.copy(center);
  43642. this.scene.rotation.copy(selected.rotation); //这里只考虑当前子级的scale rotation
  43643. //如果是世界坐标 (缩放方向有bug。)
  43644. /*
  43645. let boundingBox = selected.boundingBox.clone().applyMatrix4(selected.matrixWorld);
  43646. let center = boundingBox.getCenter(new THREE.Vector3())
  43647. this.scene.position.copy(center);
  43648. this.scene.scale.copy(boundingBox.getSize(new THREE.Vector3()));
  43649. */
  43650. this.scene.updateMatrixWorld();
  43651. {
  43652. // adjust rotation handles
  43653. if (!this.dragging) {
  43654. if (this.modesEnabled.rotation || this.modesEnabled.translation) {
  43655. var tWorld = this.scene.matrixWorld;
  43656. var tObject = tWorld.clone().invert();
  43657. var camObjectPos = camera.getWorldPosition(new Vector3()).applyMatrix4(tObject);
  43658. if (this.modesEnabled.translation) {
  43659. //add
  43660. ['xy', 'yz', 'xz'].forEach(axis => {
  43661. var handle = this.translationHandles["translation.plane." + axis];
  43662. var pos = handle.node.children[0].position;
  43663. camObjectPos.x && (pos.x = Math.sign(camObjectPos.x) * Math.abs(pos.x));
  43664. camObjectPos.y && (pos.y = Math.sign(camObjectPos.y) * Math.abs(pos.y));
  43665. camObjectPos.z && (pos.z = Math.sign(camObjectPos.z) * Math.abs(pos.z));
  43666. });
  43667. }
  43668. if (this.modesEnabled.rotation) {
  43669. var above = camObjectPos.z > 0;
  43670. var below = !above;
  43671. var PI_HALF = Math.PI / 2;
  43672. var x = this.rotationHandles["rotation.x"].node.rotation;
  43673. var y = this.rotationHandles["rotation.y"].node.rotation;
  43674. var z = this.rotationHandles["rotation.z"].node.rotation;
  43675. x.order = "ZYX";
  43676. y.order = "ZYX";
  43677. if (above) {
  43678. if (camObjectPos.x > 0 && camObjectPos.y > 0) {
  43679. x.x = 1 * PI_HALF;
  43680. y.y = 3 * PI_HALF;
  43681. z.z = 0 * PI_HALF;
  43682. } else if (camObjectPos.x < 0 && camObjectPos.y > 0) {
  43683. x.x = 1 * PI_HALF;
  43684. y.y = 2 * PI_HALF;
  43685. z.z = 1 * PI_HALF;
  43686. } else if (camObjectPos.x < 0 && camObjectPos.y < 0) {
  43687. x.x = 2 * PI_HALF;
  43688. y.y = 2 * PI_HALF;
  43689. z.z = 2 * PI_HALF;
  43690. } else if (camObjectPos.x > 0 && camObjectPos.y < 0) {
  43691. x.x = 2 * PI_HALF;
  43692. y.y = 3 * PI_HALF;
  43693. z.z = 3 * PI_HALF;
  43694. }
  43695. } else if (below) {
  43696. if (camObjectPos.x > 0 && camObjectPos.y > 0) {
  43697. x.x = 0 * PI_HALF;
  43698. y.y = 0 * PI_HALF;
  43699. z.z = 0 * PI_HALF;
  43700. } else if (camObjectPos.x < 0 && camObjectPos.y > 0) {
  43701. x.x = 0 * PI_HALF;
  43702. y.y = 1 * PI_HALF;
  43703. z.z = 1 * PI_HALF;
  43704. } else if (camObjectPos.x < 0 && camObjectPos.y < 0) {
  43705. x.x = 3 * PI_HALF;
  43706. y.y = 1 * PI_HALF;
  43707. z.z = 2 * PI_HALF;
  43708. } else if (camObjectPos.x > 0 && camObjectPos.y < 0) {
  43709. x.x = 3 * PI_HALF;
  43710. y.y = 0 * PI_HALF;
  43711. z.z = 3 * PI_HALF;
  43712. }
  43713. }
  43714. }
  43715. }
  43716. }
  43717. // adjust scale of components
  43718. for (var handleName of Object.keys(this.handles)) {
  43719. var handle = this.handles[handleName];
  43720. var node = handle.node;
  43721. //xzw add:---- -当该轴正对相机时隐藏。(主要针对ortho类型camera。
  43722. if (!Potree.Utils.getObjVisiByReason(node, 'modeForce')) continue;
  43723. var alignment = handle.alignment;
  43724. if (alignment && (!handleName.includes('rotation') || camera.type == 'OrthographicCamera')) {
  43725. //旋转的话正常都应该显示
  43726. var normal = void 0;
  43727. var dir = new Vector3(...alignment).applyQuaternion(this.scene.quaternion);
  43728. if (camera.type == 'OrthographicCamera') {
  43729. normal = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion);
  43730. } else {
  43731. normal = new Vector3().subVectors(center, camera.position).normalize();
  43732. }
  43733. var ifOnLine = void 0;
  43734. if (handleName.includes('rotation') || handleName.includes('plane')) {
  43735. // 旋转轴和视线垂直时隐藏
  43736. ifOnLine = Math.abs(dir.dot(normal)) < 0.1;
  43737. } else {
  43738. ifOnLine = Math.abs(dir.dot(normal)) > 0.995;
  43739. }
  43740. Potree.Utils.updateVisible(node, 'faceToCamHide', !ifOnLine);
  43741. } else {
  43742. Potree.Utils.updateVisible(node, 'faceToCamHide', true);
  43743. }
  43744. if (!node.visible) continue;
  43745. //------------------------------------------------------------------------
  43746. if (handle.dontScale) continue; //add
  43747. var handlePos = node.getWorldPosition(new Vector3());
  43748. var distance = handlePos.distanceTo(camera.position);
  43749. var pr = Utils.projectedRadius(1, camera, distance, domElement.clientWidth, domElement.clientHeight);
  43750. var ws = node.parent.getWorldScale(new Vector3());
  43751. var s = ScaleRatio / pr;
  43752. var _scale = new Vector3(s, s, s).divide(ws);
  43753. var rot = new Matrix4().makeRotationFromEuler(node.rotation); //需要使用到旋转,所以我把设置scale的移到旋转后了,否则在视图上下旋转的分界线处rotateHandel会被拉长从而闪烁。
  43754. var rotInv = rot.clone().invert();
  43755. _scale.applyMatrix4(rotInv);
  43756. _scale.x = Math.abs(_scale.x);
  43757. _scale.y = Math.abs(_scale.y);
  43758. _scale.z = Math.abs(_scale.z);
  43759. node.scale.copy(_scale);
  43760. }
  43761. }
  43762. } else {
  43763. this.scene.visible = false;
  43764. }
  43765. }
  43766. onPointerMove() {
  43767. var pointer = this.viewer.inputHandler.pointer;
  43768. var camera = this.viewer.mainViewport.camera;
  43769. if (this.selection.length === 1 && !this.dragging) {
  43770. //xzw 添加dragging条件
  43771. var ray = Utils.mouseToRay(pointer, camera);
  43772. var raycaster = new Raycaster(ray.origin, ray.direction);
  43773. raycaster.layers.enableAll(); //add
  43774. var pickVolumes = this.pickVolumes.filter(v => {
  43775. var mode = v.handle.split('.')[0];
  43776. if (!this.modesEnabled[mode]) return;
  43777. return v.parent.parent.visible; //可能被隐藏该轴
  43778. });
  43779. var intersects = raycaster.intersectObjects(pickVolumes, true);
  43780. intersects = intersects.sort(function (a, b) {
  43781. var order2 = b.object.renderOrder || 0;
  43782. var order1 = a.object.renderOrder || 0;
  43783. return order2 - order1;
  43784. }); // 降序
  43785. if (intersects.length > 0) {
  43786. var I = intersects[0];
  43787. var handleName = I.object.handle;
  43788. //console.log(handleName)
  43789. this.setActiveHandle(this.handles[handleName]);
  43790. } else {
  43791. this.setActiveHandle(null);
  43792. }
  43793. }
  43794. }
  43795. }
  43796. ;
  43797. /*
  43798. note:
  43799. transformationTool.scene会跟随选中物体,其scale就是boundingbox的大小。因此transformationTool.frame这个框也会跟着缩放
  43800. */
  43801. var boxOpacity = {
  43802. hovered: 0.1,
  43803. selected: 0.2
  43804. };
  43805. var LineOpacity = {
  43806. default: 0.6,
  43807. selected: 1
  43808. };
  43809. var colors = {
  43810. 2: 0x2ee4ce,
  43811. //0x00ff80, //可见
  43812. 3: 0xffc23b,
  43813. //0xff3158, //不可见
  43814. 4: 0xffffff //
  43815. };
  43816. class Volume$1 extends Object3D {
  43817. constructor() {
  43818. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  43819. super();
  43820. if (this.constructor.name === "Volume") {
  43821. console.warn("Can't create object of class Volume directly. Use classes BoxVolume or SphereVolume instead.");
  43822. }
  43823. this._clip = args.clip || false;
  43824. this._visible = true;
  43825. //this.showVolumeLabel = true;
  43826. this._modifiable = args.modifiable || true;
  43827. {
  43828. // event listeners
  43829. this.addEventListener('select', e => {
  43830. //console.log('select')
  43831. this.setSelected(true);
  43832. });
  43833. this.addEventListener('deselect', e => {
  43834. //console.log('deselect')
  43835. this.setSelected(false);
  43836. });
  43837. this.addEventListener('mouseover', e => {
  43838. this.hovered = true;
  43839. this.update();
  43840. });
  43841. this.addEventListener('mouseleave', e => {
  43842. this.hovered = false;
  43843. this.update();
  43844. });
  43845. }
  43846. }
  43847. setSelected(state) {
  43848. //add
  43849. this.selected = !!state;
  43850. this.update();
  43851. }
  43852. get visible() {
  43853. return this._visible;
  43854. }
  43855. set visible(value) {
  43856. if (this._visible !== value) {
  43857. this._visible = value;
  43858. this.dispatchEvent({
  43859. type: "visibility_changed",
  43860. object: this
  43861. });
  43862. }
  43863. }
  43864. getVolume() {
  43865. console.warn("override this in subclass");
  43866. }
  43867. update() {}
  43868. raycast(raycaster, intersects) {}
  43869. get clip() {
  43870. return this._clip;
  43871. }
  43872. set clip(value) {
  43873. if (this._clip !== value) {
  43874. this._clip = value;
  43875. this.update();
  43876. this.dispatchEvent({
  43877. type: "clip_changed",
  43878. object: this
  43879. });
  43880. }
  43881. }
  43882. get modifieable() {
  43883. return this._modifiable;
  43884. }
  43885. set modifieable(value) {
  43886. this._modifiable = value;
  43887. this.update();
  43888. }
  43889. }
  43890. ;
  43891. class BoxVolume$1 extends Volume$1 {
  43892. constructor() {
  43893. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  43894. super(args);
  43895. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  43896. this.name = 'box_' + this.constructor.counter;
  43897. this.clipTask = args.clipTask || Potree.ClipTask.SHOW_INSIDE; //add
  43898. this.showBox = true;
  43899. var boxGeometry = new BoxGeometry(1, 1, 1);
  43900. boxGeometry.computeBoundingBox();
  43901. var boxFrameGeometry = new Geometry();
  43902. var Vector3$1 = Vector3;
  43903. {
  43904. boxFrameGeometry.vertices.push(
  43905. // bottom
  43906. new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, -0.5, 0.5),
  43907. // top
  43908. new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5), new Vector3$1(-0.5, 0.5, 0.5),
  43909. // sides
  43910. new Vector3$1(-0.5, -0.5, 0.5), new Vector3$1(-0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, 0.5), new Vector3$1(0.5, 0.5, 0.5), new Vector3$1(0.5, -0.5, -0.5), new Vector3$1(0.5, 0.5, -0.5), new Vector3$1(-0.5, -0.5, -0.5), new Vector3$1(-0.5, 0.5, -0.5));
  43911. }
  43912. this.material = new DepthBasicMaterial({
  43913. color: colors[this.clipTask],
  43914. side: DoubleSide,
  43915. transparent: true,
  43916. opacity: boxOpacity.hovered,
  43917. depthTest: true,
  43918. depthWrite: false,
  43919. useDepth: true,
  43920. clipDistance: 2,
  43921. //消失距离
  43922. occlusionDistance: 0.1,
  43923. //变为backColor距离
  43924. maxClipFactor: 0.9
  43925. });
  43926. this.box = new Mesh(boxGeometry, this.material);
  43927. this.box.geometry.computeBoundingBox();
  43928. this.boundingBox = this.box.geometry.boundingBox;
  43929. this.add(this.box);
  43930. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: colors[this.clipTask], opacity:LineOpacity.default/* 0xff2050 */}));
  43931. this.frame = LineDraw.createFatLine(boxFrameGeometry.vertices, {
  43932. color: colors[this.clipTask],
  43933. opacity: LineOpacity.default,
  43934. lineWidth: 1,
  43935. dontAlwaysSeen: true
  43936. });
  43937. // this.frame.mode = THREE.Lines;
  43938. this.add(this.frame);
  43939. this.update();
  43940. }
  43941. update() {
  43942. this.boundingBox = this.box.geometry.boundingBox;
  43943. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  43944. Potree.Utils.updateVisible(this.box, 'selected', (this.selected || this.hovered) && this.showBox);
  43945. this.box.material.opacity = this.selected ? boxOpacity.selected : boxOpacity.hovered;
  43946. this.box.material.color.set(colors[this.clipTask]);
  43947. this.frame.material.color.set(colors[this.clipTask]);
  43948. this.frame.material.opacity = this.selected ? LineOpacity.selected : LineOpacity.default;
  43949. this.frame.material.lineWidth = this.selected ? 2 : 1;
  43950. }
  43951. raycast(raycaster, intersects) {
  43952. var is = [];
  43953. this.box.raycast(raycaster, is);
  43954. if (is.length > 0) {
  43955. var I = is[0];
  43956. intersects.push({
  43957. distance: I.distance,
  43958. object: this,
  43959. point: I.point.clone()
  43960. });
  43961. }
  43962. }
  43963. getVolume() {
  43964. return Math.abs(this.scale.x * this.scale.y * this.scale.z);
  43965. }
  43966. }
  43967. ;
  43968. class SphereVolume$2 extends Volume$1 {
  43969. constructor() {
  43970. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  43971. super(args);
  43972. this.constructor.counter = this.constructor.counter === undefined ? 0 : this.constructor.counter + 1;
  43973. this.name = 'sphere_' + this.constructor.counter;
  43974. var sphereGeometry = new SphereGeometry(1, 32, 32);
  43975. sphereGeometry.computeBoundingBox();
  43976. this.material = new MeshBasicMaterial({
  43977. color: 0x00ff00,
  43978. transparent: true,
  43979. opacity: 0.3,
  43980. depthTest: true,
  43981. depthWrite: false
  43982. });
  43983. this.sphere = new Mesh(sphereGeometry, this.material);
  43984. this.sphere.visible = false;
  43985. this.sphere.geometry.computeBoundingBox();
  43986. this.boundingBox = this.sphere.geometry.boundingBox;
  43987. this.add(this.sphere);
  43988. this.label.visible = false;
  43989. var frameGeometry = new Geometry();
  43990. {
  43991. var steps = 64;
  43992. var uSegments = 8;
  43993. var vSegments = 5;
  43994. var r = 1;
  43995. for (var uSegment = 0; uSegment < uSegments; uSegment++) {
  43996. var alpha = uSegment / uSegments * Math.PI * 2;
  43997. var dirx = Math.cos(alpha);
  43998. var diry = Math.sin(alpha);
  43999. for (var i = 0; i <= steps; i++) {
  44000. var v = i / steps * Math.PI * 2;
  44001. var vNext = v + 2 * Math.PI / steps;
  44002. var height = Math.sin(v);
  44003. var xyAmount = Math.cos(v);
  44004. var heightNext = Math.sin(vNext);
  44005. var xyAmountNext = Math.cos(vNext);
  44006. var vertex = new Vector3(dirx * xyAmount, diry * xyAmount, height);
  44007. frameGeometry.vertices.push(vertex);
  44008. var vertexNext = new Vector3(dirx * xyAmountNext, diry * xyAmountNext, heightNext);
  44009. frameGeometry.vertices.push(vertexNext);
  44010. }
  44011. }
  44012. // creates rings at poles, just because it's easier to implement
  44013. for (var vSegment = 0; vSegment <= vSegments + 1; vSegment++) {
  44014. //let height = (vSegment / (vSegments + 1)) * 2 - 1; // -1 to 1
  44015. var uh = vSegment / (vSegments + 1); // -1 to 1
  44016. uh = (1 - uh) * (-Math.PI / 2) + uh * (Math.PI / 2);
  44017. var _height = Math.sin(uh);
  44018. console.log(uh, _height);
  44019. for (var _i = 0; _i <= steps; _i++) {
  44020. var u = _i / steps * Math.PI * 2;
  44021. var uNext = u + 2 * Math.PI / steps;
  44022. var _dirx = Math.cos(u);
  44023. var _diry = Math.sin(u);
  44024. var dirxNext = Math.cos(uNext);
  44025. var diryNext = Math.sin(uNext);
  44026. var _xyAmount = Math.sqrt(1 - _height * _height);
  44027. var _vertex = new Vector3(_dirx * _xyAmount, _diry * _xyAmount, _height);
  44028. frameGeometry.vertices.push(_vertex);
  44029. var _vertexNext = new Vector3(dirxNext * _xyAmount, diryNext * _xyAmount, _height);
  44030. frameGeometry.vertices.push(_vertexNext);
  44031. }
  44032. }
  44033. }
  44034. this.frame = new LineSegments(frameGeometry, new LineBasicMaterial({
  44035. color: 0x000000
  44036. }));
  44037. this.add(this.frame);
  44038. var frameMaterial = new MeshBasicMaterial({
  44039. wireframe: true,
  44040. color: 0x000000
  44041. });
  44042. this.frame = new Mesh(sphereGeometry, frameMaterial);
  44043. //this.add(this.frame);
  44044. //this.frame = new THREE.LineSegments(boxFrameGeometry, new THREE.LineBasicMaterial({color: 0x000000}));
  44045. // this.frame.mode = THREE.Lines;
  44046. //this.add(this.frame);
  44047. this.update();
  44048. }
  44049. update() {
  44050. this.boundingBox = this.sphere.geometry.boundingBox;
  44051. this.boundingSphere = this.boundingBox.getBoundingSphere(new Sphere());
  44052. //if (this._clip) {
  44053. // this.sphere.visible = false;
  44054. // this.label.visible = false;
  44055. //} else {
  44056. // this.sphere.visible = true;
  44057. // this.label.visible = this.showVolumeLabel;
  44058. //}
  44059. }
  44060. raycast(raycaster, intersects) {
  44061. var is = [];
  44062. this.sphere.raycast(raycaster, is);
  44063. if (is.length > 0) {
  44064. var I = is[0];
  44065. intersects.push({
  44066. distance: I.distance,
  44067. object: this,
  44068. point: I.point.clone()
  44069. });
  44070. }
  44071. }
  44072. // see https://en.wikipedia.org/wiki/Ellipsoid#Volume
  44073. getVolume() {
  44074. return 4 / 3 * Math.PI * this.scale.x * this.scale.y * this.scale.z;
  44075. }
  44076. }
  44077. ;
  44078. var _SplatBuffer, _PlyParser;
  44079. /**
  44080. * AbortablePromise: A quick & dirty wrapper for JavaScript's Promise class that allows the underlying
  44081. * asynchronous operation to be cancelled. It is only meant for simple situations where no complex promise
  44082. * chaining or merging occurs. It needs a significant amount of work to truly replicate the full
  44083. * functionality of JavaScript's Promise class. Look at Util.fetchWithProgress() for example usage.
  44084. *
  44085. * This class was primarily added to allow splat scene downloads to be cancelled. It has not been tested
  44086. * very thoroughly and the implementation is kinda janky. If you can at all help it, please avoid using it :)
  44087. */
  44088. class AbortablePromise {
  44089. constructor(promiseFunc, abortHandler) {
  44090. var promiseResolve;
  44091. var promiseReject;
  44092. this.promise = new Promise((resolve, reject) => {
  44093. promiseResolve = resolve.bind(this);
  44094. promiseReject = reject.bind(this);
  44095. });
  44096. var resolve = function resolve() {
  44097. promiseResolve(...arguments);
  44098. };
  44099. var reject = error => {
  44100. promiseReject(error);
  44101. };
  44102. promiseFunc(resolve.bind(this), reject.bind(this));
  44103. this.abortHandler = abortHandler;
  44104. this.id = AbortablePromise.idGen++;
  44105. }
  44106. then(onResolve) {
  44107. return new AbortablePromise((resolve, reject) => {
  44108. this.promise = this.promise.then(function () {
  44109. var onResolveResult = onResolve(...arguments);
  44110. if (onResolveResult instanceof Promise || onResolveResult instanceof AbortablePromise) {
  44111. onResolveResult.then(function () {
  44112. resolve(...arguments);
  44113. });
  44114. } else {
  44115. resolve(onResolveResult);
  44116. }
  44117. }).catch(error => {
  44118. reject(error);
  44119. });
  44120. }, this.abortHandler);
  44121. }
  44122. catch(onFail) {
  44123. return new AbortablePromise(resolve => {
  44124. this.promise = this.promise.then(function () {
  44125. resolve(...arguments);
  44126. }).catch(onFail);
  44127. }, this.abortHandler);
  44128. }
  44129. abort() {
  44130. if (this.abortHandler) this.abortHandler();
  44131. }
  44132. }
  44133. _defineProperty(AbortablePromise, "idGen", 0);
  44134. class AbortedPromiseError extends Error {
  44135. constructor(msg) {
  44136. super(msg);
  44137. }
  44138. }
  44139. var floatToHalf = function () {
  44140. var floatView = new Float32Array(1);
  44141. var int32View = new Int32Array(floatView.buffer);
  44142. return function (val) {
  44143. floatView[0] = val;
  44144. var x = int32View[0];
  44145. var bits = x >> 16 & 0x8000;
  44146. var m = x >> 12 & 0x07ff;
  44147. var e = x >> 23 & 0xff;
  44148. if (e < 103) return bits;
  44149. if (e > 142) {
  44150. bits |= 0x7c00;
  44151. bits |= (e == 255 ? 0 : 1) && x & 0x007fffff;
  44152. return bits;
  44153. }
  44154. if (e < 113) {
  44155. m |= 0x0800;
  44156. bits |= (m >> 114 - e) + (m >> 113 - e & 1);
  44157. return bits;
  44158. }
  44159. bits |= e - 112 << 10 | m >> 1;
  44160. bits += m & 1;
  44161. return bits;
  44162. };
  44163. }();
  44164. var uintEncodedFloat = function () {
  44165. var floatView = new Float32Array(1);
  44166. var int32View = new Int32Array(floatView.buffer);
  44167. return function (f) {
  44168. floatView[0] = f;
  44169. return int32View[0];
  44170. };
  44171. }();
  44172. var rgbaToInteger = function rgbaToInteger(r, g, b, a) {
  44173. return r + (g << 8) + (b << 16) + (a << 24);
  44174. };
  44175. var rgbaArrayToInteger = function rgbaArrayToInteger(arr, offset) {
  44176. return arr[offset] + (arr[offset + 1] << 8) + (arr[offset + 2] << 16) + (arr[offset + 3] << 24);
  44177. };
  44178. var fetchWithProgress = function fetchWithProgress(path, onProgress) {
  44179. var saveChunks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  44180. var abortController = new AbortController();
  44181. var signal = abortController.signal;
  44182. var aborted = false;
  44183. var rejectFunc = null;
  44184. var abortHandler = () => {
  44185. abortController.abort();
  44186. rejectFunc(new AbortedPromiseError('Fetch aborted.'));
  44187. aborted = true;
  44188. };
  44189. return new AbortablePromise((resolve, reject) => {
  44190. rejectFunc = reject;
  44191. fetch(path, {
  44192. signal
  44193. }).then( /*#__PURE__*/function () {
  44194. var _ref = _asyncToGenerator(function* (data) {
  44195. var reader = data.body.getReader();
  44196. var bytesDownloaded = 0;
  44197. var _fileSize = data.headers.get('Content-Length');
  44198. var fileSize = _fileSize ? parseInt(_fileSize) : undefined;
  44199. var chunks = [];
  44200. while (!aborted) {
  44201. try {
  44202. var {
  44203. value: chunk,
  44204. done
  44205. } = yield reader.read();
  44206. if (done) {
  44207. if (onProgress) {
  44208. onProgress(100, '100%', chunk, fileSize);
  44209. }
  44210. if (saveChunks) {
  44211. var buffer = new Blob(chunks).arrayBuffer();
  44212. resolve(buffer);
  44213. } else {
  44214. resolve();
  44215. }
  44216. break;
  44217. }
  44218. bytesDownloaded += chunk.length;
  44219. var percent = void 0;
  44220. var percentLabel = void 0;
  44221. if (fileSize !== undefined) {
  44222. percent = bytesDownloaded / fileSize * 100;
  44223. percentLabel = "".concat(percent.toFixed(2), "%");
  44224. }
  44225. if (saveChunks) chunks.push(chunk);
  44226. if (onProgress) {
  44227. var cancelSaveChucnks = onProgress(percent, percentLabel, chunk, fileSize);
  44228. if (cancelSaveChucnks) saveChunks = false;
  44229. }
  44230. } catch (error) {
  44231. reject(error);
  44232. break;
  44233. }
  44234. }
  44235. });
  44236. return function (_x) {
  44237. return _ref.apply(this, arguments);
  44238. };
  44239. }());
  44240. }, abortHandler);
  44241. };
  44242. var clamp = function clamp(val, min, max) {
  44243. return Math.max(Math.min(val, max), min);
  44244. };
  44245. var getCurrentTime = function getCurrentTime() {
  44246. return performance.now() / 1000;
  44247. };
  44248. var disposeAllMeshes = object3D => {
  44249. if (object3D.geometry) {
  44250. object3D.geometry.dispose();
  44251. object3D.geometry = null;
  44252. }
  44253. if (object3D.material) {
  44254. object3D.material.dispose();
  44255. object3D.material = null;
  44256. }
  44257. if (object3D.children) {
  44258. for (var child of object3D.children) {
  44259. disposeAllMeshes(child);
  44260. }
  44261. }
  44262. };
  44263. var delayedExecute = (func, fast) => {
  44264. return new Promise(resolve => {
  44265. window.setTimeout(() => {
  44266. resolve(func());
  44267. }, fast ? 1 : 50);
  44268. });
  44269. };
  44270. var getSphericalHarmonicsComponentCountForDegree = function getSphericalHarmonicsComponentCountForDegree() {
  44271. var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  44272. switch (sphericalHarmonicsDegree) {
  44273. case 1:
  44274. return 9;
  44275. case 2:
  44276. return 24;
  44277. }
  44278. return 0;
  44279. };
  44280. var BASE_COMPONENT_COUNT = 14;
  44281. class UncompressedSplatArray {
  44282. constructor() {
  44283. var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  44284. this.sphericalHarmonicsDegree = sphericalHarmonicsDegree;
  44285. this.sphericalHarmonicsCount = getSphericalHarmonicsComponentCountForDegree(this.sphericalHarmonicsDegree);
  44286. this.componentCount = this.sphericalHarmonicsCount + BASE_COMPONENT_COUNT;
  44287. this.defaultSphericalHarmonics = new Array(this.sphericalHarmonicsCount).fill(0);
  44288. this.splats = [];
  44289. this.splatCount = 0;
  44290. }
  44291. static createSplat() {
  44292. var sphericalHarmonicsDegree = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  44293. var baseSplat = [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
  44294. var shEntries = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree);
  44295. for (var i = 0; i < shEntries; i++) baseSplat.push(0);
  44296. return baseSplat;
  44297. }
  44298. addSplat(splat) {
  44299. this.splats.push(splat);
  44300. this.splatCount++;
  44301. }
  44302. getSplat(index) {
  44303. return this.splats[index];
  44304. }
  44305. addDefaultSplat() {
  44306. var newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree);
  44307. this.addSplat(newSplat);
  44308. return newSplat;
  44309. }
  44310. addSplatFromComonents(x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity) {
  44311. var newSplat = [x, y, z, scale0, scale1, scale2, rot0, rot1, rot2, rot3, r, g, b, opacity, ...this.defaultSphericalHarmonics];
  44312. for (var i = 0; i < (arguments.length <= 14 ? 0 : arguments.length - 14) && i < this.sphericalHarmonicsCount; i++) {
  44313. newSplat[i] = i + 14 < 14 || arguments.length <= i + 14 ? undefined : arguments[i + 14];
  44314. }
  44315. this.addSplat(newSplat);
  44316. return newSplat;
  44317. }
  44318. addSplatFromArray(src, srcIndex) {
  44319. var srcSplat = src.splats[srcIndex];
  44320. var newSplat = UncompressedSplatArray.createSplat(this.sphericalHarmonicsDegree);
  44321. for (var i = 0; i < this.componentCount && i < srcSplat.length; i++) {
  44322. newSplat[i] = srcSplat[i];
  44323. }
  44324. this.addSplat(newSplat);
  44325. }
  44326. }
  44327. _defineProperty(UncompressedSplatArray, "OFFSET", {
  44328. X: 0,
  44329. Y: 1,
  44330. Z: 2,
  44331. SCALE0: 3,
  44332. SCALE1: 4,
  44333. SCALE2: 5,
  44334. ROTATION0: 6,
  44335. ROTATION1: 7,
  44336. ROTATION2: 8,
  44337. ROTATION3: 9,
  44338. FDC0: 10,
  44339. FDC1: 11,
  44340. FDC2: 12,
  44341. OPACITY: 13,
  44342. FRC0: 14,
  44343. FRC1: 15,
  44344. FRC2: 16,
  44345. FRC3: 17,
  44346. FRC4: 18,
  44347. FRC5: 19,
  44348. FRC6: 20,
  44349. FRC7: 21,
  44350. FRC8: 22,
  44351. FRC9: 23,
  44352. FRC10: 24,
  44353. FRC11: 25,
  44354. FRC12: 26,
  44355. FRC13: 27,
  44356. FRC14: 28,
  44357. FRC15: 29,
  44358. FRC16: 30,
  44359. FRC17: 31,
  44360. FRC18: 32,
  44361. FRC19: 33,
  44362. FRC20: 34,
  44363. FRC21: 35,
  44364. FRC22: 36,
  44365. FRC23: 37
  44366. });
  44367. var toHalfFloat = THREE$2.DataUtils.toHalfFloat.bind(THREE$2.DataUtils);
  44368. var toUint8 = v => {
  44369. return Math.floor(v * 128) + 128;
  44370. };
  44371. var fromUint8 = v => {
  44372. return v / 255 * 2.0 - 1.0;
  44373. };
  44374. //xzw 改 暂时没用到 需要更新版本
  44375. var fromHalfFloat = () => {}; //THREE.DataUtils.fromHalfFloat.bind(THREE.DataUtils);
  44376. var fromHalfFloatToUint8 = v => {
  44377. return Math.floor(fromHalfFloat(v) * 128) + 128;
  44378. };
  44379. var toUncompressedFloat = function toUncompressedFloat(f, compressionLevel) {
  44380. var isSH = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  44381. if (compressionLevel === 0) {
  44382. return f;
  44383. } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) {
  44384. return THREE$2.DataUtils.fromHalfFloat(f);
  44385. } else if (compressionLevel === 2) {
  44386. return fromUint8(f);
  44387. }
  44388. };
  44389. var dataViewFloatForCompressionLevel = function dataViewFloatForCompressionLevel(dataView, floatIndex, compressionLevel) {
  44390. var isSH = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  44391. if (compressionLevel === 0) {
  44392. return dataView.getFloat32(floatIndex * 4, true);
  44393. } else if (compressionLevel === 1 || compressionLevel === 2 && !isSH) {
  44394. return dataView.getUint16(floatIndex * 2, true);
  44395. } else {
  44396. return dataView.getUint8(floatIndex, true);
  44397. }
  44398. };
  44399. /**
  44400. * SplatBuffer: Container for splat data from a single scene/file and capable of (mediocre) compression.
  44401. */
  44402. class SplatBuffer {
  44403. constructor(bufferData) {
  44404. var secLoadedCountsToMax = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  44405. _defineProperty(this, "getSplatScaleAndRotation", function () {
  44406. var scaleMatrix = new THREE$2.Matrix4();
  44407. var rotationMatrix = new THREE$2.Matrix4();
  44408. var tempMatrix = new THREE$2.Matrix4();
  44409. var tempPosition = new THREE$2.Vector3();
  44410. var scale = new THREE$2.Vector3();
  44411. var rotation = new THREE$2.Quaternion();
  44412. return function (index, outScale, outRotation, transform) {
  44413. var sectionIndex = this.globalSplatIndexToSectionMap[index];
  44414. var section = this.sections[sectionIndex];
  44415. var localSplatIndex = index - section.splatCountOffset;
  44416. var srcSplatScalesBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes;
  44417. var dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase);
  44418. scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel));
  44419. rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel));
  44420. if (transform) {
  44421. scaleMatrix.makeScale(scale.x, scale.y, scale.z);
  44422. rotationMatrix.makeRotationFromQuaternion(rotation);
  44423. tempMatrix.copy(scaleMatrix).multiply(rotationMatrix).multiply(transform);
  44424. tempMatrix.decompose(tempPosition, outRotation, outScale);
  44425. } else {
  44426. outScale.copy(scale);
  44427. outRotation.copy(rotation);
  44428. }
  44429. };
  44430. }());
  44431. _defineProperty(this, "fillSphericalHarmonicsArray", function () {
  44432. var sphericalHarmonicVectors = [];
  44433. for (var i = 0; i < 15; i++) {
  44434. sphericalHarmonicVectors[i] = new THREE$2.Vector3();
  44435. }
  44436. var tempMatrix3 = new THREE$2.Matrix3();
  44437. var sh11 = [];
  44438. var sh12 = [];
  44439. var sh13 = [];
  44440. var sh21 = [];
  44441. var sh22 = [];
  44442. var sh23 = [];
  44443. var sh24 = [];
  44444. var sh25 = [];
  44445. var shIn1 = [];
  44446. var shIn2 = [];
  44447. var shIn3 = [];
  44448. var shIn4 = [];
  44449. var shIn5 = [];
  44450. var shOut1 = [];
  44451. var shOut2 = [];
  44452. var shOut3 = [];
  44453. var shOut4 = [];
  44454. var shOut5 = [];
  44455. var noop = v => v;
  44456. var set3 = (array, val1, val2, val3) => {
  44457. array[0] = val1;
  44458. array[1] = val2;
  44459. array[2] = val3;
  44460. };
  44461. var set3FromArray = (array, srcDestView, stride, srcBase, compressionLevel) => {
  44462. array[0] = dataViewFloatForCompressionLevel(srcDestView, srcBase, compressionLevel, true);
  44463. array[1] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride, compressionLevel, true);
  44464. array[2] = dataViewFloatForCompressionLevel(srcDestView, srcBase + stride + stride, compressionLevel, true);
  44465. };
  44466. var copy3 = (srcArray, destArray) => {
  44467. destArray[0] = srcArray[0];
  44468. destArray[1] = srcArray[1];
  44469. destArray[2] = srcArray[2];
  44470. };
  44471. var setOutput3 = (srcArray, destArray, destBase, conversionFunc) => {
  44472. destArray[destBase] = conversionFunc(srcArray[0]);
  44473. destArray[destBase + 1] = conversionFunc(srcArray[1]);
  44474. destArray[destBase + 2] = conversionFunc(srcArray[2]);
  44475. };
  44476. var toUncompressedFloatArray3 = (src, dest, compressionLevel) => {
  44477. dest[0] = toUncompressedFloat(src[0], compressionLevel, true);
  44478. dest[1] = toUncompressedFloat(src[1], compressionLevel, true);
  44479. dest[2] = toUncompressedFloat(src[2], compressionLevel, true);
  44480. return dest;
  44481. };
  44482. return function (outSphericalHarmonicsArray, outSphericalHarmonicsDegree, transform, srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) {
  44483. var splatCount = this.splatCount;
  44484. srcFrom = srcFrom || 0;
  44485. srcTo = srcTo || splatCount - 1;
  44486. if (destFrom === undefined) destFrom = srcFrom;
  44487. if (transform && outSphericalHarmonicsDegree >= 1) {
  44488. tempMatrix3.setFromMatrix4(transform);
  44489. set3(sh11, tempMatrix3.elements[4], -tempMatrix3.elements[7], tempMatrix3.elements[1]);
  44490. set3(sh12, -tempMatrix3.elements[5], tempMatrix3.elements[8], -tempMatrix3.elements[2]);
  44491. set3(sh13, tempMatrix3.elements[3], -tempMatrix3.elements[6], tempMatrix3.elements[0]);
  44492. }
  44493. for (var _i = srcFrom; _i <= srcTo; _i++) {
  44494. var sectionIndex = this.globalSplatIndexToSectionMap[_i];
  44495. var section = this.sections[sectionIndex];
  44496. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, section.sphericalHarmonicsDegree);
  44497. var outSphericalHarmonicsComponentsCount = getSphericalHarmonicsComponentCountForDegree(outSphericalHarmonicsDegree);
  44498. var localSplatIndex = _i - section.splatCountOffset;
  44499. var srcSplatSHBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].SphericalHarmonicsOffsetBytes;
  44500. var dataView = new DataView(this.bufferData, section.dataBase + srcSplatSHBase);
  44501. var shDestBase = (_i - srcFrom + destFrom) * outSphericalHarmonicsComponentsCount;
  44502. var compressionLevelForOutputConversion = transform ? 0 : this.compressionLevel;
  44503. var outputConversionFunc = noop;
  44504. if (compressionLevelForOutputConversion !== desiredOutputCompressionLevel) {
  44505. if (compressionLevelForOutputConversion === 1) {
  44506. if (desiredOutputCompressionLevel === 0) outputConversionFunc = fromHalfFloat;else if (desiredOutputCompressionLevel == 2) outputConversionFunc = fromHalfFloatToUint8;
  44507. } else if (compressionLevelForOutputConversion === 0) {
  44508. if (desiredOutputCompressionLevel === 1) outputConversionFunc = toHalfFloat;else if (desiredOutputCompressionLevel == 2) outputConversionFunc = toUint8;
  44509. }
  44510. }
  44511. if (outSphericalHarmonicsDegree >= 1) {
  44512. set3FromArray(shIn1, dataView, 3, 0, this.compressionLevel);
  44513. set3FromArray(shIn2, dataView, 3, 1, this.compressionLevel);
  44514. set3FromArray(shIn3, dataView, 3, 2, this.compressionLevel);
  44515. if (transform) {
  44516. toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel);
  44517. toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel);
  44518. toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel);
  44519. SplatBuffer.rotateSphericalHarmonics3(shIn1, shIn2, shIn3, sh11, sh12, sh13, shOut1, shOut2, shOut3);
  44520. } else {
  44521. copy3(shIn1, shOut1);
  44522. copy3(shIn2, shOut2);
  44523. copy3(shIn3, shOut3);
  44524. }
  44525. setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase, outputConversionFunc);
  44526. setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 3, outputConversionFunc);
  44527. setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 6, outputConversionFunc);
  44528. if (outSphericalHarmonicsDegree >= 2) {
  44529. set3FromArray(shIn1, dataView, 5, 9, this.compressionLevel);
  44530. set3FromArray(shIn2, dataView, 5, 10, this.compressionLevel);
  44531. set3FromArray(shIn3, dataView, 5, 11, this.compressionLevel);
  44532. set3FromArray(shIn4, dataView, 5, 12, this.compressionLevel);
  44533. set3FromArray(shIn5, dataView, 5, 13, this.compressionLevel);
  44534. if (transform) {
  44535. toUncompressedFloatArray3(shIn1, shIn1, this.compressionLevel);
  44536. toUncompressedFloatArray3(shIn2, shIn2, this.compressionLevel);
  44537. toUncompressedFloatArray3(shIn3, shIn3, this.compressionLevel);
  44538. toUncompressedFloatArray3(shIn4, shIn4, this.compressionLevel);
  44539. toUncompressedFloatArray3(shIn5, shIn5, this.compressionLevel);
  44540. SplatBuffer.rotateSphericalHarmonics5(shIn1, shIn2, shIn3, shIn4, shIn5, sh11, sh12, sh13, sh21, sh22, sh23, sh24, sh25, shOut1, shOut2, shOut3, shOut4, shOut5);
  44541. } else {
  44542. copy3(shIn1, shOut1);
  44543. copy3(shIn2, shOut2);
  44544. copy3(shIn3, shOut3);
  44545. copy3(shIn4, shOut4);
  44546. copy3(shIn5, shOut5);
  44547. }
  44548. setOutput3(shOut1, outSphericalHarmonicsArray, shDestBase + 9, outputConversionFunc);
  44549. setOutput3(shOut2, outSphericalHarmonicsArray, shDestBase + 12, outputConversionFunc);
  44550. setOutput3(shOut3, outSphericalHarmonicsArray, shDestBase + 15, outputConversionFunc);
  44551. setOutput3(shOut4, outSphericalHarmonicsArray, shDestBase + 18, outputConversionFunc);
  44552. setOutput3(shOut5, outSphericalHarmonicsArray, shDestBase + 21, outputConversionFunc);
  44553. }
  44554. }
  44555. }
  44556. };
  44557. }());
  44558. this.constructFromBuffer(bufferData, secLoadedCountsToMax);
  44559. }
  44560. getSplatCount() {
  44561. return this.splatCount;
  44562. }
  44563. getMaxSplatCount() {
  44564. return this.maxSplatCount;
  44565. }
  44566. getMinSphericalHarmonicsDegree() {
  44567. var minSphericalHarmonicsDegree = 0;
  44568. for (var i = 0; i < this.sections.length; i++) {
  44569. var section = this.sections[i];
  44570. if (i === 0 || section.sphericalHarmonicsDegree < minSphericalHarmonicsDegree) {
  44571. minSphericalHarmonicsDegree = section.sphericalHarmonicsDegree;
  44572. }
  44573. }
  44574. return minSphericalHarmonicsDegree;
  44575. }
  44576. getBucketIndex(section, localSplatIndex) {
  44577. var bucketIndex;
  44578. var maxSplatIndexInFullBuckets = section.fullBucketCount * section.bucketSize;
  44579. if (localSplatIndex < maxSplatIndexInFullBuckets) {
  44580. bucketIndex = Math.floor(localSplatIndex / section.bucketSize);
  44581. } else {
  44582. var bucketSplatIndex = maxSplatIndexInFullBuckets;
  44583. bucketIndex = section.fullBucketCount;
  44584. var partiallyFullBucketIndex = 0;
  44585. while (bucketSplatIndex < section.splatCount) {
  44586. var currentPartiallyFilledBucketSize = section.partiallyFilledBucketLengths[partiallyFullBucketIndex];
  44587. if (localSplatIndex >= bucketSplatIndex && localSplatIndex < bucketSplatIndex + currentPartiallyFilledBucketSize) {
  44588. break;
  44589. }
  44590. bucketSplatIndex += currentPartiallyFilledBucketSize;
  44591. bucketIndex++;
  44592. partiallyFullBucketIndex++;
  44593. }
  44594. }
  44595. return bucketIndex;
  44596. }
  44597. getSplatCenter(globalSplatIndex, outCenter, transform) {
  44598. var sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex];
  44599. var section = this.sections[sectionIndex];
  44600. var localSplatIndex = globalSplatIndex - section.splatCountOffset;
  44601. var srcSplatCentersBase = section.bytesPerSplat * localSplatIndex;
  44602. var dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase);
  44603. var x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel);
  44604. var y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel);
  44605. var z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel);
  44606. if (this.compressionLevel >= 1) {
  44607. var bucketIndex = this.getBucketIndex(section, localSplatIndex);
  44608. var bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats;
  44609. var sf = section.compressionScaleFactor;
  44610. var sr = section.compressionScaleRange;
  44611. outCenter.x = (x - sr) * sf + section.bucketArray[bucketBase];
  44612. outCenter.y = (y - sr) * sf + section.bucketArray[bucketBase + 1];
  44613. outCenter.z = (z - sr) * sf + section.bucketArray[bucketBase + 2];
  44614. } else {
  44615. outCenter.x = x;
  44616. outCenter.y = y;
  44617. outCenter.z = z;
  44618. }
  44619. if (transform) outCenter.applyMatrix4(transform);
  44620. }
  44621. getSplatColor(globalSplatIndex, outColor) {
  44622. var sectionIndex = this.globalSplatIndexToSectionMap[globalSplatIndex];
  44623. var section = this.sections[sectionIndex];
  44624. var localSplatIndex = globalSplatIndex - section.splatCountOffset;
  44625. var srcSplatColorsBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes;
  44626. var splatColorsArray = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase, 4);
  44627. outColor.set(splatColorsArray[0], splatColorsArray[1], splatColorsArray[2], splatColorsArray[3]);
  44628. }
  44629. fillSplatCenterArray(outCenterArray, transform, srcFrom, srcTo, destFrom) {
  44630. var splatCount = this.splatCount;
  44631. srcFrom = srcFrom || 0;
  44632. srcTo = srcTo || splatCount - 1;
  44633. if (destFrom === undefined) destFrom = srcFrom;
  44634. var center = new THREE$2.Vector3();
  44635. for (var i = srcFrom; i <= srcTo; i++) {
  44636. var sectionIndex = this.globalSplatIndexToSectionMap[i];
  44637. var section = this.sections[sectionIndex];
  44638. var localSplatIndex = i - section.splatCountOffset;
  44639. var centerDestBase = (i - srcFrom + destFrom) * SplatBuffer.CenterComponentCount;
  44640. var srcSplatCentersBase = section.bytesPerSplat * localSplatIndex;
  44641. var dataView = new DataView(this.bufferData, section.dataBase + srcSplatCentersBase);
  44642. var x = dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel);
  44643. var y = dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel);
  44644. var z = dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel);
  44645. if (this.compressionLevel >= 1) {
  44646. var bucketIndex = this.getBucketIndex(section, localSplatIndex);
  44647. var bucketBase = bucketIndex * SplatBuffer.BucketStorageSizeFloats;
  44648. var sf = section.compressionScaleFactor;
  44649. var sr = section.compressionScaleRange;
  44650. center.x = (x - sr) * sf + section.bucketArray[bucketBase];
  44651. center.y = (y - sr) * sf + section.bucketArray[bucketBase + 1];
  44652. center.z = (z - sr) * sf + section.bucketArray[bucketBase + 2];
  44653. } else {
  44654. center.x = x;
  44655. center.y = y;
  44656. center.z = z;
  44657. }
  44658. if (transform) {
  44659. center.applyMatrix4(transform);
  44660. }
  44661. outCenterArray[centerDestBase] = center.x;
  44662. outCenterArray[centerDestBase + 1] = center.y;
  44663. outCenterArray[centerDestBase + 2] = center.z;
  44664. }
  44665. }
  44666. fillSplatCovarianceArray(covarianceArray, transform, srcFrom, srcTo, destFrom, desiredOutputCompressionLevel) {
  44667. var splatCount = this.splatCount;
  44668. var scale = new THREE$2.Vector3();
  44669. var rotation = new THREE$2.Quaternion();
  44670. srcFrom = srcFrom || 0;
  44671. srcTo = srcTo || splatCount - 1;
  44672. if (destFrom === undefined) destFrom = srcFrom;
  44673. for (var i = srcFrom; i <= srcTo; i++) {
  44674. var sectionIndex = this.globalSplatIndexToSectionMap[i];
  44675. var section = this.sections[sectionIndex];
  44676. var localSplatIndex = i - section.splatCountOffset;
  44677. var covarianceDestBase = (i - srcFrom + destFrom) * SplatBuffer.CovarianceComponentCount;
  44678. var srcSplatScalesBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ScaleOffsetBytes;
  44679. var dataView = new DataView(this.bufferData, section.dataBase + srcSplatScalesBase);
  44680. scale.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 0, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 1, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 2, this.compressionLevel), this.compressionLevel));
  44681. rotation.set(toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 4, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 5, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 6, this.compressionLevel), this.compressionLevel), toUncompressedFloat(dataViewFloatForCompressionLevel(dataView, 3, this.compressionLevel), this.compressionLevel));
  44682. SplatBuffer.computeCovariance(scale, rotation, transform, covarianceArray, covarianceDestBase, desiredOutputCompressionLevel);
  44683. }
  44684. }
  44685. fillSplatColorArray(outColorArray, minimumAlpha, srcFrom, srcTo, destFrom) {
  44686. var splatCount = this.splatCount;
  44687. srcFrom = srcFrom || 0;
  44688. srcTo = srcTo || splatCount - 1;
  44689. if (destFrom === undefined) destFrom = srcFrom;
  44690. for (var i = srcFrom; i <= srcTo; i++) {
  44691. var sectionIndex = this.globalSplatIndexToSectionMap[i];
  44692. var section = this.sections[sectionIndex];
  44693. var localSplatIndex = i - section.splatCountOffset;
  44694. var colorDestBase = (i - srcFrom + destFrom) * SplatBuffer.ColorComponentCount;
  44695. var srcSplatColorsBase = section.bytesPerSplat * localSplatIndex + SplatBuffer.CompressionLevels[this.compressionLevel].ColorOffsetBytes;
  44696. var dataView = new Uint8Array(this.bufferData, section.dataBase + srcSplatColorsBase);
  44697. var alpha = dataView[3];
  44698. alpha = alpha >= minimumAlpha ? alpha : 0;
  44699. outColorArray[colorDestBase] = dataView[0];
  44700. outColorArray[colorDestBase + 1] = dataView[1];
  44701. outColorArray[colorDestBase + 2] = dataView[2];
  44702. outColorArray[colorDestBase + 3] = alpha;
  44703. }
  44704. }
  44705. static parseHeader(buffer) {
  44706. var headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes);
  44707. var headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2);
  44708. var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  44709. var headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  44710. var versionMajor = headerArrayUint8[0];
  44711. var versionMinor = headerArrayUint8[1];
  44712. var maxSectionCount = headerArrayUint32[1];
  44713. var sectionCount = headerArrayUint32[2];
  44714. var maxSplatCount = headerArrayUint32[3];
  44715. var splatCount = headerArrayUint32[4];
  44716. var compressionLevel = headerArrayUint16[10];
  44717. var sceneCenter = new THREE$2.Vector3(headerArrayFloat32[6], headerArrayFloat32[7], headerArrayFloat32[8]);
  44718. return {
  44719. versionMajor,
  44720. versionMinor,
  44721. maxSectionCount,
  44722. sectionCount,
  44723. maxSplatCount,
  44724. splatCount,
  44725. compressionLevel,
  44726. sceneCenter
  44727. };
  44728. }
  44729. static writeHeaderCountsToBuffer(sectionCount, splatCount, buffer) {
  44730. var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  44731. headerArrayUint32[2] = sectionCount;
  44732. headerArrayUint32[4] = splatCount;
  44733. }
  44734. static writeHeaderToBuffer(header, buffer) {
  44735. var headerArrayUint8 = new Uint8Array(buffer, 0, SplatBuffer.HeaderSizeBytes);
  44736. var headerArrayUint16 = new Uint16Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 2);
  44737. var headerArrayUint32 = new Uint32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  44738. var headerArrayFloat32 = new Float32Array(buffer, 0, SplatBuffer.HeaderSizeBytes / 4);
  44739. headerArrayUint8[0] = header.versionMajor;
  44740. headerArrayUint8[1] = header.versionMinor;
  44741. headerArrayUint8[2] = 0; // unused for now
  44742. headerArrayUint8[3] = 0; // unused for now
  44743. headerArrayUint32[1] = header.maxSectionCount;
  44744. headerArrayUint32[2] = header.sectionCount;
  44745. headerArrayUint32[3] = header.maxSplatCount;
  44746. headerArrayUint32[4] = header.splatCount;
  44747. headerArrayUint16[10] = header.compressionLevel;
  44748. headerArrayFloat32[6] = header.sceneCenter.x;
  44749. headerArrayFloat32[7] = header.sceneCenter.y;
  44750. headerArrayFloat32[8] = header.sceneCenter.z;
  44751. }
  44752. static parseSectionHeaders(header, buffer) {
  44753. var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  44754. var secLoadedCountsToMax = arguments.length > 3 ? arguments[3] : undefined;
  44755. var compressionLevel = header.compressionLevel;
  44756. var maxSectionCount = header.maxSectionCount;
  44757. var sectionHeaderArrayUint16 = new Uint16Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 2);
  44758. var sectionHeaderArrayUint32 = new Uint32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4);
  44759. var sectionHeaderArrayFloat32 = new Float32Array(buffer, offset, maxSectionCount * SplatBuffer.SectionHeaderSizeBytes / 4);
  44760. var sectionHeaders = [];
  44761. var sectionHeaderBase = 0;
  44762. var sectionHeaderBaseUint16 = sectionHeaderBase / 2;
  44763. var sectionHeaderBaseUint32 = sectionHeaderBase / 4;
  44764. var sectionBase = SplatBuffer.HeaderSizeBytes + header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes;
  44765. var splatCountOffset = 0;
  44766. for (var i = 0; i < maxSectionCount; i++) {
  44767. var maxSplatCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 1];
  44768. var bucketSize = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 2];
  44769. var bucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 3];
  44770. var bucketBlockSize = sectionHeaderArrayFloat32[sectionHeaderBaseUint32 + 4];
  44771. var halfBucketBlockSize = bucketBlockSize / 2.0;
  44772. var bucketStorageSizeBytes = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 10];
  44773. var compressionScaleRange = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 6] || SplatBuffer.CompressionLevels[compressionLevel].ScaleRange;
  44774. var fullBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 8];
  44775. var partiallyFilledBucketCount = sectionHeaderArrayUint32[sectionHeaderBaseUint32 + 9];
  44776. var bucketsMetaDataSizeBytes = partiallyFilledBucketCount * 4;
  44777. var bucketsStorageSizeBytes = bucketStorageSizeBytes * bucketCount + bucketsMetaDataSizeBytes;
  44778. var sphericalHarmonicsDegree = sectionHeaderArrayUint16[sectionHeaderBaseUint16 + 20];
  44779. var {
  44780. bytesPerSplat
  44781. } = SplatBuffer.calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree);
  44782. var splatDataStorageSizeBytes = bytesPerSplat * maxSplatCount;
  44783. var storageSizeBytes = splatDataStorageSizeBytes + bucketsStorageSizeBytes;
  44784. var sectionHeader = {
  44785. bytesPerSplat: bytesPerSplat,
  44786. splatCountOffset: splatCountOffset,
  44787. splatCount: secLoadedCountsToMax ? maxSplatCount : 0,
  44788. maxSplatCount: maxSplatCount,
  44789. bucketSize: bucketSize,
  44790. bucketCount: bucketCount,
  44791. bucketBlockSize: bucketBlockSize,
  44792. halfBucketBlockSize: halfBucketBlockSize,
  44793. bucketStorageSizeBytes: bucketStorageSizeBytes,
  44794. bucketsStorageSizeBytes: bucketsStorageSizeBytes,
  44795. splatDataStorageSizeBytes: splatDataStorageSizeBytes,
  44796. storageSizeBytes: storageSizeBytes,
  44797. compressionScaleRange: compressionScaleRange,
  44798. compressionScaleFactor: halfBucketBlockSize / compressionScaleRange,
  44799. base: sectionBase,
  44800. bucketsBase: sectionBase + bucketsMetaDataSizeBytes,
  44801. dataBase: sectionBase + bucketsStorageSizeBytes,
  44802. fullBucketCount: fullBucketCount,
  44803. partiallyFilledBucketCount: partiallyFilledBucketCount,
  44804. sphericalHarmonicsDegree: sphericalHarmonicsDegree
  44805. };
  44806. sectionHeaders[i] = sectionHeader;
  44807. sectionBase += storageSizeBytes;
  44808. sectionHeaderBase += SplatBuffer.SectionHeaderSizeBytes;
  44809. sectionHeaderBaseUint16 = sectionHeaderBase / 2;
  44810. sectionHeaderBaseUint32 = sectionHeaderBase / 4;
  44811. splatCountOffset += maxSplatCount;
  44812. }
  44813. return sectionHeaders;
  44814. }
  44815. static writeSectionHeaderToBuffer(sectionHeader, compressionLevel, buffer) {
  44816. var offset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  44817. var sectionHeadeArrayUint16 = new Uint16Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 2);
  44818. var sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  44819. var sectionHeadeArrayFloat32 = new Float32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  44820. sectionHeadeArrayUint32[0] = sectionHeader.splatCount;
  44821. sectionHeadeArrayUint32[1] = sectionHeader.maxSplatCount;
  44822. sectionHeadeArrayUint32[2] = compressionLevel >= 1 ? sectionHeader.bucketSize : 0;
  44823. sectionHeadeArrayUint32[3] = compressionLevel >= 1 ? sectionHeader.bucketCount : 0;
  44824. sectionHeadeArrayFloat32[4] = compressionLevel >= 1 ? sectionHeader.bucketBlockSize : 0.0;
  44825. sectionHeadeArrayUint16[10] = compressionLevel >= 1 ? SplatBuffer.BucketStorageSizeBytes : 0;
  44826. sectionHeadeArrayUint32[6] = compressionLevel >= 1 ? sectionHeader.compressionScaleRange : 0;
  44827. sectionHeadeArrayUint32[7] = sectionHeader.storageSizeBytes;
  44828. sectionHeadeArrayUint32[8] = compressionLevel >= 1 ? sectionHeader.fullBucketCount : 0;
  44829. sectionHeadeArrayUint32[9] = compressionLevel >= 1 ? sectionHeader.partiallyFilledBucketCount : 0;
  44830. sectionHeadeArrayUint16[20] = sectionHeader.sphericalHarmonicsDegree;
  44831. }
  44832. static writeSectionHeaderSplatCountToBuffer(splatCount, buffer) {
  44833. var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  44834. var sectionHeadeArrayUint32 = new Uint32Array(buffer, offset, SplatBuffer.SectionHeaderSizeBytes / 4);
  44835. sectionHeadeArrayUint32[0] = splatCount;
  44836. }
  44837. constructFromBuffer(bufferData, secLoadedCountsToMax) {
  44838. this.bufferData = bufferData;
  44839. this.globalSplatIndexToLocalSplatIndexMap = [];
  44840. this.globalSplatIndexToSectionMap = [];
  44841. var header = SplatBuffer.parseHeader(this.bufferData);
  44842. this.versionMajor = header.versionMajor;
  44843. this.versionMinor = header.versionMinor;
  44844. this.maxSectionCount = header.maxSectionCount;
  44845. this.sectionCount = secLoadedCountsToMax ? header.maxSectionCount : 0;
  44846. this.maxSplatCount = header.maxSplatCount;
  44847. this.splatCount = secLoadedCountsToMax ? header.maxSplatCount : 0;
  44848. this.compressionLevel = header.compressionLevel;
  44849. this.sceneCenter = new THREE$2.Vector3().copy(header.sceneCenter);
  44850. this.sections = SplatBuffer.parseSectionHeaders(header, this.bufferData, SplatBuffer.HeaderSizeBytes, secLoadedCountsToMax);
  44851. this.linkBufferArrays();
  44852. this.buildMaps();
  44853. }
  44854. static calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree) {
  44855. var bytesPerCenter = SplatBuffer.CompressionLevels[compressionLevel].BytesPerCenter;
  44856. var bytesPerScale = SplatBuffer.CompressionLevels[compressionLevel].BytesPerScale;
  44857. var bytesPerRotation = SplatBuffer.CompressionLevels[compressionLevel].BytesPerRotation;
  44858. var bytesPerColor = SplatBuffer.CompressionLevels[compressionLevel].BytesPerColor;
  44859. var sphericalHarmonicsComponentsPerSplat = getSphericalHarmonicsComponentCountForDegree(sphericalHarmonicsDegree);
  44860. var sphericalHarmonicsBytesPerSplat = SplatBuffer.CompressionLevels[compressionLevel].BytesPerSphericalHarmonicsComponent * sphericalHarmonicsComponentsPerSplat;
  44861. var bytesPerSplat = bytesPerCenter + bytesPerScale + bytesPerRotation + bytesPerColor + sphericalHarmonicsBytesPerSplat;
  44862. return {
  44863. bytesPerCenter,
  44864. bytesPerScale,
  44865. bytesPerRotation,
  44866. bytesPerColor,
  44867. sphericalHarmonicsComponentsPerSplat,
  44868. sphericalHarmonicsBytesPerSplat,
  44869. bytesPerSplat
  44870. };
  44871. }
  44872. linkBufferArrays() {
  44873. for (var i = 0; i < this.maxSectionCount; i++) {
  44874. var section = this.sections[i];
  44875. section.bucketArray = new Float32Array(this.bufferData, section.bucketsBase, section.bucketCount * SplatBuffer.BucketStorageSizeFloats);
  44876. if (section.partiallyFilledBucketCount > 0) {
  44877. section.partiallyFilledBucketLengths = new Uint32Array(this.bufferData, section.base, section.partiallyFilledBucketCount);
  44878. }
  44879. }
  44880. }
  44881. buildMaps() {
  44882. var cumulativeSplatCount = 0;
  44883. for (var i = 0; i < this.maxSectionCount; i++) {
  44884. var section = this.sections[i];
  44885. for (var j = 0; j < section.maxSplatCount; j++) {
  44886. var globalSplatIndex = cumulativeSplatCount + j;
  44887. this.globalSplatIndexToLocalSplatIndexMap[globalSplatIndex] = j;
  44888. this.globalSplatIndexToSectionMap[globalSplatIndex] = i;
  44889. }
  44890. cumulativeSplatCount += section.maxSplatCount;
  44891. }
  44892. }
  44893. updateLoadedCounts(newSectionCount, newSplatCount) {
  44894. SplatBuffer.writeHeaderCountsToBuffer(newSectionCount, newSplatCount, this.bufferData);
  44895. this.sectionCount = newSectionCount;
  44896. this.splatCount = newSplatCount;
  44897. }
  44898. updateSectionLoadedCounts(sectionIndex, newSplatCount) {
  44899. var sectionHeaderOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * sectionIndex;
  44900. SplatBuffer.writeSectionHeaderSplatCountToBuffer(newSplatCount, this.bufferData, sectionHeaderOffset);
  44901. this.sections[sectionIndex].splatCount = newSplatCount;
  44902. }
  44903. static generateFromUncompressedSplatArrays(splatArrays, minimumAlpha, compressionLevel, sceneCenter, blockSize, bucketSize) {
  44904. var options = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : [];
  44905. var copyBetweenBuffers = function copyBetweenBuffers(srcBuffer, srcOffset, destBuffer, destOffset) {
  44906. var byteCount = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  44907. var src = new Uint8Array(srcBuffer, srcOffset);
  44908. var dest = new Uint8Array(destBuffer, destOffset);
  44909. for (var i = 0; i < byteCount; i++) {
  44910. dest[i] = src[i];
  44911. }
  44912. };
  44913. var sphericalHarmonicsDegree = 0;
  44914. for (var sa = 0; sa < splatArrays.length; sa++) {
  44915. var splatArray = splatArrays[sa];
  44916. if (sa === 0 || splatArray.sphericalHarmonicsDegree < sphericalHarmonicsDegree) {
  44917. if (sa > 0 && splatArray.sphericalHarmonicsDegree !== sphericalHarmonicsDegree) {
  44918. var msg = 'SplatBuffer::generateFromUncompressedSplatArrays() -> ' + 'all splat arrays must have the same spherical harmonics degree.';
  44919. throw new Error(msg);
  44920. }
  44921. sphericalHarmonicsDegree = splatArray.sphericalHarmonicsDegree;
  44922. }
  44923. }
  44924. var {
  44925. bytesPerCenter,
  44926. bytesPerScale,
  44927. bytesPerRotation,
  44928. bytesPerColor,
  44929. sphericalHarmonicsComponentsPerSplat,
  44930. sphericalHarmonicsBytesPerSplat,
  44931. bytesPerSplat
  44932. } = SplatBuffer.calculateComponentStorage(compressionLevel, sphericalHarmonicsDegree);
  44933. var compressionScaleRange = SplatBuffer.CompressionLevels[compressionLevel].ScaleRange;
  44934. var sectionBuffers = [];
  44935. var sectionHeaderBuffers = [];
  44936. var totalSplatCount = 0;
  44937. var tempRotation = new THREE$2.Quaternion();
  44938. for (var _sa = 0; _sa < splatArrays.length; _sa++) {
  44939. var _splatArray = splatArrays[_sa];
  44940. var sectionOptions = options[_sa] || {};
  44941. var sectionBlockSize = (sectionOptions.blockSizeFactor || 1) * (blockSize || SplatBuffer.BucketBlockSize);
  44942. var sectionBucketSize = Math.ceil((sectionOptions.bucketSizeFactor || 1) * (bucketSize || SplatBuffer.BucketSize));
  44943. var validSplats = new UncompressedSplatArray(sphericalHarmonicsDegree);
  44944. for (var i = 0; i < _splatArray.splatCount; i++) {
  44945. var targetSplat = _splatArray.splats[i];
  44946. var alpha = void 0;
  44947. if (targetSplat[UncompressedSplatArray.OFFSET.OPACITY]) {
  44948. alpha = targetSplat[UncompressedSplatArray.OFFSET.OPACITY];
  44949. } else {
  44950. alpha = 255;
  44951. }
  44952. if (alpha >= minimumAlpha) {
  44953. validSplats.addSplat(targetSplat);
  44954. }
  44955. }
  44956. var bucketInfo = SplatBuffer.computeBucketsForUncompressedSplatArray(validSplats, sectionBlockSize, sectionBucketSize);
  44957. var fullBucketCount = bucketInfo.fullBuckets.length;
  44958. var partiallyFullBucketLengths = bucketInfo.partiallyFullBuckets.map(bucket => bucket.splats.length);
  44959. var partiallyFilledBucketCount = partiallyFullBucketLengths.length;
  44960. var buckets = [...bucketInfo.fullBuckets, ...bucketInfo.partiallyFullBuckets];
  44961. var sectionDataSizeBytes = validSplats.splats.length * bytesPerSplat;
  44962. var bucketMetaDataSizeBytes = partiallyFilledBucketCount * 4;
  44963. var bucketDataBytes = compressionLevel >= 1 ? buckets.length * SplatBuffer.BucketStorageSizeBytes + bucketMetaDataSizeBytes : 0;
  44964. var sectionSizeBytes = sectionDataSizeBytes + bucketDataBytes;
  44965. var sectionBuffer = new ArrayBuffer(sectionSizeBytes);
  44966. var blockHalfSize = sectionBlockSize / 2.0;
  44967. var compressionScaleFactor = compressionScaleRange / blockHalfSize;
  44968. var doubleCompressionScaleRange = compressionScaleRange * 2 + 1;
  44969. var tempCenterBuffer = new ArrayBuffer(bytesPerCenter);
  44970. var tempScaleBuffer = new ArrayBuffer(bytesPerScale);
  44971. var tempRotationBuffer = new ArrayBuffer(bytesPerRotation);
  44972. var tempColorBuffer = new ArrayBuffer(bytesPerColor);
  44973. var tempSHBuffer = new ArrayBuffer(sphericalHarmonicsBytesPerSplat);
  44974. var bucketCenter = new THREE$2.Vector3();
  44975. var bucketCenterDelta = new THREE$2.Vector3();
  44976. var outSplatCount = 0;
  44977. for (var b = 0; b < buckets.length; b++) {
  44978. var bucket = buckets[b];
  44979. bucketCenter.fromArray(bucket.center);
  44980. for (var _i2 = 0; _i2 < bucket.splats.length; _i2++) {
  44981. var row = bucket.splats[_i2];
  44982. var _targetSplat = validSplats.splats[row];
  44983. var centerBase = bucketDataBytes + outSplatCount * bytesPerSplat;
  44984. var scaleBase = centerBase + bytesPerCenter;
  44985. var rotationBase = scaleBase + bytesPerScale;
  44986. var colorBase = rotationBase + bytesPerRotation;
  44987. var sphericalHarmonicsBase = colorBase + bytesPerColor;
  44988. if (compressionLevel === 0) {
  44989. var center = new Float32Array(sectionBuffer, centerBase, SplatBuffer.CenterComponentCount);
  44990. var rot = new Float32Array(sectionBuffer, rotationBase, SplatBuffer.RotationComponentCount);
  44991. var scale = new Float32Array(sectionBuffer, scaleBase, SplatBuffer.ScaleComponentCount);
  44992. if (_targetSplat[UncompressedSplatArray.OFFSET.SCALE0] !== undefined) {
  44993. tempRotation.set(_targetSplat[UncompressedSplatArray.OFFSET.ROTATION0], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION1], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION2], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION3]);
  44994. tempRotation.normalize();
  44995. rot.set([tempRotation.x, tempRotation.y, tempRotation.z, tempRotation.w]);
  44996. scale.set([_targetSplat[UncompressedSplatArray.OFFSET.SCALE0], _targetSplat[UncompressedSplatArray.OFFSET.SCALE1], _targetSplat[UncompressedSplatArray.OFFSET.SCALE2]]);
  44997. } else {
  44998. rot.set([1.0, 0.0, 0.0, 0.0]);
  44999. scale.set([0.01, 0.01, 0.01]);
  45000. }
  45001. center.set([_targetSplat[UncompressedSplatArray.OFFSET.X], _targetSplat[UncompressedSplatArray.OFFSET.Y], _targetSplat[UncompressedSplatArray.OFFSET.Z]]);
  45002. if (sphericalHarmonicsDegree > 0) {
  45003. var shOut = new Float32Array(sectionBuffer, sphericalHarmonicsBase, sphericalHarmonicsComponentsPerSplat);
  45004. if (sphericalHarmonicsDegree >= 1) {
  45005. for (var s = 0; s < 9; s++) shOut[s] = _targetSplat[UncompressedSplatArray.OFFSET.FRC0 + s];
  45006. if (sphericalHarmonicsDegree >= 2) {
  45007. for (var _s = 0; _s < 15; _s++) shOut[_s + 9] = _targetSplat[UncompressedSplatArray.OFFSET.FRC9 + _s];
  45008. }
  45009. }
  45010. }
  45011. } else {
  45012. var _center = new Uint16Array(tempCenterBuffer, 0, SplatBuffer.CenterComponentCount);
  45013. var _rot = new Uint16Array(tempRotationBuffer, 0, SplatBuffer.RotationComponentCount);
  45014. var _scale = new Uint16Array(tempScaleBuffer, 0, SplatBuffer.ScaleComponentCount);
  45015. if (_targetSplat[UncompressedSplatArray.OFFSET.SCALE0] !== undefined) {
  45016. tempRotation.set(_targetSplat[UncompressedSplatArray.OFFSET.ROTATION0], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION1], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION2], _targetSplat[UncompressedSplatArray.OFFSET.ROTATION3]);
  45017. tempRotation.normalize();
  45018. _rot.set([toHalfFloat(tempRotation.x), toHalfFloat(tempRotation.y), toHalfFloat(tempRotation.z), toHalfFloat(tempRotation.w)]);
  45019. _scale.set([toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE0]), toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE1]), toHalfFloat(_targetSplat[UncompressedSplatArray.OFFSET.SCALE2])]);
  45020. } else {
  45021. _rot.set([toHalfFloat(1.), 0, 0, 0]);
  45022. _scale.set([toHalfFloat(0.01), toHalfFloat(0.01), toHalfFloat(0.01)]);
  45023. }
  45024. bucketCenterDelta.set(_targetSplat[UncompressedSplatArray.OFFSET.X], _targetSplat[UncompressedSplatArray.OFFSET.Y], _targetSplat[UncompressedSplatArray.OFFSET.Z]).sub(bucketCenter);
  45025. bucketCenterDelta.x = Math.round(bucketCenterDelta.x * compressionScaleFactor) + compressionScaleRange;
  45026. bucketCenterDelta.x = clamp(bucketCenterDelta.x, 0, doubleCompressionScaleRange);
  45027. bucketCenterDelta.y = Math.round(bucketCenterDelta.y * compressionScaleFactor) + compressionScaleRange;
  45028. bucketCenterDelta.y = clamp(bucketCenterDelta.y, 0, doubleCompressionScaleRange);
  45029. bucketCenterDelta.z = Math.round(bucketCenterDelta.z * compressionScaleFactor) + compressionScaleRange;
  45030. bucketCenterDelta.z = clamp(bucketCenterDelta.z, 0, doubleCompressionScaleRange);
  45031. _center.set([bucketCenterDelta.x, bucketCenterDelta.y, bucketCenterDelta.z]);
  45032. if (sphericalHarmonicsDegree > 0) {
  45033. var SHArrayType = compressionLevel === 1 ? Uint16Array : Uint8Array;
  45034. var bytesPerSHComponent = compressionLevel === 1 ? 2 : 1;
  45035. var _shOut = new SHArrayType(tempSHBuffer, 0, sphericalHarmonicsComponentsPerSplat);
  45036. if (sphericalHarmonicsDegree >= 1) {
  45037. for (var _s2 = 0; _s2 < 9; _s2++) {
  45038. var srcVal = _targetSplat[UncompressedSplatArray.OFFSET.FRC0 + _s2];
  45039. _shOut[_s2] = compressionLevel === 1 ? toHalfFloat(srcVal) : toUint8(srcVal);
  45040. }
  45041. var degree1ByteCount = 9 * bytesPerSHComponent;
  45042. copyBetweenBuffers(_shOut.buffer, 0, sectionBuffer, sphericalHarmonicsBase, degree1ByteCount);
  45043. if (sphericalHarmonicsDegree >= 2) {
  45044. for (var _s3 = 0; _s3 < 15; _s3++) {
  45045. var _srcVal = _targetSplat[UncompressedSplatArray.OFFSET.FRC9 + _s3];
  45046. _shOut[_s3 + 9] = compressionLevel === 1 ? toHalfFloat(_srcVal) : toUint8(_srcVal);
  45047. }
  45048. var degree2ByteCount = 15 * bytesPerSHComponent;
  45049. copyBetweenBuffers(_shOut.buffer, degree1ByteCount, sectionBuffer, sphericalHarmonicsBase + degree1ByteCount, degree2ByteCount);
  45050. }
  45051. }
  45052. }
  45053. copyBetweenBuffers(_center.buffer, 0, sectionBuffer, centerBase, 6);
  45054. copyBetweenBuffers(_scale.buffer, 0, sectionBuffer, scaleBase, 6);
  45055. copyBetweenBuffers(_rot.buffer, 0, sectionBuffer, rotationBase, 8);
  45056. }
  45057. var rgba = new Uint8ClampedArray(tempColorBuffer, 0, 4);
  45058. if (_targetSplat[UncompressedSplatArray.OFFSET.FDC0] !== undefined) {
  45059. rgba.set([_targetSplat[UncompressedSplatArray.OFFSET.FDC0], _targetSplat[UncompressedSplatArray.OFFSET.FDC1], _targetSplat[UncompressedSplatArray.OFFSET.FDC2]]);
  45060. } else {
  45061. rgba.set([255, 0, 0]);
  45062. }
  45063. if (_targetSplat[UncompressedSplatArray.OFFSET.OPACITY] !== undefined) {
  45064. rgba[3] = _targetSplat[UncompressedSplatArray.OFFSET.OPACITY];
  45065. } else {
  45066. rgba[3] = 255;
  45067. }
  45068. copyBetweenBuffers(rgba.buffer, 0, sectionBuffer, colorBase, 4);
  45069. outSplatCount++;
  45070. }
  45071. }
  45072. totalSplatCount += outSplatCount;
  45073. if (compressionLevel >= 1) {
  45074. var bucketMetaDataArray = new Uint32Array(sectionBuffer, 0, partiallyFullBucketLengths.length * 4);
  45075. for (var pfb = 0; pfb < partiallyFullBucketLengths.length; pfb++) {
  45076. bucketMetaDataArray[pfb] = partiallyFullBucketLengths[pfb];
  45077. }
  45078. var bucketArray = new Float32Array(sectionBuffer, bucketMetaDataSizeBytes, buckets.length * SplatBuffer.BucketStorageSizeFloats);
  45079. for (var _b = 0; _b < buckets.length; _b++) {
  45080. var _bucket = buckets[_b];
  45081. var base = _b * 3;
  45082. bucketArray[base] = _bucket.center[0];
  45083. bucketArray[base + 1] = _bucket.center[1];
  45084. bucketArray[base + 2] = _bucket.center[2];
  45085. }
  45086. }
  45087. sectionBuffers.push(sectionBuffer);
  45088. var sectionHeaderBuffer = new ArrayBuffer(SplatBuffer.SectionHeaderSizeBytes);
  45089. SplatBuffer.writeSectionHeaderToBuffer({
  45090. maxSplatCount: outSplatCount,
  45091. splatCount: outSplatCount,
  45092. bucketSize: sectionBucketSize,
  45093. bucketCount: buckets.length,
  45094. bucketBlockSize: sectionBlockSize,
  45095. compressionScaleRange: compressionScaleRange,
  45096. storageSizeBytes: sectionSizeBytes,
  45097. fullBucketCount: fullBucketCount,
  45098. partiallyFilledBucketCount: partiallyFilledBucketCount,
  45099. sphericalHarmonicsDegree: sphericalHarmonicsDegree
  45100. }, compressionLevel, sectionHeaderBuffer, 0);
  45101. sectionHeaderBuffers.push(sectionHeaderBuffer);
  45102. }
  45103. var sectionsCumulativeSizeBytes = 0;
  45104. for (var _sectionBuffer of sectionBuffers) sectionsCumulativeSizeBytes += _sectionBuffer.byteLength;
  45105. var unifiedBufferSize = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * sectionBuffers.length + sectionsCumulativeSizeBytes;
  45106. var unifiedBuffer = new ArrayBuffer(unifiedBufferSize);
  45107. SplatBuffer.writeHeaderToBuffer({
  45108. versionMajor: 0,
  45109. versionMinor: 1,
  45110. maxSectionCount: sectionBuffers.length,
  45111. sectionCount: sectionBuffers.length,
  45112. maxSplatCount: totalSplatCount,
  45113. splatCount: totalSplatCount,
  45114. compressionLevel: compressionLevel,
  45115. sceneCenter: sceneCenter
  45116. }, unifiedBuffer);
  45117. var currentUnifiedBase = SplatBuffer.HeaderSizeBytes;
  45118. for (var _sectionHeaderBuffer of sectionHeaderBuffers) {
  45119. new Uint8Array(unifiedBuffer, currentUnifiedBase, SplatBuffer.SectionHeaderSizeBytes).set(new Uint8Array(_sectionHeaderBuffer));
  45120. currentUnifiedBase += SplatBuffer.SectionHeaderSizeBytes;
  45121. }
  45122. for (var _sectionBuffer2 of sectionBuffers) {
  45123. new Uint8Array(unifiedBuffer, currentUnifiedBase, _sectionBuffer2.byteLength).set(new Uint8Array(_sectionBuffer2));
  45124. currentUnifiedBase += _sectionBuffer2.byteLength;
  45125. }
  45126. var splatBuffer = new SplatBuffer(unifiedBuffer);
  45127. return splatBuffer;
  45128. }
  45129. static computeBucketsForUncompressedSplatArray(splatArray, blockSize, bucketSize) {
  45130. var splatCount = splatArray.splatCount;
  45131. var halfBlockSize = blockSize / 2.0;
  45132. var min = new THREE$2.Vector3();
  45133. var max = new THREE$2.Vector3();
  45134. for (var i = 0; i < splatCount; i++) {
  45135. var targetSplat = splatArray.splats[i];
  45136. var center = [targetSplat[UncompressedSplatArray.OFFSET.X], targetSplat[UncompressedSplatArray.OFFSET.Y], targetSplat[UncompressedSplatArray.OFFSET.Z]];
  45137. if (i === 0 || center[0] < min.x) min.x = center[0];
  45138. if (i === 0 || center[0] > max.x) max.x = center[0];
  45139. if (i === 0 || center[1] < min.y) min.y = center[1];
  45140. if (i === 0 || center[1] > max.y) max.y = center[1];
  45141. if (i === 0 || center[2] < min.z) min.z = center[2];
  45142. if (i === 0 || center[2] > max.z) max.z = center[2];
  45143. }
  45144. var dimensions = new THREE$2.Vector3().copy(max).sub(min);
  45145. var yBlocks = Math.ceil(dimensions.y / blockSize);
  45146. var zBlocks = Math.ceil(dimensions.z / blockSize);
  45147. var blockCenter = new THREE$2.Vector3();
  45148. var fullBuckets = [];
  45149. var partiallyFullBuckets = {};
  45150. for (var _i3 = 0; _i3 < splatCount; _i3++) {
  45151. var _targetSplat2 = splatArray.splats[_i3];
  45152. var _center2 = [_targetSplat2[UncompressedSplatArray.OFFSET.X], _targetSplat2[UncompressedSplatArray.OFFSET.Y], _targetSplat2[UncompressedSplatArray.OFFSET.Z]];
  45153. var xBlock = Math.floor((_center2[0] - min.x) / blockSize);
  45154. var yBlock = Math.floor((_center2[1] - min.y) / blockSize);
  45155. var zBlock = Math.floor((_center2[2] - min.z) / blockSize);
  45156. blockCenter.x = xBlock * blockSize + min.x + halfBlockSize;
  45157. blockCenter.y = yBlock * blockSize + min.y + halfBlockSize;
  45158. blockCenter.z = zBlock * blockSize + min.z + halfBlockSize;
  45159. var bucketId = xBlock * (yBlocks * zBlocks) + yBlock * zBlocks + zBlock;
  45160. var bucket = partiallyFullBuckets[bucketId];
  45161. if (!bucket) {
  45162. partiallyFullBuckets[bucketId] = bucket = {
  45163. 'splats': [],
  45164. 'center': blockCenter.toArray()
  45165. };
  45166. }
  45167. bucket.splats.push(_i3);
  45168. if (bucket.splats.length >= bucketSize) {
  45169. fullBuckets.push(bucket);
  45170. partiallyFullBuckets[bucketId] = null;
  45171. }
  45172. }
  45173. var partiallyFullBucketArray = [];
  45174. for (var _bucketId in partiallyFullBuckets) {
  45175. if (partiallyFullBuckets.hasOwnProperty(_bucketId)) {
  45176. var _bucket2 = partiallyFullBuckets[_bucketId];
  45177. if (_bucket2) {
  45178. partiallyFullBucketArray.push(_bucket2);
  45179. }
  45180. }
  45181. }
  45182. return {
  45183. 'fullBuckets': fullBuckets,
  45184. 'partiallyFullBuckets': partiallyFullBucketArray
  45185. };
  45186. }
  45187. }
  45188. _SplatBuffer = SplatBuffer;
  45189. _defineProperty(SplatBuffer, "CurrentMajorVersion", 0);
  45190. _defineProperty(SplatBuffer, "CurrentMinorVersion", 1);
  45191. _defineProperty(SplatBuffer, "CenterComponentCount", 3);
  45192. _defineProperty(SplatBuffer, "ScaleComponentCount", 3);
  45193. _defineProperty(SplatBuffer, "RotationComponentCount", 4);
  45194. _defineProperty(SplatBuffer, "ColorComponentCount", 4);
  45195. _defineProperty(SplatBuffer, "CovarianceComponentCount", 6);
  45196. _defineProperty(SplatBuffer, "SplatScaleOffsetFloat", 3);
  45197. _defineProperty(SplatBuffer, "SplatRotationOffsetFloat", 6);
  45198. _defineProperty(SplatBuffer, "CompressionLevels", {
  45199. 0: {
  45200. BytesPerCenter: 12,
  45201. BytesPerScale: 12,
  45202. BytesPerRotation: 16,
  45203. BytesPerColor: 4,
  45204. ScaleOffsetBytes: 12,
  45205. RotationffsetBytes: 24,
  45206. ColorOffsetBytes: 40,
  45207. SphericalHarmonicsOffsetBytes: 44,
  45208. ScaleRange: 1,
  45209. BytesPerSphericalHarmonicsComponent: 4,
  45210. SphericalHarmonicsOffsetFloat: 11,
  45211. SphericalHarmonicsDegrees: {
  45212. 0: {
  45213. BytesPerSplat: 44
  45214. },
  45215. 1: {
  45216. BytesPerSplat: 80
  45217. },
  45218. 2: {
  45219. BytesPerSplat: 140
  45220. }
  45221. }
  45222. },
  45223. 1: {
  45224. BytesPerCenter: 6,
  45225. BytesPerScale: 6,
  45226. BytesPerRotation: 8,
  45227. BytesPerColor: 4,
  45228. ScaleOffsetBytes: 6,
  45229. RotationffsetBytes: 12,
  45230. ColorOffsetBytes: 20,
  45231. SphericalHarmonicsOffsetBytes: 24,
  45232. ScaleRange: 32767,
  45233. BytesPerSphericalHarmonicsComponent: 2,
  45234. SphericalHarmonicsOffsetFloat: 12,
  45235. SphericalHarmonicsDegrees: {
  45236. 0: {
  45237. BytesPerSplat: 24
  45238. },
  45239. 1: {
  45240. BytesPerSplat: 42
  45241. },
  45242. 2: {
  45243. BytesPerSplat: 72
  45244. }
  45245. }
  45246. },
  45247. 2: {
  45248. BytesPerCenter: 6,
  45249. BytesPerScale: 6,
  45250. BytesPerRotation: 8,
  45251. BytesPerColor: 4,
  45252. ScaleOffsetBytes: 6,
  45253. RotationffsetBytes: 12,
  45254. ColorOffsetBytes: 20,
  45255. SphericalHarmonicsOffsetBytes: 24,
  45256. ScaleRange: 32767,
  45257. BytesPerSphericalHarmonicsComponent: 1,
  45258. SphericalHarmonicsOffsetFloat: 12,
  45259. SphericalHarmonicsDegrees: {
  45260. 0: {
  45261. BytesPerSplat: 24
  45262. },
  45263. 1: {
  45264. BytesPerSplat: 33
  45265. },
  45266. 2: {
  45267. BytesPerSplat: 48
  45268. }
  45269. }
  45270. }
  45271. });
  45272. _defineProperty(SplatBuffer, "CovarianceSizeFloats", 6);
  45273. _defineProperty(SplatBuffer, "HeaderSizeBytes", 4096);
  45274. _defineProperty(SplatBuffer, "SectionHeaderSizeBytes", 1024);
  45275. _defineProperty(SplatBuffer, "BucketStorageSizeBytes", 12);
  45276. _defineProperty(SplatBuffer, "BucketStorageSizeFloats", 3);
  45277. _defineProperty(SplatBuffer, "BucketBlockSize", 5.0);
  45278. _defineProperty(SplatBuffer, "BucketSize", 256);
  45279. _defineProperty(SplatBuffer, "computeCovariance", function () {
  45280. //通过旋转和缩放计算协方差(决定姿态)得到6个数
  45281. var tempMatrix4 = new THREE$2.Matrix4();
  45282. var scaleMatrix = new THREE$2.Matrix3();
  45283. var rotationMatrix = new THREE$2.Matrix3();
  45284. var covarianceMatrix = new THREE$2.Matrix3();
  45285. var transformedCovariance = new THREE$2.Matrix3();
  45286. var transform3x3 = new THREE$2.Matrix3();
  45287. var transform3x3Transpose = new THREE$2.Matrix3();
  45288. return function (scale, rotation, transform, outCovariance) {
  45289. var outOffset = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  45290. var desiredOutputCompressionLevel = arguments.length > 5 ? arguments[5] : undefined;
  45291. tempMatrix4.makeScale(scale.x, scale.y, scale.z);
  45292. scaleMatrix.setFromMatrix4(tempMatrix4);
  45293. tempMatrix4.makeRotationFromQuaternion(rotation);
  45294. rotationMatrix.setFromMatrix4(tempMatrix4);
  45295. covarianceMatrix.copy(rotationMatrix).multiply(scaleMatrix);
  45296. transformedCovariance.copy(covarianceMatrix).transpose().premultiply(covarianceMatrix); //为什么要乘以自己的转置呀?
  45297. if (transform) {
  45298. //场景的整体transform
  45299. transform3x3.setFromMatrix4(transform);
  45300. transform3x3Transpose.copy(transform3x3).transpose();
  45301. transformedCovariance.multiply(transform3x3Transpose);
  45302. transformedCovariance.premultiply(transform3x3);
  45303. }
  45304. if (desiredOutputCompressionLevel >= 1) {
  45305. //压缩
  45306. outCovariance[outOffset] = toHalfFloat(transformedCovariance.elements[0]);
  45307. outCovariance[outOffset + 1] = toHalfFloat(transformedCovariance.elements[3]);
  45308. outCovariance[outOffset + 2] = toHalfFloat(transformedCovariance.elements[6]);
  45309. outCovariance[outOffset + 3] = toHalfFloat(transformedCovariance.elements[4]);
  45310. outCovariance[outOffset + 4] = toHalfFloat(transformedCovariance.elements[7]);
  45311. outCovariance[outOffset + 5] = toHalfFloat(transformedCovariance.elements[8]);
  45312. } else {
  45313. outCovariance[outOffset] = transformedCovariance.elements[0];
  45314. outCovariance[outOffset + 1] = transformedCovariance.elements[3];
  45315. outCovariance[outOffset + 2] = transformedCovariance.elements[6];
  45316. outCovariance[outOffset + 3] = transformedCovariance.elements[4];
  45317. outCovariance[outOffset + 4] = transformedCovariance.elements[7];
  45318. outCovariance[outOffset + 5] = transformedCovariance.elements[8];
  45319. }
  45320. };
  45321. }());
  45322. _defineProperty(SplatBuffer, "dot3", (v1, v2, v3, transformRow, outArray) => {
  45323. outArray[0] = outArray[1] = outArray[2] = 0;
  45324. var t0 = transformRow[0];
  45325. var t1 = transformRow[1];
  45326. var t2 = transformRow[2];
  45327. _SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray);
  45328. _SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray);
  45329. _SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray);
  45330. });
  45331. _defineProperty(SplatBuffer, "addInto3", (val1, val2, val3, destArray) => {
  45332. destArray[0] = destArray[0] + val1;
  45333. destArray[1] = destArray[1] + val2;
  45334. destArray[2] = destArray[2] + val3;
  45335. });
  45336. _defineProperty(SplatBuffer, "dot5", (v1, v2, v3, v4, v5, transformRow, outArray) => {
  45337. outArray[0] = outArray[1] = outArray[2] = 0;
  45338. var t0 = transformRow[0];
  45339. var t1 = transformRow[1];
  45340. var t2 = transformRow[2];
  45341. var t3 = transformRow[3];
  45342. var t4 = transformRow[4];
  45343. _SplatBuffer.addInto3(v1[0] * t0, v1[1] * t0, v1[2] * t0, outArray);
  45344. _SplatBuffer.addInto3(v2[0] * t1, v2[1] * t1, v2[2] * t1, outArray);
  45345. _SplatBuffer.addInto3(v3[0] * t2, v3[1] * t2, v3[2] * t2, outArray);
  45346. _SplatBuffer.addInto3(v4[0] * t3, v4[1] * t3, v4[2] * t3, outArray);
  45347. _SplatBuffer.addInto3(v5[0] * t4, v5[1] * t4, v5[2] * t4, outArray);
  45348. });
  45349. _defineProperty(SplatBuffer, "rotateSphericalHarmonics3", (in1, in2, in3, tsh11, tsh12, tsh13, out1, out2, out3) => {
  45350. _SplatBuffer.dot3(in1, in2, in3, tsh11, out1);
  45351. _SplatBuffer.dot3(in1, in2, in3, tsh12, out2);
  45352. _SplatBuffer.dot3(in1, in2, in3, tsh13, out3);
  45353. });
  45354. _defineProperty(SplatBuffer, "rotateSphericalHarmonics5", (in1, in2, in3, in4, in5, tsh11, tsh12, tsh13, tsh21, tsh22, tsh23, tsh24, tsh25, out1, out2, out3, out4, out5) => {
  45355. var kSqrt0104 = Math.sqrt(1.0 / 4.0);
  45356. var kSqrt0304 = Math.sqrt(3.0 / 4.0);
  45357. var kSqrt0103 = Math.sqrt(1.0 / 3.0);
  45358. var kSqrt0403 = Math.sqrt(4.0 / 3.0);
  45359. var kSqrt0112 = Math.sqrt(1.0 / 12.0);
  45360. tsh21[0] = kSqrt0104 * (tsh13[2] * tsh11[0] + tsh13[0] * tsh11[2] + (tsh11[2] * tsh13[0] + tsh11[0] * tsh13[2]));
  45361. tsh21[1] = tsh13[1] * tsh11[0] + tsh11[1] * tsh13[0];
  45362. tsh21[2] = kSqrt0304 * (tsh13[1] * tsh11[1] + tsh11[1] * tsh13[1]);
  45363. tsh21[3] = tsh13[1] * tsh11[2] + tsh11[1] * tsh13[2];
  45364. tsh21[4] = kSqrt0104 * (tsh13[2] * tsh11[2] - tsh13[0] * tsh11[0] + (tsh11[2] * tsh13[2] - tsh11[0] * tsh13[0]));
  45365. _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh21, out1);
  45366. tsh22[0] = kSqrt0104 * (tsh12[2] * tsh11[0] + tsh12[0] * tsh11[2] + (tsh11[2] * tsh12[0] + tsh11[0] * tsh12[2]));
  45367. tsh22[1] = tsh12[1] * tsh11[0] + tsh11[1] * tsh12[0];
  45368. tsh22[2] = kSqrt0304 * (tsh12[1] * tsh11[1] + tsh11[1] * tsh12[1]);
  45369. tsh22[3] = tsh12[1] * tsh11[2] + tsh11[1] * tsh12[2];
  45370. tsh22[4] = kSqrt0104 * (tsh12[2] * tsh11[2] - tsh12[0] * tsh11[0] + (tsh11[2] * tsh12[2] - tsh11[0] * tsh12[0]));
  45371. _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh22, out2);
  45372. tsh23[0] = kSqrt0103 * (tsh12[2] * tsh12[0] + tsh12[0] * tsh12[2]) + -kSqrt0112 * (tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2] + (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2]));
  45373. tsh23[1] = kSqrt0403 * tsh12[1] * tsh12[0] + -kSqrt0103 * (tsh13[1] * tsh13[0] + tsh11[1] * tsh11[0]);
  45374. tsh23[2] = tsh12[1] * tsh12[1] + -kSqrt0104 * (tsh13[1] * tsh13[1] + tsh11[1] * tsh11[1]);
  45375. tsh23[3] = kSqrt0403 * tsh12[1] * tsh12[2] + -kSqrt0103 * (tsh13[1] * tsh13[2] + tsh11[1] * tsh11[2]);
  45376. tsh23[4] = kSqrt0103 * (tsh12[2] * tsh12[2] - tsh12[0] * tsh12[0]) + -kSqrt0112 * (tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0] + (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0]));
  45377. _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh23, out3);
  45378. tsh24[0] = kSqrt0104 * (tsh12[2] * tsh13[0] + tsh12[0] * tsh13[2] + (tsh13[2] * tsh12[0] + tsh13[0] * tsh12[2]));
  45379. tsh24[1] = tsh12[1] * tsh13[0] + tsh13[1] * tsh12[0];
  45380. tsh24[2] = kSqrt0304 * (tsh12[1] * tsh13[1] + tsh13[1] * tsh12[1]);
  45381. tsh24[3] = tsh12[1] * tsh13[2] + tsh13[1] * tsh12[2];
  45382. tsh24[4] = kSqrt0104 * (tsh12[2] * tsh13[2] - tsh12[0] * tsh13[0] + (tsh13[2] * tsh12[2] - tsh13[0] * tsh12[0]));
  45383. _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh24, out4);
  45384. tsh25[0] = kSqrt0104 * (tsh13[2] * tsh13[0] + tsh13[0] * tsh13[2] - (tsh11[2] * tsh11[0] + tsh11[0] * tsh11[2]));
  45385. tsh25[1] = tsh13[1] * tsh13[0] - tsh11[1] * tsh11[0];
  45386. tsh25[2] = kSqrt0304 * (tsh13[1] * tsh13[1] - tsh11[1] * tsh11[1]);
  45387. tsh25[3] = tsh13[1] * tsh13[2] - tsh11[1] * tsh11[2];
  45388. tsh25[4] = kSqrt0104 * (tsh13[2] * tsh13[2] - tsh13[0] * tsh13[0] - (tsh11[2] * tsh11[2] - tsh11[0] * tsh11[0]));
  45389. _SplatBuffer.dot5(in1, in2, in3, in4, in5, tsh25, out5);
  45390. });
  45391. var HeaderMagicBytes = new Uint8Array([112, 108, 121, 10]);
  45392. var HeaderEndTokenBytes = new Uint8Array([10, 101, 110, 100, 95, 104, 101, 97, 100, 101, 114, 10]);
  45393. var HeaderEndToken = 'end_header';
  45394. var DataTypeMap = new Map([['char', Int8Array], ['uchar', Uint8Array], ['short', Int16Array], ['ushort', Uint16Array], ['int', Int32Array], ['uint', Uint32Array], ['float', Float32Array], ['double', Float64Array]]);
  45395. var unpackUnorm = (value, bits) => {
  45396. var t = (1 << bits) - 1;
  45397. return (value & t) / t;
  45398. };
  45399. var unpack111011 = (result, value) => {
  45400. result.x = unpackUnorm(value >>> 21, 11);
  45401. result.y = unpackUnorm(value >>> 11, 10);
  45402. result.z = unpackUnorm(value, 11);
  45403. };
  45404. var unpack8888 = (result, value) => {
  45405. result.x = unpackUnorm(value >>> 24, 8);
  45406. result.y = unpackUnorm(value >>> 16, 8);
  45407. result.z = unpackUnorm(value >>> 8, 8);
  45408. result.w = unpackUnorm(value, 8);
  45409. };
  45410. // unpack quaternion with 2,10,10,10 format (largest element, 3x10bit element)
  45411. var unpackRot = (result, value) => {
  45412. var norm = 1.0 / (Math.sqrt(2) * 0.5);
  45413. var a = (unpackUnorm(value >>> 20, 10) - 0.5) * norm;
  45414. var b = (unpackUnorm(value >>> 10, 10) - 0.5) * norm;
  45415. var c = (unpackUnorm(value, 10) - 0.5) * norm;
  45416. var m = Math.sqrt(1.0 - (a * a + b * b + c * c));
  45417. switch (value >>> 30) {
  45418. case 0:
  45419. result.set(m, a, b, c);
  45420. break;
  45421. case 1:
  45422. result.set(a, m, b, c);
  45423. break;
  45424. case 2:
  45425. result.set(a, b, m, c);
  45426. break;
  45427. case 3:
  45428. result.set(a, b, c, m);
  45429. break;
  45430. }
  45431. };
  45432. var lerp$1 = (a, b, t) => {
  45433. return a * (1 - t) + b * t;
  45434. };
  45435. var getElementPropStorage = (element, name) => {
  45436. var _element$properties$f;
  45437. return (_element$properties$f = element.properties.find(p => p.name === name && p.storage)) === null || _element$properties$f === void 0 ? void 0 : _element$properties$f.storage;
  45438. };
  45439. class CompressedPlyParser {
  45440. static decodeHeaderText(headerText) {
  45441. var element;
  45442. var chunkElement;
  45443. var vertexElement;
  45444. var headerLines = headerText.split('\n').filter(line => !line.startsWith('comment '));
  45445. var bytesPerSplat = 0;
  45446. var done = false;
  45447. for (var i = 1; i < headerLines.length; ++i) {
  45448. var words = headerLines[i].split(' ');
  45449. switch (words[0]) {
  45450. case 'format':
  45451. if (words[1] !== 'binary_little_endian') {
  45452. throw new Error('Unsupported ply format');
  45453. }
  45454. break;
  45455. case 'element':
  45456. element = {
  45457. name: words[1],
  45458. count: parseInt(words[2], 10),
  45459. properties: [],
  45460. storageSizeBytes: 0
  45461. };
  45462. if (element.name === 'chunk') chunkElement = element;else if (element.name === 'vertex') vertexElement = element;
  45463. break;
  45464. case 'property':
  45465. {
  45466. if (!DataTypeMap.has(words[1])) {
  45467. throw new Error("Unrecognized property data type '".concat(words[1], "' in ply header"));
  45468. }
  45469. var StorageType = DataTypeMap.get(words[1]);
  45470. var storageSizeByes = StorageType.BYTES_PER_ELEMENT * element.count;
  45471. if (element.name === 'vertex') bytesPerSplat += StorageType.BYTES_PER_ELEMENT;
  45472. element.properties.push({
  45473. type: words[1],
  45474. name: words[2],
  45475. storage: null,
  45476. byteSize: StorageType.BYTES_PER_ELEMENT,
  45477. storageSizeByes: storageSizeByes
  45478. });
  45479. element.storageSizeBytes += storageSizeByes;
  45480. break;
  45481. }
  45482. case HeaderEndToken:
  45483. done = true;
  45484. break;
  45485. default:
  45486. throw new Error("Unrecognized header value '".concat(words[0], "' in ply header"));
  45487. }
  45488. if (done) break;
  45489. }
  45490. return {
  45491. 'chunkElement': chunkElement,
  45492. 'vertexElement': vertexElement,
  45493. 'bytesPerSplat': bytesPerSplat,
  45494. 'headerSizeBytes': headerText.indexOf(HeaderEndToken) + HeaderEndToken.length + 1
  45495. };
  45496. }
  45497. static decodeHeader(plyBuffer) {
  45498. /**
  45499. * Searches for the first occurrence of a sequence within a buffer.
  45500. * @example
  45501. * find(new Uint8Array([1, 2, 3, 4]), new Uint8Array([3, 4])); // 2
  45502. * @param {Uint8Array} buf - The buffer in which to search.
  45503. * @param {Uint8Array} search - The sequence to search for.
  45504. * @return {number} The index of the first occurrence of the search sequence in the buffer, or -1 if not found.
  45505. */
  45506. var find = (buf, search) => {
  45507. var endIndex = buf.length - search.length;
  45508. var i;
  45509. var j;
  45510. for (i = 0; i <= endIndex; ++i) {
  45511. for (j = 0; j < search.length; ++j) {
  45512. if (buf[i + j] !== search[j]) {
  45513. break;
  45514. }
  45515. }
  45516. if (j === search.length) {
  45517. return i;
  45518. }
  45519. }
  45520. return -1;
  45521. };
  45522. /**
  45523. * Checks if array 'a' starts with the same elements as array 'b'.
  45524. * @example
  45525. * startsWith(new Uint8Array([1, 2, 3, 4]), new Uint8Array([1, 2])); // true
  45526. * @param {Uint8Array} a - The array to check against.
  45527. * @param {Uint8Array} b - The array of elements to look for at the start of 'a'.
  45528. * @return {boolean} - True if 'a' starts with all elements of 'b', otherwise false.
  45529. */
  45530. var startsWith = (a, b) => {
  45531. if (a.length < b.length) {
  45532. return false;
  45533. }
  45534. for (var i = 0; i < b.length; ++i) {
  45535. if (a[i] !== b[i]) {
  45536. return false;
  45537. }
  45538. }
  45539. return true;
  45540. };
  45541. var buf = new Uint8Array(plyBuffer);
  45542. var endHeaderTokenOffset;
  45543. if (buf.length >= HeaderMagicBytes.length && !startsWith(buf, HeaderMagicBytes)) {
  45544. throw new Error('Invalid PLY header');
  45545. }
  45546. endHeaderTokenOffset = find(buf, HeaderEndTokenBytes);
  45547. if (endHeaderTokenOffset === -1) {
  45548. throw new Error('End of PLY header not found');
  45549. }
  45550. var headerText = new TextDecoder('ascii').decode(buf.slice(0, endHeaderTokenOffset));
  45551. var {
  45552. chunkElement,
  45553. vertexElement,
  45554. bytesPerSplat
  45555. } = CompressedPlyParser.decodeHeaderText(headerText);
  45556. return {
  45557. 'headerSizeBytes': endHeaderTokenOffset + HeaderEndTokenBytes.length,
  45558. 'bytesPerSplat': bytesPerSplat,
  45559. 'chunkElement': chunkElement,
  45560. 'vertexElement': vertexElement
  45561. };
  45562. }
  45563. static readElementData(element, readBuffer, readOffset, fromIndex, toIndex) {
  45564. var propertyFilter = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null;
  45565. var dataView = readBuffer instanceof DataView ? readBuffer : new DataView(readBuffer);
  45566. fromIndex = fromIndex || 0;
  45567. toIndex = toIndex || element.count - 1;
  45568. for (var e = fromIndex; e <= toIndex; ++e) {
  45569. for (var j = 0; j < element.properties.length; ++j) {
  45570. var property = element.properties[j];
  45571. var StorageType = DataTypeMap.get(property.type);
  45572. var requiredStorageSizeBytes = StorageType.BYTES_PER_ELEMENT * element.count;
  45573. if ((!property.storage || property.storage.byteLength < requiredStorageSizeBytes) && (!propertyFilter || propertyFilter(property.name))) {
  45574. property.storage = new StorageType(element.count);
  45575. }
  45576. if (property.storage) {
  45577. switch (property.type) {
  45578. case 'char':
  45579. property.storage[e] = dataView.getInt8(readOffset);
  45580. break;
  45581. case 'uchar':
  45582. property.storage[e] = dataView.getUint8(readOffset);
  45583. break;
  45584. case 'short':
  45585. property.storage[e] = dataView.getInt16(readOffset, true);
  45586. break;
  45587. case 'ushort':
  45588. property.storage[e] = dataView.getUint16(readOffset, true);
  45589. break;
  45590. case 'int':
  45591. property.storage[e] = dataView.getInt32(readOffset, true);
  45592. break;
  45593. case 'uint':
  45594. property.storage[e] = dataView.getUint32(readOffset, true);
  45595. break;
  45596. case 'float':
  45597. property.storage[e] = dataView.getFloat32(readOffset, true);
  45598. break;
  45599. case 'double':
  45600. property.storage[e] = dataView.getFloat64(readOffset, true);
  45601. break;
  45602. }
  45603. }
  45604. readOffset += property.byteSize;
  45605. }
  45606. }
  45607. return readOffset;
  45608. }
  45609. static readPly(plyBuffer) {
  45610. var propertyFilter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  45611. var header = CompressedPlyParser.decodeHeader(plyBuffer);
  45612. var readIndex = CompressedPlyParser.readElementData(header.chunkElement, plyBuffer, header.headerSizeBytes, null, null, propertyFilter);
  45613. CompressedPlyParser.readElementData(header.vertexElement, plyBuffer, readIndex, null, null, propertyFilter);
  45614. return {
  45615. 'chunkElement': header.chunkElement,
  45616. 'vertexElement': header.vertexElement
  45617. };
  45618. }
  45619. static getElementStorageArrays(chunkElement, vertexElement) {
  45620. var minX = getElementPropStorage(chunkElement, 'min_x');
  45621. var minY = getElementPropStorage(chunkElement, 'min_y');
  45622. var minZ = getElementPropStorage(chunkElement, 'min_z');
  45623. var maxX = getElementPropStorage(chunkElement, 'max_x');
  45624. var maxY = getElementPropStorage(chunkElement, 'max_y');
  45625. var maxZ = getElementPropStorage(chunkElement, 'max_z');
  45626. var minScaleX = getElementPropStorage(chunkElement, 'min_scale_x');
  45627. var minScaleY = getElementPropStorage(chunkElement, 'min_scale_y');
  45628. var minScaleZ = getElementPropStorage(chunkElement, 'min_scale_z');
  45629. var maxScaleX = getElementPropStorage(chunkElement, 'max_scale_x');
  45630. var maxScaleY = getElementPropStorage(chunkElement, 'max_scale_y');
  45631. var maxScaleZ = getElementPropStorage(chunkElement, 'max_scale_z');
  45632. var position = getElementPropStorage(vertexElement, 'packed_position');
  45633. var rotation = getElementPropStorage(vertexElement, 'packed_rotation');
  45634. var scale = getElementPropStorage(vertexElement, 'packed_scale');
  45635. var color = getElementPropStorage(vertexElement, 'packed_color');
  45636. return {
  45637. positionExtremes: {
  45638. minX,
  45639. maxX,
  45640. minY,
  45641. maxY,
  45642. minZ,
  45643. maxZ
  45644. },
  45645. scaleExtremes: {
  45646. minScaleX,
  45647. maxScaleX,
  45648. minScaleY,
  45649. maxScaleY,
  45650. minScaleZ,
  45651. maxScaleZ
  45652. },
  45653. position,
  45654. rotation,
  45655. scale,
  45656. color
  45657. };
  45658. }
  45659. static parseToUncompressedSplatBufferSection(chunkElement, vertexElement, fromIndex, toIndex, chunkSplatIndexOffset, vertexDataBuffer, veretxReadOffset, outBuffer, outOffset) {
  45660. var propertyFilter = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null;
  45661. CompressedPlyParser.readElementData(vertexElement, vertexDataBuffer, veretxReadOffset, fromIndex, toIndex, propertyFilter);
  45662. var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter;
  45663. var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale;
  45664. var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation;
  45665. var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  45666. var {
  45667. positionExtremes,
  45668. scaleExtremes,
  45669. position,
  45670. rotation,
  45671. scale,
  45672. color
  45673. } = CompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement);
  45674. var OFFSET = UncompressedSplatArray.OFFSET;
  45675. var tempSplat = UncompressedSplatArray.createSplat();
  45676. for (var i = fromIndex; i <= toIndex; ++i) {
  45677. CompressedPlyParser.decompressSplat(i, chunkSplatIndexOffset, position, positionExtremes, scale, scaleExtremes, rotation, color, tempSplat);
  45678. var outBase = i * outBytesPerSplat + outOffset;
  45679. var outCenter = new Float32Array(outBuffer, outBase, 3);
  45680. var outScale = new Float32Array(outBuffer, outBase + outBytesPerCenter, 3);
  45681. var outRotation = new Float32Array(outBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4);
  45682. var outColor = new Uint8Array(outBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4);
  45683. outCenter[0] = tempSplat[OFFSET.X];
  45684. outCenter[1] = tempSplat[OFFSET.Y];
  45685. outCenter[2] = tempSplat[OFFSET.Z];
  45686. outScale[0] = tempSplat[OFFSET.SCALE0];
  45687. outScale[1] = tempSplat[OFFSET.SCALE1];
  45688. outScale[2] = tempSplat[OFFSET.SCALE2];
  45689. outRotation[0] = tempSplat[OFFSET.ROTATION0];
  45690. outRotation[1] = tempSplat[OFFSET.ROTATION1];
  45691. outRotation[2] = tempSplat[OFFSET.ROTATION2];
  45692. outRotation[3] = tempSplat[OFFSET.ROTATION3];
  45693. outColor[0] = tempSplat[OFFSET.FDC0];
  45694. outColor[1] = tempSplat[OFFSET.FDC1];
  45695. outColor[2] = tempSplat[OFFSET.FDC2];
  45696. outColor[3] = tempSplat[OFFSET.OPACITY];
  45697. }
  45698. }
  45699. static parseToUncompressedSplatArray(plyBuffer) {
  45700. var {
  45701. chunkElement,
  45702. vertexElement
  45703. } = CompressedPlyParser.readPly(plyBuffer);
  45704. var splatArray = new UncompressedSplatArray();
  45705. var {
  45706. positionExtremes,
  45707. scaleExtremes,
  45708. position,
  45709. rotation,
  45710. scale,
  45711. color
  45712. } = CompressedPlyParser.getElementStorageArrays(chunkElement, vertexElement);
  45713. for (var i = 0; i < vertexElement.count; ++i) {
  45714. splatArray.addDefaultSplat();
  45715. var newSplat = splatArray.getSplat(splatArray.splatCount - 1);
  45716. CompressedPlyParser.decompressSplat(i, 0, position, positionExtremes, scale, scaleExtremes, rotation, color, newSplat);
  45717. }
  45718. var mat = new THREE$2.Matrix4();
  45719. mat.identity();
  45720. return splatArray;
  45721. }
  45722. }
  45723. _defineProperty(CompressedPlyParser, "decompressSplat", function () {
  45724. var p = new THREE$2.Vector3();
  45725. var r = new THREE$2.Quaternion();
  45726. var s = new THREE$2.Vector3();
  45727. var c = new THREE$2.Vector4();
  45728. var OFFSET = UncompressedSplatArray.OFFSET;
  45729. return function (index, chunkSplatIndexOffset, positionArray, positionExtremes, scaleArray, scaleExtremes, rotationArray, colorArray, outSplat) {
  45730. outSplat = outSplat || UncompressedSplatArray.createSplat();
  45731. var chunkIndex = Math.floor((chunkSplatIndexOffset + index) / 256);
  45732. unpack111011(p, positionArray[index]);
  45733. unpackRot(r, rotationArray[index]);
  45734. unpack111011(s, scaleArray[index]);
  45735. unpack8888(c, colorArray[index]);
  45736. outSplat[OFFSET.X] = lerp$1(positionExtremes.minX[chunkIndex], positionExtremes.maxX[chunkIndex], p.x);
  45737. outSplat[OFFSET.Y] = lerp$1(positionExtremes.minY[chunkIndex], positionExtremes.maxY[chunkIndex], p.y);
  45738. outSplat[OFFSET.Z] = lerp$1(positionExtremes.minZ[chunkIndex], positionExtremes.maxZ[chunkIndex], p.z);
  45739. outSplat[OFFSET.ROTATION0] = r.x;
  45740. outSplat[OFFSET.ROTATION1] = r.y;
  45741. outSplat[OFFSET.ROTATION2] = r.z;
  45742. outSplat[OFFSET.ROTATION3] = r.w;
  45743. outSplat[OFFSET.SCALE0] = Math.exp(lerp$1(scaleExtremes.minScaleX[chunkIndex], scaleExtremes.maxScaleX[chunkIndex], s.x));
  45744. outSplat[OFFSET.SCALE1] = Math.exp(lerp$1(scaleExtremes.minScaleY[chunkIndex], scaleExtremes.maxScaleY[chunkIndex], s.y));
  45745. outSplat[OFFSET.SCALE2] = Math.exp(lerp$1(scaleExtremes.minScaleZ[chunkIndex], scaleExtremes.maxScaleZ[chunkIndex], s.z));
  45746. outSplat[OFFSET.FDC0] = clamp(Math.floor(c.x * 255), 0, 255);
  45747. outSplat[OFFSET.FDC1] = clamp(Math.floor(c.y * 255), 0, 255);
  45748. outSplat[OFFSET.FDC2] = clamp(Math.floor(c.z * 255), 0, 255);
  45749. outSplat[OFFSET.OPACITY] = clamp(Math.floor(c.w * 255), 0, 255);
  45750. return outSplat;
  45751. };
  45752. }());
  45753. class PlyParser {
  45754. static checkTextForEndHeader(endHeaderTestText) {
  45755. if (endHeaderTestText.includes(PlyParser.HeaderEndToken)) {
  45756. return true;
  45757. }
  45758. return false;
  45759. }
  45760. static checkBufferForEndHeader(buffer, searchOfset, chunkSize, decoder) {
  45761. var endHeaderTestChunk = new Uint8Array(buffer, Math.max(0, searchOfset - chunkSize), chunkSize);
  45762. var endHeaderTestText = decoder.decode(endHeaderTestChunk);
  45763. return PlyParser.checkTextForEndHeader(endHeaderTestText);
  45764. }
  45765. static decodeHeaderText(headerText) {
  45766. var headerLines = headerText.split('\n');
  45767. var prunedLines = [];
  45768. var splatCount = 0;
  45769. var propertyTypes = {};
  45770. var compressed = false;
  45771. for (var i = 0; i < headerLines.length; i++) {
  45772. var line = headerLines[i].trim();
  45773. prunedLines.push(line);
  45774. if (line.startsWith('element chunk') || line.match(/[A-Za-z]*packed_[A-Za-z]*/)) {
  45775. compressed = true;
  45776. } else if (line.startsWith('element vertex')) {
  45777. var splatCountMatch = line.match(/\d+/);
  45778. if (splatCountMatch) {
  45779. splatCount = parseInt(splatCountMatch[0]);
  45780. }
  45781. } else if (line.startsWith('property')) {
  45782. var propertyMatch = line.match(/(\w+)\s+(\w+)\s+(\w+)/);
  45783. if (propertyMatch) {
  45784. var propertyType = propertyMatch[2];
  45785. var propertyName = propertyMatch[3];
  45786. propertyTypes[propertyName] = propertyType;
  45787. }
  45788. } else if (line === PlyParser.HeaderEndToken) {
  45789. break;
  45790. }
  45791. }
  45792. var bytesPerSplat = 0;
  45793. var fieldOffsets = {};
  45794. var fieldSize = {
  45795. 'double': 8,
  45796. 'int': 4,
  45797. 'uint': 4,
  45798. 'float': 4,
  45799. 'short': 2,
  45800. 'ushort': 2,
  45801. 'uchar': 1
  45802. };
  45803. var fieldNames = [];
  45804. for (var fieldName in propertyTypes) {
  45805. if (propertyTypes.hasOwnProperty(fieldName)) {
  45806. fieldNames.push(fieldName);
  45807. var type = propertyTypes[fieldName];
  45808. fieldOffsets[fieldName] = bytesPerSplat;
  45809. bytesPerSplat += fieldSize[type];
  45810. }
  45811. }
  45812. var sphericalHarmonicsFieldCount = 0;
  45813. var sphericalHarmonicsCoefficientsPerChannel = 0;
  45814. for (var _fieldName of fieldNames) {
  45815. if (_fieldName.startsWith('f_rest')) sphericalHarmonicsFieldCount++;
  45816. }
  45817. sphericalHarmonicsCoefficientsPerChannel = sphericalHarmonicsFieldCount / 3;
  45818. var sphericalHarmonicsDegree = 0;
  45819. if (sphericalHarmonicsCoefficientsPerChannel >= 3) sphericalHarmonicsDegree = 1;
  45820. if (sphericalHarmonicsCoefficientsPerChannel >= 8) sphericalHarmonicsDegree = 2;
  45821. var sphericalHarmonicsDegree1Fields = [];
  45822. if (sphericalHarmonicsDegree >= 1) {
  45823. for (var rgb = 0; rgb < 3; rgb++) {
  45824. for (var _i4 = 0; _i4 < 3; _i4++) {
  45825. sphericalHarmonicsDegree1Fields.push('f_rest_' + (_i4 + sphericalHarmonicsCoefficientsPerChannel * rgb));
  45826. }
  45827. }
  45828. }
  45829. var sphericalHarmonicsDegree2Fields = [];
  45830. if (sphericalHarmonicsDegree >= 2) {
  45831. for (var _rgb = 0; _rgb < 3; _rgb++) {
  45832. for (var _i5 = 0; _i5 < 5; _i5++) {
  45833. sphericalHarmonicsDegree2Fields.push('f_rest_' + (_i5 + sphericalHarmonicsCoefficientsPerChannel * _rgb + 3));
  45834. }
  45835. }
  45836. }
  45837. return {
  45838. 'splatCount': splatCount,
  45839. 'propertyTypes': propertyTypes,
  45840. 'compressed': compressed,
  45841. 'headerText': headerText,
  45842. 'headerLines': prunedLines,
  45843. 'headerSizeBytes': headerText.indexOf(PlyParser.HeaderEndToken) + PlyParser.HeaderEndToken.length + 1,
  45844. 'bytesPerSplat': bytesPerSplat,
  45845. 'fieldOffsets': fieldOffsets,
  45846. 'sphericalHarmonicsDegree': sphericalHarmonicsDegree,
  45847. 'sphericalHarmonicsCoefficientsPerChannel': sphericalHarmonicsCoefficientsPerChannel,
  45848. 'sphericalHarmonicsDegree1Fields': sphericalHarmonicsDegree1Fields,
  45849. 'sphericalHarmonicsDegree2Fields': sphericalHarmonicsDegree2Fields
  45850. };
  45851. }
  45852. static decodeHeadeFromBuffer(plyBuffer) {
  45853. var decoder = new TextDecoder();
  45854. var headerOffset = 0;
  45855. var headerText = '';
  45856. var readChunkSize = 100;
  45857. while (true) {
  45858. if (headerOffset + readChunkSize >= plyBuffer.byteLength) {
  45859. throw new Error('End of file reached while searching for end of header');
  45860. }
  45861. var headerChunk = new Uint8Array(plyBuffer, headerOffset, readChunkSize);
  45862. headerText += decoder.decode(headerChunk);
  45863. headerOffset += readChunkSize;
  45864. if (PlyParser.checkBufferForEndHeader(plyBuffer, headerOffset, readChunkSize * 2, decoder)) {
  45865. break;
  45866. }
  45867. }
  45868. return PlyParser.decodeHeaderText(headerText);
  45869. }
  45870. static findVertexData(plyBuffer, header) {
  45871. return new DataView(plyBuffer, header.headerSizeBytes);
  45872. }
  45873. static readRawVertexFast(vertexData, offset, fieldOffsets, propertiesToRead, propertyTypes, outVertex) {
  45874. var rawVertex = outVertex || {};
  45875. for (var property of propertiesToRead) {
  45876. var propertyType = propertyTypes[property];
  45877. if (propertyType === 'float') {
  45878. rawVertex[property] = vertexData.getFloat32(offset + fieldOffsets[property], true);
  45879. } else if (propertyType === 'double') {
  45880. //xzw add! 因为我试过一个ply的坐标是double
  45881. rawVertex[property] = vertexData.getFloat64(offset + fieldOffsets[property], true);
  45882. } else if (propertyType === 'uchar') {
  45883. rawVertex[property] = vertexData.getUint8(offset + fieldOffsets[property]) / 255.0;
  45884. }
  45885. }
  45886. }
  45887. static parseToUncompressedSplatBufferSection(header, fromSplat, toSplat, vertexData, vertexDataOffset, toBuffer, toOffset) {
  45888. var outSphericalHarmonicsDegree = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : 0;
  45889. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  45890. var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter;
  45891. var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale;
  45892. var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation;
  45893. var outBytesPerColor = SplatBuffer.CompressionLevels[0].BytesPerColor;
  45894. var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree].BytesPerSplat;
  45895. for (var i = fromSplat; i <= toSplat; i++) {
  45896. var parsedSplat = PlyParser.parseToUncompressedSplat(vertexData, i, header, vertexDataOffset, outSphericalHarmonicsDegree);
  45897. var outBase = i * outBytesPerSplat + toOffset;
  45898. var outCenter = new Float32Array(toBuffer, outBase, 3);
  45899. var outScale = new Float32Array(toBuffer, outBase + outBytesPerCenter, 3);
  45900. var outRotation = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4);
  45901. var outColor = new Uint8Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4);
  45902. outCenter[0] = parsedSplat[UncompressedSplatArray.OFFSET.X];
  45903. outCenter[1] = parsedSplat[UncompressedSplatArray.OFFSET.Y];
  45904. outCenter[2] = parsedSplat[UncompressedSplatArray.OFFSET.Z];
  45905. outScale[0] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE0];
  45906. outScale[1] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE1];
  45907. outScale[2] = parsedSplat[UncompressedSplatArray.OFFSET.SCALE2];
  45908. outRotation[0] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION0];
  45909. outRotation[1] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION1];
  45910. outRotation[2] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION2];
  45911. outRotation[3] = parsedSplat[UncompressedSplatArray.OFFSET.ROTATION3];
  45912. outColor[0] = parsedSplat[UncompressedSplatArray.OFFSET.FDC0];
  45913. outColor[1] = parsedSplat[UncompressedSplatArray.OFFSET.FDC1];
  45914. outColor[2] = parsedSplat[UncompressedSplatArray.OFFSET.FDC2];
  45915. outColor[3] = parsedSplat[UncompressedSplatArray.OFFSET.OPACITY];
  45916. if (outSphericalHarmonicsDegree >= 1) {
  45917. var outSphericalHarmonics = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation + outBytesPerColor, parsedSplat.sphericalHarmonicsCount);
  45918. for (var _i6 = 0; _i6 <= 8; _i6++) {
  45919. outSphericalHarmonics[_i6] = parsedSplat[UncompressedSplatArray.OFFSET.FRC0 + _i6];
  45920. }
  45921. if (outSphericalHarmonicsDegree >= 2) {
  45922. for (var _i7 = 9; _i7 <= 23; _i7++) {
  45923. outSphericalHarmonics[_i7] = parsedSplat[UncompressedSplatArray.OFFSET.FRC0 + _i7];
  45924. }
  45925. }
  45926. }
  45927. }
  45928. }
  45929. static parseToUncompressedSplatArray(plyBuffer) {
  45930. var outSphericalHarmonicsDegree = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  45931. var header = PlyParser.decodeHeadeFromBuffer(plyBuffer);
  45932. if (header.compressed) {
  45933. return CompressedPlyParser.parseToUncompressedSplatArray(plyBuffer);
  45934. } else {
  45935. var splatCount = header.splatCount;
  45936. var vertexData = PlyParser.findVertexData(plyBuffer, header);
  45937. // TODO: Eventually properly support multiple degree spherical harmonics
  45938. // figure out the SH degree from the number of coefficients
  45939. /* let nRestCoeffs = 0;
  45940. for (const propertyName in header.propertyTypes) {
  45941. if (propertyName.startsWith('f_rest_')) {
  45942. nRestCoeffs += 1;
  45943. }
  45944. }
  45945. const nCoeffsPerColor = nRestCoeffs / 3;*/
  45946. // const sphericalHarmonicsDegree = Math.sqrt(nCoeffsPerColor + 1) - 1;
  45947. // const sphericalHarmonicsDegree = 0;
  45948. // console.log('Detected degree', sphericalHarmonicsDegree, 'with ', nCoeffsPerColor, 'coefficients per color');
  45949. // figure out the order in which spherical harmonics should be read
  45950. /* const shFeatureOrder = [];
  45951. for (let rgb = 0; rgb < 3; ++rgb) {
  45952. shFeatureOrder.push(`f_dc_${rgb}`);
  45953. }
  45954. for (let i = 0; i < nCoeffsPerColor; ++i) {
  45955. for (let rgb = 0; rgb < 3; ++rgb) {
  45956. shFeatureOrder.push(`f_rest_${rgb * nCoeffsPerColor + i}`);
  45957. }
  45958. }*/
  45959. var splatArray = new UncompressedSplatArray(outSphericalHarmonicsDegree);
  45960. for (var row = 0; row < splatCount; row++) {
  45961. var newSplat = PlyParser.parseToUncompressedSplat(vertexData, row, header, 0, outSphericalHarmonicsDegree);
  45962. splatArray.addSplat(newSplat);
  45963. }
  45964. return splatArray;
  45965. }
  45966. }
  45967. }
  45968. _PlyParser = PlyParser;
  45969. _defineProperty(PlyParser, "HeaderEndToken", 'end_header');
  45970. _defineProperty(PlyParser, "BaseFields", ['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', 'red', 'green', 'blue', 'opacity']);
  45971. _defineProperty(PlyParser, "SphericalHarmonicsFields", Array.from(Array(45)).map((e, i) => "f_rest_".concat(i)));
  45972. _defineProperty(PlyParser, "Fields", [[..._PlyParser.BaseFields], [..._PlyParser.BaseFields, ..._PlyParser.SphericalHarmonicsFields]]);
  45973. _defineProperty(PlyParser, "parseToUncompressedSplat", function () {
  45974. var rawVertex = {};
  45975. var tempRotation = new THREE$2.Quaternion();
  45976. return function (vertexData, row, header) {
  45977. var vertexDataOffset = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  45978. var outSphericalHarmonicsDegree = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0;
  45979. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  45980. _PlyParser.readRawVertexFast(vertexData, row * header.bytesPerSplat + vertexDataOffset, header.fieldOffsets, _PlyParser.Fields[outSphericalHarmonicsDegree > 0 ? 1 : 0], header.propertyTypes, rawVertex);
  45981. var newSplat = UncompressedSplatArray.createSplat(outSphericalHarmonicsDegree);
  45982. if (rawVertex['scale_0'] !== undefined) {
  45983. newSplat[UncompressedSplatArray.OFFSET.SCALE0] = Math.exp(rawVertex['scale_0']);
  45984. newSplat[UncompressedSplatArray.OFFSET.SCALE1] = Math.exp(rawVertex['scale_1']);
  45985. newSplat[UncompressedSplatArray.OFFSET.SCALE2] = Math.exp(rawVertex['scale_2']);
  45986. } else {
  45987. newSplat[UncompressedSplatArray.OFFSET.SCALE0] = 0.01;
  45988. newSplat[UncompressedSplatArray.OFFSET.SCALE1] = 0.01;
  45989. newSplat[UncompressedSplatArray.OFFSET.SCALE2] = 0.01;
  45990. }
  45991. if (rawVertex['f_dc_0'] !== undefined) {
  45992. var SH_C0 = 0.28209479177387814;
  45993. newSplat[UncompressedSplatArray.OFFSET.FDC0] = (0.5 + SH_C0 * rawVertex['f_dc_0']) * 255;
  45994. newSplat[UncompressedSplatArray.OFFSET.FDC1] = (0.5 + SH_C0 * rawVertex['f_dc_1']) * 255;
  45995. newSplat[UncompressedSplatArray.OFFSET.FDC2] = (0.5 + SH_C0 * rawVertex['f_dc_2']) * 255;
  45996. } else if (rawVertex['red'] !== undefined) {
  45997. newSplat[UncompressedSplatArray.OFFSET.FDC0] = rawVertex['red'] * 255;
  45998. newSplat[UncompressedSplatArray.OFFSET.FDC1] = rawVertex['green'] * 255;
  45999. newSplat[UncompressedSplatArray.OFFSET.FDC2] = rawVertex['blue'] * 255;
  46000. } else {
  46001. newSplat[UncompressedSplatArray.OFFSET.FDC0] = 0;
  46002. newSplat[UncompressedSplatArray.OFFSET.FDC1] = 0;
  46003. newSplat[UncompressedSplatArray.OFFSET.FDC2] = 0;
  46004. }
  46005. if (rawVertex['opacity'] !== undefined) {
  46006. newSplat[UncompressedSplatArray.OFFSET.OPACITY] = 1 / (1 + Math.exp(-rawVertex['opacity'])) * 255;
  46007. } else {
  46008. //xzw add
  46009. newSplat[UncompressedSplatArray.OFFSET.OPACITY] = 1;
  46010. }
  46011. newSplat[UncompressedSplatArray.OFFSET.FDC0] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC0]), 0, 255);
  46012. newSplat[UncompressedSplatArray.OFFSET.FDC1] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC1]), 0, 255);
  46013. newSplat[UncompressedSplatArray.OFFSET.FDC2] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.FDC2]), 0, 255);
  46014. newSplat[UncompressedSplatArray.OFFSET.OPACITY] = clamp(Math.floor(newSplat[UncompressedSplatArray.OFFSET.OPACITY]), 0, 255);
  46015. if (outSphericalHarmonicsDegree >= 1) {
  46016. if (rawVertex['f_rest_0'] !== undefined) {
  46017. for (var i = 0; i < 9; i++) {
  46018. newSplat[UncompressedSplatArray.OFFSET.FRC0 + i] = rawVertex[header.sphericalHarmonicsDegree1Fields[i]];
  46019. }
  46020. if (outSphericalHarmonicsDegree >= 2) {
  46021. for (var _i18 = 0; _i18 < 15; _i18++) {
  46022. newSplat[UncompressedSplatArray.OFFSET.FRC9 + _i18] = rawVertex[header.sphericalHarmonicsDegree2Fields[_i18]];
  46023. }
  46024. }
  46025. } else {
  46026. newSplat[UncompressedSplatArray.OFFSET.FRC0] = 0;
  46027. newSplat[UncompressedSplatArray.OFFSET.FRC1] = 0;
  46028. newSplat[UncompressedSplatArray.OFFSET.FRC2] = 0;
  46029. }
  46030. }
  46031. if (rawVertex['rot_0'] == void 0) {
  46032. //xzw add 表现为任何方向都是圆形 sprite
  46033. tempRotation.set(0, 0, 0, 1);
  46034. } else {
  46035. tempRotation.set(rawVertex['rot_0'], rawVertex['rot_1'], rawVertex['rot_2'], rawVertex['rot_3']);
  46036. tempRotation.normalize();
  46037. }
  46038. newSplat[UncompressedSplatArray.OFFSET.ROTATION0] = tempRotation.x;
  46039. newSplat[UncompressedSplatArray.OFFSET.ROTATION1] = tempRotation.y;
  46040. newSplat[UncompressedSplatArray.OFFSET.ROTATION2] = tempRotation.z;
  46041. newSplat[UncompressedSplatArray.OFFSET.ROTATION3] = tempRotation.w;
  46042. newSplat[UncompressedSplatArray.OFFSET.X] = rawVertex['x'];
  46043. newSplat[UncompressedSplatArray.OFFSET.Y] = rawVertex['y'];
  46044. newSplat[UncompressedSplatArray.OFFSET.Z] = rawVertex['z'];
  46045. return newSplat;
  46046. };
  46047. }());
  46048. class SplatPartitioner {
  46049. constructor(sectionCount, sectionFilters, groupingParameters, partitionGenerator) {
  46050. this.sectionCount = sectionCount;
  46051. this.sectionFilters = sectionFilters;
  46052. this.groupingParameters = groupingParameters;
  46053. this.partitionGenerator = partitionGenerator;
  46054. }
  46055. partitionUncompressedSplatArray(splatArray) {
  46056. var groupingParameters;
  46057. var sectionCount;
  46058. var sectionFilters;
  46059. if (this.partitionGenerator) {
  46060. var results = this.partitionGenerator(splatArray);
  46061. groupingParameters = results.groupingParameters;
  46062. sectionCount = results.sectionCount;
  46063. sectionFilters = results.sectionFilters;
  46064. } else {
  46065. groupingParameters = this.groupingParameters;
  46066. sectionCount = this.sectionCount;
  46067. sectionFilters = this.sectionFilters;
  46068. }
  46069. var newArrays = [];
  46070. for (var s = 0; s < sectionCount; s++) {
  46071. var sectionSplats = new UncompressedSplatArray(splatArray.sphericalHarmonicsDegree);
  46072. var sectionFilter = sectionFilters[s];
  46073. for (var i = 0; i < splatArray.splatCount; i++) {
  46074. if (sectionFilter(i)) {
  46075. sectionSplats.addSplatFromArray(splatArray, i);
  46076. }
  46077. }
  46078. newArrays.push(sectionSplats);
  46079. }
  46080. return {
  46081. splatArrays: newArrays,
  46082. parameters: groupingParameters
  46083. };
  46084. }
  46085. static getStandardPartitioner() {
  46086. var partitionSize = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  46087. var sceneCenter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE$2.Vector3();
  46088. var blockSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : SplatBuffer.BucketBlockSize;
  46089. var bucketSize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : SplatBuffer.BucketSize;
  46090. var partitionGenerator = splatArray => {
  46091. if (partitionSize <= 0) partitionSize = splatArray.splatCount;
  46092. var centerA = new THREE$2.Vector3();
  46093. var centerB = new THREE$2.Vector3();
  46094. var clampDistance = 0.5;
  46095. var clampPoint = point => {
  46096. point.x = Math.floor(point.x / clampDistance) * clampDistance;
  46097. point.y = Math.floor(point.y / clampDistance) * clampDistance;
  46098. point.z = Math.floor(point.z / clampDistance) * clampDistance;
  46099. };
  46100. splatArray.splats.sort((a, b) => {
  46101. centerA.set(a[UncompressedSplatArray.OFFSET.X], a[UncompressedSplatArray.OFFSET.Y], a[UncompressedSplatArray.OFFSET.Z]).sub(sceneCenter);
  46102. clampPoint(centerA);
  46103. var centerADist = centerA.lengthSq();
  46104. centerB.set(b[UncompressedSplatArray.OFFSET.X], b[UncompressedSplatArray.OFFSET.Y], b[UncompressedSplatArray.OFFSET.Z]).sub(sceneCenter);
  46105. clampPoint(centerB);
  46106. var centerBDist = centerB.lengthSq();
  46107. if (centerADist > centerBDist) return 1;else return -1;
  46108. });
  46109. var sectionFilters = [];
  46110. var groupingParameters = [];
  46111. partitionSize = Math.min(splatArray.splatCount, partitionSize);
  46112. var patitionCount = Math.ceil(splatArray.splatCount / partitionSize);
  46113. var currentStartSplat = 0;
  46114. var _loop = function _loop() {
  46115. var startSplat = currentStartSplat;
  46116. sectionFilters.push(splatIndex => {
  46117. return splatIndex >= startSplat && splatIndex < startSplat + partitionSize;
  46118. });
  46119. groupingParameters.push({
  46120. 'blocksSize': blockSize,
  46121. 'bucketSize': bucketSize
  46122. });
  46123. currentStartSplat += partitionSize;
  46124. };
  46125. for (var i = 0; i < patitionCount; i++) {
  46126. _loop();
  46127. }
  46128. return {
  46129. 'sectionCount': sectionFilters.length,
  46130. sectionFilters,
  46131. groupingParameters
  46132. };
  46133. };
  46134. return new SplatPartitioner(undefined, undefined, undefined, partitionGenerator);
  46135. }
  46136. }
  46137. class SplatBufferGenerator {
  46138. constructor(splatPartitioner, alphaRemovalThreshold, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize) {
  46139. this.splatPartitioner = splatPartitioner;
  46140. this.alphaRemovalThreshold = alphaRemovalThreshold;
  46141. this.compressionLevel = compressionLevel;
  46142. this.sectionSize = sectionSize;
  46143. this.sceneCenter = sceneCenter ? new THREE$2.Vector3().copy(sceneCenter) : undefined;
  46144. this.blockSize = blockSize;
  46145. this.bucketSize = bucketSize;
  46146. }
  46147. generateFromUncompressedSplatArray(splatArray) {
  46148. var partitionResults = this.splatPartitioner.partitionUncompressedSplatArray(splatArray);
  46149. return SplatBuffer.generateFromUncompressedSplatArrays(partitionResults.splatArrays, this.alphaRemovalThreshold, this.compressionLevel, this.sceneCenter, this.blockSize, this.bucketSize, partitionResults.parameters);
  46150. }
  46151. static getStandardGenerator() {
  46152. var alphaRemovalThreshold = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  46153. var compressionLevel = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  46154. var sectionSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  46155. var sceneCenter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new THREE$2.Vector3();
  46156. var blockSize = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : SplatBuffer.BucketBlockSize;
  46157. var bucketSize = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : SplatBuffer.BucketSize;
  46158. var splatPartitioner = SplatPartitioner.getStandardPartitioner(sectionSize, sceneCenter, blockSize, bucketSize);
  46159. return new SplatBufferGenerator(splatPartitioner, alphaRemovalThreshold, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize);
  46160. }
  46161. }
  46162. var LoaderStatus = {
  46163. 'Downloading': 0,
  46164. 'Processing': 1,
  46165. 'Done': 2
  46166. };
  46167. class Constants {}
  46168. _defineProperty(Constants, "DepthMapRange", 1 << 16);
  46169. _defineProperty(Constants, "MemoryPageSize", 65536);
  46170. _defineProperty(Constants, "BytesPerFloat", 4);
  46171. _defineProperty(Constants, "BytesPerInt", 4);
  46172. _defineProperty(Constants, "MaxScenes", 32);
  46173. _defineProperty(Constants, "StreamingSectionSize", 524288);
  46174. function storeChunksInBuffer(chunks, buffer) {
  46175. var inBytes = 0;
  46176. for (var chunk of chunks) inBytes += chunk.sizeBytes;
  46177. if (!buffer || buffer.byteLength < inBytes) {
  46178. buffer = new ArrayBuffer(inBytes);
  46179. }
  46180. var offset = 0;
  46181. for (var _chunk of chunks) {
  46182. new Uint8Array(buffer, offset, _chunk.sizeBytes).set(_chunk.data);
  46183. offset += _chunk.sizeBytes;
  46184. }
  46185. return buffer;
  46186. }
  46187. class PlyLoader {
  46188. static loadFromURL(fileName, onProgress, streamLoadData, onStreamedSectionProgress, minimumAlpha, compressionLevel) {
  46189. var outSphericalHarmonicsDegree = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0;
  46190. var sectionSize = arguments.length > 7 ? arguments[7] : undefined;
  46191. var sceneCenter = arguments.length > 8 ? arguments[8] : undefined;
  46192. var blockSize = arguments.length > 9 ? arguments[9] : undefined;
  46193. var bucketSize = arguments.length > 10 ? arguments[10] : undefined;
  46194. var streamedSectionSizeBytes = Constants.StreamingSectionSize;
  46195. var splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes;
  46196. var sectionCount = 1;
  46197. var streamBufferIn;
  46198. var streamBufferOut;
  46199. var streamedSplatBuffer;
  46200. var compressedPlyHeaderChunksBuffer;
  46201. var maxSplatCount = 0;
  46202. var splatCount = 0;
  46203. var headerLoaded = false;
  46204. var readyToLoadSplatData = false;
  46205. var compressed = false;
  46206. var streamLoadCompleteResolver;
  46207. var streamLoadPromise = new Promise(resolve => {
  46208. streamLoadCompleteResolver = resolve;
  46209. });
  46210. var numBytesStreamed = 0;
  46211. var numBytesParsed = 0;
  46212. var numBytesDownloaded = 0;
  46213. var headerText = '';
  46214. var header = null;
  46215. var chunks = [];
  46216. var textDecoder = new TextDecoder();
  46217. var localOnProgress = (percent, percentLabel, chunkData) => {
  46218. var loadComplete = percent >= 100;
  46219. if (streamLoadData) {
  46220. if (chunkData) {
  46221. chunks.push({
  46222. 'data': chunkData,
  46223. 'sizeBytes': chunkData.byteLength,
  46224. 'startBytes': numBytesDownloaded,
  46225. 'endBytes': numBytesDownloaded + chunkData.byteLength
  46226. });
  46227. numBytesDownloaded += chunkData.byteLength;
  46228. }
  46229. if (!headerLoaded) {
  46230. headerText += textDecoder.decode(chunkData);
  46231. if (PlyParser.checkTextForEndHeader(headerText)) {
  46232. header = PlyParser.decodeHeaderText(headerText);
  46233. outSphericalHarmonicsDegree = Math.min(outSphericalHarmonicsDegree, header.sphericalHarmonicsDegree);
  46234. compressed = header.compressed;
  46235. if (compressed) {
  46236. header = CompressedPlyParser.decodeHeaderText(headerText);
  46237. maxSplatCount = header.vertexElement.count;
  46238. } else {
  46239. maxSplatCount = header.splatCount;
  46240. readyToLoadSplatData = true;
  46241. }
  46242. var shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree];
  46243. var splatBufferSizeBytes = splatDataOffsetBytes + shDescriptor.BytesPerSplat * maxSplatCount;
  46244. streamBufferOut = new ArrayBuffer(splatBufferSizeBytes);
  46245. SplatBuffer.writeHeaderToBuffer({
  46246. versionMajor: SplatBuffer.CurrentMajorVersion,
  46247. versionMinor: SplatBuffer.CurrentMinorVersion,
  46248. maxSectionCount: sectionCount,
  46249. sectionCount: sectionCount,
  46250. maxSplatCount: maxSplatCount,
  46251. splatCount: splatCount,
  46252. compressionLevel: 0,
  46253. sceneCenter: new THREE$2.Vector3()
  46254. }, streamBufferOut);
  46255. numBytesStreamed = header.headerSizeBytes;
  46256. numBytesParsed = header.headerSizeBytes;
  46257. headerLoaded = true;
  46258. }
  46259. } else if (compressed && !readyToLoadSplatData) {
  46260. var sizeRequiredForHeaderAndChunks = header.headerSizeBytes + header.chunkElement.storageSizeBytes;
  46261. compressedPlyHeaderChunksBuffer = storeChunksInBuffer(chunks, compressedPlyHeaderChunksBuffer);
  46262. if (compressedPlyHeaderChunksBuffer.byteLength >= sizeRequiredForHeaderAndChunks) {
  46263. CompressedPlyParser.readElementData(header.chunkElement, compressedPlyHeaderChunksBuffer, header.headerSizeBytes);
  46264. numBytesStreamed = sizeRequiredForHeaderAndChunks;
  46265. numBytesParsed = sizeRequiredForHeaderAndChunks;
  46266. readyToLoadSplatData = true;
  46267. }
  46268. }
  46269. if (headerLoaded && readyToLoadSplatData) {
  46270. if (chunks.length > 0) {
  46271. streamBufferIn = storeChunksInBuffer(chunks, streamBufferIn);
  46272. var bytesLoadedSinceLastStreamedSection = numBytesDownloaded - numBytesStreamed;
  46273. if (bytesLoadedSinceLastStreamedSection > streamedSectionSizeBytes || loadComplete) {
  46274. var numBytesToProcess = numBytesDownloaded - numBytesParsed;
  46275. var addedSplatCount = Math.floor(numBytesToProcess / header.bytesPerSplat);
  46276. var numBytesToParse = addedSplatCount * header.bytesPerSplat;
  46277. var numBytesLeftOver = numBytesToProcess - numBytesToParse;
  46278. var newSplatCount = splatCount + addedSplatCount;
  46279. var parsedDataViewOffset = numBytesParsed - chunks[0].startBytes;
  46280. var dataToParse = new DataView(streamBufferIn, parsedDataViewOffset, numBytesToParse);
  46281. var _shDescriptor = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[outSphericalHarmonicsDegree];
  46282. var outOffset = splatCount * _shDescriptor.BytesPerSplat + splatDataOffsetBytes;
  46283. if (compressed) {
  46284. CompressedPlyParser.parseToUncompressedSplatBufferSection(header.chunkElement, header.vertexElement, 0, addedSplatCount - 1, splatCount, dataToParse, 0, streamBufferOut, outOffset);
  46285. } else {
  46286. PlyParser.parseToUncompressedSplatBufferSection(header, 0, addedSplatCount - 1, dataToParse, 0, streamBufferOut, outOffset, outSphericalHarmonicsDegree);
  46287. }
  46288. splatCount = newSplatCount;
  46289. if (!streamedSplatBuffer) {
  46290. SplatBuffer.writeSectionHeaderToBuffer({
  46291. maxSplatCount: maxSplatCount,
  46292. splatCount: splatCount,
  46293. bucketSize: 0,
  46294. bucketCount: 0,
  46295. bucketBlockSize: 0,
  46296. compressionScaleRange: 0,
  46297. storageSizeBytes: 0,
  46298. fullBucketCount: 0,
  46299. partiallyFilledBucketCount: 0,
  46300. sphericalHarmonicsDegree: outSphericalHarmonicsDegree
  46301. }, 0, streamBufferOut, SplatBuffer.HeaderSizeBytes);
  46302. streamedSplatBuffer = new SplatBuffer(streamBufferOut, false);
  46303. }
  46304. streamedSplatBuffer.updateLoadedCounts(1, splatCount);
  46305. onStreamedSectionProgress(streamedSplatBuffer, loadComplete);
  46306. numBytesStreamed += streamedSectionSizeBytes;
  46307. numBytesParsed += numBytesToParse;
  46308. if (numBytesLeftOver === 0) {
  46309. chunks = [];
  46310. } else {
  46311. var keepChunks = [];
  46312. var keepSize = 0;
  46313. for (var i = chunks.length - 1; i >= 0; i--) {
  46314. var chunk = chunks[i];
  46315. keepSize += chunk.sizeBytes;
  46316. keepChunks.unshift(chunk);
  46317. if (keepSize >= numBytesLeftOver) break;
  46318. }
  46319. chunks = keepChunks;
  46320. }
  46321. }
  46322. }
  46323. if (loadComplete) {
  46324. streamLoadCompleteResolver(streamedSplatBuffer);
  46325. }
  46326. }
  46327. }
  46328. if (onProgress) onProgress(percent, percentLabel, LoaderStatus.Downloading);
  46329. };
  46330. return fetchWithProgress(fileName, localOnProgress, !streamLoadData).then(plyFileData => {
  46331. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  46332. var loadPromise = streamLoadData ? streamLoadPromise : PlyLoader.loadFromFileData(plyFileData, minimumAlpha, compressionLevel, outSphericalHarmonicsDegree, sectionSize, sceneCenter, blockSize, bucketSize);
  46333. return loadPromise.then(splatBuffer => {
  46334. if (onProgress) onProgress(100, '100%', LoaderStatus.Done);
  46335. return splatBuffer;
  46336. });
  46337. });
  46338. }
  46339. static loadFromFileData(plyFileData, minimumAlpha, compressionLevel) {
  46340. var outSphericalHarmonicsDegree = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  46341. var sectionSize = arguments.length > 4 ? arguments[4] : undefined;
  46342. var sceneCenter = arguments.length > 5 ? arguments[5] : undefined;
  46343. var blockSize = arguments.length > 6 ? arguments[6] : undefined;
  46344. var bucketSize = arguments.length > 7 ? arguments[7] : undefined;
  46345. return delayedExecute(() => {
  46346. return PlyParser.parseToUncompressedSplatArray(plyFileData, outSphericalHarmonicsDegree);
  46347. }).then(splatArray => {
  46348. var splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize);
  46349. return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray);
  46350. });
  46351. }
  46352. }
  46353. class SplatParser {
  46354. static parseToUncompressedSplatBufferSection(fromSplat, toSplat, fromBuffer, fromOffset, toBuffer, toOffset) {
  46355. var outBytesPerCenter = SplatBuffer.CompressionLevels[0].BytesPerCenter;
  46356. var outBytesPerScale = SplatBuffer.CompressionLevels[0].BytesPerScale;
  46357. var outBytesPerRotation = SplatBuffer.CompressionLevels[0].BytesPerRotation;
  46358. var outBytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  46359. for (var i = fromSplat; i <= toSplat; i++) {
  46360. var inBase = i * SplatParser.RowSizeBytes + fromOffset;
  46361. var inCenter = new Float32Array(fromBuffer, inBase, 3);
  46362. var inScale = new Float32Array(fromBuffer, inBase + SplatParser.CenterSizeBytes, 3);
  46363. var inColor = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4);
  46364. var inRotation = new Uint8Array(fromBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes + SplatParser.RotationSizeBytes, 4);
  46365. var quat = new THREE$2.Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128);
  46366. quat.normalize();
  46367. var outBase = i * outBytesPerSplat + toOffset;
  46368. var outCenter = new Float32Array(toBuffer, outBase, 3);
  46369. var outScale = new Float32Array(toBuffer, outBase + outBytesPerCenter, 3);
  46370. var outRotation = new Float32Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale, 4);
  46371. var outColor = new Uint8Array(toBuffer, outBase + outBytesPerCenter + outBytesPerScale + outBytesPerRotation, 4);
  46372. outCenter[0] = inCenter[0];
  46373. outCenter[1] = inCenter[1];
  46374. outCenter[2] = inCenter[2];
  46375. outScale[0] = inScale[0];
  46376. outScale[1] = inScale[1];
  46377. outScale[2] = inScale[2];
  46378. outRotation[0] = quat.w;
  46379. outRotation[1] = quat.x;
  46380. outRotation[2] = quat.y;
  46381. outRotation[3] = quat.z;
  46382. outColor[0] = inColor[0];
  46383. outColor[1] = inColor[1];
  46384. outColor[2] = inColor[2];
  46385. outColor[3] = inColor[3];
  46386. }
  46387. }
  46388. static parseStandardSplatToUncompressedSplatArray(inBuffer) {
  46389. // Standard .splat row layout:
  46390. // XYZ - Position (Float32)
  46391. // XYZ - Scale (Float32)
  46392. // RGBA - colors (uint8)
  46393. // IJKL - quaternion/rot (uint8)
  46394. var splatCount = inBuffer.byteLength / SplatParser.RowSizeBytes;
  46395. var splatArray = new UncompressedSplatArray();
  46396. for (var i = 0; i < splatCount; i++) {
  46397. var inBase = i * SplatParser.RowSizeBytes;
  46398. var inCenter = new Float32Array(inBuffer, inBase, 3);
  46399. var inScale = new Float32Array(inBuffer, inBase + SplatParser.CenterSizeBytes, 3);
  46400. var inColor = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes, 4);
  46401. var inRotation = new Uint8Array(inBuffer, inBase + SplatParser.CenterSizeBytes + SplatParser.ScaleSizeBytes + SplatParser.ColorSizeBytes, 4);
  46402. var quat = new THREE$2.Quaternion((inRotation[1] - 128) / 128, (inRotation[2] - 128) / 128, (inRotation[3] - 128) / 128, (inRotation[0] - 128) / 128);
  46403. quat.normalize();
  46404. splatArray.addSplatFromComonents(inCenter[0], inCenter[1], inCenter[2], inScale[0], inScale[1], inScale[2], quat.w, quat.x, quat.y, quat.z, inColor[0], inColor[1], inColor[2], inColor[3]);
  46405. }
  46406. return splatArray;
  46407. }
  46408. }
  46409. _defineProperty(SplatParser, "RowSizeBytes", 32);
  46410. _defineProperty(SplatParser, "CenterSizeBytes", 12);
  46411. _defineProperty(SplatParser, "ScaleSizeBytes", 12);
  46412. _defineProperty(SplatParser, "RotationSizeBytes", 4);
  46413. _defineProperty(SplatParser, "ColorSizeBytes", 4);
  46414. class SplatLoader {
  46415. static loadFromURL(fileName, onProgress, streamLoadData, onStreamedSectionProgress, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize) {
  46416. var splatDataOffsetBytes = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes;
  46417. var streamSectionSizeBytes = Constants.StreamingSectionSize;
  46418. var sectionCount = 1;
  46419. var streamBufferIn;
  46420. var streamBufferOut;
  46421. var streamSplatBuffer;
  46422. var maxSplatCount = 0;
  46423. var splatCount = 0;
  46424. var streamLoadCompleteResolver;
  46425. var streamLoadPromise = new Promise(resolve => {
  46426. streamLoadCompleteResolver = resolve;
  46427. });
  46428. var numBytesStreamed = 0;
  46429. var numBytesLoaded = 0;
  46430. var chunks = [];
  46431. var localOnProgress = (percent, percentStr, chunk, fileSize) => {
  46432. var loadComplete = percent >= 100;
  46433. if (!fileSize) streamLoadData = false;
  46434. if (streamLoadData) {
  46435. if (!streamBufferIn) {
  46436. maxSplatCount = fileSize / SplatParser.RowSizeBytes;
  46437. streamBufferIn = new ArrayBuffer(fileSize);
  46438. var bytesPerSplat = SplatBuffer.CompressionLevels[0].SphericalHarmonicsDegrees[0].BytesPerSplat;
  46439. var splatBufferSizeBytes = splatDataOffsetBytes + bytesPerSplat * maxSplatCount;
  46440. streamBufferOut = new ArrayBuffer(splatBufferSizeBytes);
  46441. SplatBuffer.writeHeaderToBuffer({
  46442. versionMajor: SplatBuffer.CurrentMajorVersion,
  46443. versionMinor: SplatBuffer.CurrentMinorVersion,
  46444. maxSectionCount: sectionCount,
  46445. sectionCount: sectionCount,
  46446. maxSplatCount: maxSplatCount,
  46447. splatCount: splatCount,
  46448. compressionLevel: 0,
  46449. sceneCenter: new THREE$2.Vector3()
  46450. }, streamBufferOut);
  46451. }
  46452. if (chunk) {
  46453. chunks.push(chunk);
  46454. new Uint8Array(streamBufferIn, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk));
  46455. numBytesLoaded += chunk.byteLength;
  46456. var bytesLoadedSinceLastSection = numBytesLoaded - numBytesStreamed;
  46457. if (bytesLoadedSinceLastSection > streamSectionSizeBytes || loadComplete) {
  46458. var bytesToUpdate = loadComplete ? bytesLoadedSinceLastSection : streamSectionSizeBytes;
  46459. var addedSplatCount = bytesToUpdate / SplatParser.RowSizeBytes;
  46460. var newSplatCount = splatCount + addedSplatCount;
  46461. SplatParser.parseToUncompressedSplatBufferSection(splatCount, newSplatCount - 1, streamBufferIn, 0, streamBufferOut, splatDataOffsetBytes);
  46462. splatCount = newSplatCount;
  46463. if (!streamSplatBuffer) {
  46464. SplatBuffer.writeSectionHeaderToBuffer({
  46465. maxSplatCount: maxSplatCount,
  46466. splatCount: splatCount,
  46467. bucketSize: 0,
  46468. bucketCount: 0,
  46469. bucketBlockSize: 0,
  46470. compressionScaleRange: 0,
  46471. storageSizeBytes: 0,
  46472. fullBucketCount: 0,
  46473. partiallyFilledBucketCount: 0
  46474. }, 0, streamBufferOut, SplatBuffer.HeaderSizeBytes);
  46475. streamSplatBuffer = new SplatBuffer(streamBufferOut, false);
  46476. }
  46477. streamSplatBuffer.updateLoadedCounts(1, splatCount);
  46478. onStreamedSectionProgress(streamSplatBuffer, loadComplete);
  46479. numBytesStreamed += streamSectionSizeBytes;
  46480. }
  46481. }
  46482. if (loadComplete) {
  46483. streamLoadCompleteResolver(streamSplatBuffer);
  46484. }
  46485. }
  46486. if (onProgress) onProgress(percent, percentStr, LoaderStatus.Downloading);
  46487. return streamLoadData;
  46488. };
  46489. return fetchWithProgress(fileName, localOnProgress, true).then(fullBuffer => {
  46490. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  46491. var loadPromise = streamLoadData ? streamLoadPromise : SplatLoader.loadFromFileData(fullBuffer, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize);
  46492. return loadPromise.then(splatBuffer => {
  46493. if (onProgress) onProgress(100, '100%', LoaderStatus.Done);
  46494. return splatBuffer;
  46495. });
  46496. });
  46497. }
  46498. static loadFromFileData(splatFileData, minimumAlpha, compressionLevel, optimizeSplatData, sectionSize, sceneCenter, blockSize, bucketSize) {
  46499. return delayedExecute(() => {
  46500. var splatArray = SplatParser.parseStandardSplatToUncompressedSplatArray(splatFileData);
  46501. if (optimizeSplatData) {
  46502. var splatBufferGenerator = SplatBufferGenerator.getStandardGenerator(minimumAlpha, compressionLevel, sectionSize, sceneCenter, blockSize, bucketSize);
  46503. return splatBufferGenerator.generateFromUncompressedSplatArray(splatArray);
  46504. } else {
  46505. return SplatBuffer.generateFromUncompressedSplatArrays([splatArray], minimumAlpha, 0, new THREE$2.Vector3());
  46506. }
  46507. });
  46508. }
  46509. }
  46510. class KSplatLoader {
  46511. static checkVersion(buffer) {
  46512. var minVersionMajor = SplatBuffer.CurrentMajorVersion;
  46513. var minVersionMinor = SplatBuffer.CurrentMinorVersion;
  46514. var header = SplatBuffer.parseHeader(buffer);
  46515. if (header.versionMajor === minVersionMajor && header.versionMinor >= minVersionMinor || header.versionMajor > minVersionMajor) {
  46516. return true;
  46517. } else {
  46518. throw new Error("KSplat version not supported: v".concat(header.versionMajor, ".").concat(header.versionMinor, ". ") + "Minimum required: v".concat(minVersionMajor, ".").concat(minVersionMinor));
  46519. }
  46520. }
  46521. static loadFromURL(fileName, onProgress, streamLoadData, onSectionBuilt) {
  46522. var streamBuffer;
  46523. var streamSplatBuffer;
  46524. var headerBuffer;
  46525. var header;
  46526. var headerLoaded = false;
  46527. var headerLoading = false;
  46528. var sectionHeadersBuffer;
  46529. var sectionHeaders = [];
  46530. var sectionHeadersLoaded = false;
  46531. var sectionHeadersLoading = false;
  46532. var numBytesLoaded = 0;
  46533. var numBytesStreamed = 0;
  46534. var streamSectionSizeBytes = Constants.StreamingSectionSize;
  46535. var totalBytesToDownload = 0;
  46536. var loadComplete = false;
  46537. var chunks = [];
  46538. var streamLoadCompleteResolver;
  46539. var streamLoadPromise = new Promise(resolve => {
  46540. streamLoadCompleteResolver = resolve;
  46541. });
  46542. var checkAndLoadHeader = () => {
  46543. if (!headerLoaded && !headerLoading && numBytesLoaded >= SplatBuffer.HeaderSizeBytes) {
  46544. headerLoading = true;
  46545. var headerAssemblyPromise = new Blob(chunks).arrayBuffer();
  46546. headerAssemblyPromise.then(bufferData => {
  46547. headerBuffer = new ArrayBuffer(SplatBuffer.HeaderSizeBytes);
  46548. new Uint8Array(headerBuffer).set(new Uint8Array(bufferData, 0, SplatBuffer.HeaderSizeBytes));
  46549. KSplatLoader.checkVersion(headerBuffer);
  46550. headerLoading = false;
  46551. headerLoaded = true;
  46552. header = SplatBuffer.parseHeader(headerBuffer);
  46553. window.setTimeout(() => {
  46554. checkAndLoadSectionHeaders();
  46555. }, 1);
  46556. });
  46557. }
  46558. };
  46559. var queuedCheckAndLoadSectionsCount = 0;
  46560. var queueCheckAndLoadSections = () => {
  46561. if (queuedCheckAndLoadSectionsCount === 0) {
  46562. queuedCheckAndLoadSectionsCount++;
  46563. window.setTimeout(() => {
  46564. queuedCheckAndLoadSectionsCount--;
  46565. checkAndLoadSections(true);
  46566. }, 1);
  46567. }
  46568. };
  46569. var checkAndLoadSectionHeaders = () => {
  46570. var performLoad = () => {
  46571. sectionHeadersLoading = true;
  46572. var sectionHeadersAssemblyPromise = new Blob(chunks).arrayBuffer();
  46573. sectionHeadersAssemblyPromise.then(bufferData => {
  46574. sectionHeadersLoading = false;
  46575. sectionHeadersLoaded = true;
  46576. sectionHeadersBuffer = new ArrayBuffer(header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes);
  46577. new Uint8Array(sectionHeadersBuffer).set(new Uint8Array(bufferData, SplatBuffer.HeaderSizeBytes, header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes));
  46578. sectionHeaders = SplatBuffer.parseSectionHeaders(header, sectionHeadersBuffer, 0, false);
  46579. var totalSectionStorageStorageByes = 0;
  46580. for (var i = 0; i < header.maxSectionCount; i++) {
  46581. totalSectionStorageStorageByes += sectionHeaders[i].storageSizeBytes;
  46582. }
  46583. var totalStorageSizeBytes = SplatBuffer.HeaderSizeBytes + header.maxSectionCount * SplatBuffer.SectionHeaderSizeBytes + totalSectionStorageStorageByes;
  46584. if (!streamBuffer) {
  46585. streamBuffer = new ArrayBuffer(totalStorageSizeBytes);
  46586. var offset = 0;
  46587. for (var _i8 = 0; _i8 < chunks.length; _i8++) {
  46588. var chunk = chunks[_i8];
  46589. new Uint8Array(streamBuffer, offset, chunk.byteLength).set(new Uint8Array(chunk));
  46590. offset += chunk.byteLength;
  46591. }
  46592. }
  46593. totalBytesToDownload = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount;
  46594. for (var _i9 = 0; _i9 <= sectionHeaders.length && _i9 < header.maxSectionCount; _i9++) {
  46595. totalBytesToDownload += sectionHeaders[_i9].storageSizeBytes;
  46596. }
  46597. queueCheckAndLoadSections();
  46598. });
  46599. };
  46600. if (!sectionHeadersLoading && !sectionHeadersLoaded && headerLoaded && numBytesLoaded >= SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount) {
  46601. performLoad();
  46602. }
  46603. };
  46604. var checkAndLoadSections = () => {
  46605. if (sectionHeadersLoaded) {
  46606. if (loadComplete) return;
  46607. loadComplete = numBytesLoaded >= totalBytesToDownload;
  46608. var bytesLoadedSinceLastSection = numBytesLoaded - numBytesStreamed;
  46609. if (bytesLoadedSinceLastSection > streamSectionSizeBytes || loadComplete) {
  46610. numBytesStreamed = numBytesLoaded;
  46611. if (!streamSplatBuffer) streamSplatBuffer = new SplatBuffer(streamBuffer, false);
  46612. var baseDataOffset = SplatBuffer.HeaderSizeBytes + SplatBuffer.SectionHeaderSizeBytes * header.maxSectionCount;
  46613. var sectionBase = 0;
  46614. var reachedSections = 0;
  46615. var loadedSplatCount = 0;
  46616. for (var i = 0; i < header.maxSectionCount; i++) {
  46617. var sectionHeader = sectionHeaders[i];
  46618. var bucketsDataOffset = sectionBase + sectionHeader.partiallyFilledBucketCount * 4 + sectionHeader.bucketStorageSizeBytes * sectionHeader.bucketCount;
  46619. var bytesRequiredToReachSectionSplatData = baseDataOffset + bucketsDataOffset;
  46620. if (numBytesLoaded >= bytesRequiredToReachSectionSplatData) {
  46621. reachedSections++;
  46622. var bytesPastSSectionSplatDataStart = numBytesLoaded - bytesRequiredToReachSectionSplatData;
  46623. var baseDescriptor = SplatBuffer.CompressionLevels[header.compressionLevel];
  46624. var shDesc = baseDescriptor.SphericalHarmonicsDegrees[sectionHeader.sphericalHarmonicsDegree];
  46625. var bytesPerSplat = shDesc.BytesPerSplat;
  46626. var loadedSplatsForSection = Math.floor(bytesPastSSectionSplatDataStart / bytesPerSplat);
  46627. loadedSplatsForSection = Math.min(loadedSplatsForSection, sectionHeader.maxSplatCount);
  46628. loadedSplatCount += loadedSplatsForSection;
  46629. streamSplatBuffer.updateLoadedCounts(reachedSections, loadedSplatCount);
  46630. streamSplatBuffer.updateSectionLoadedCounts(i, loadedSplatsForSection);
  46631. } else {
  46632. break;
  46633. }
  46634. sectionBase += sectionHeader.storageSizeBytes;
  46635. }
  46636. onSectionBuilt(streamSplatBuffer, loadComplete);
  46637. if (loadComplete) {
  46638. streamLoadCompleteResolver(streamSplatBuffer);
  46639. }
  46640. }
  46641. }
  46642. };
  46643. var localOnProgress = (percent, percentStr, chunk) => {
  46644. if (chunk) {
  46645. chunks.push(chunk);
  46646. if (streamBuffer) {
  46647. new Uint8Array(streamBuffer, numBytesLoaded, chunk.byteLength).set(new Uint8Array(chunk));
  46648. }
  46649. numBytesLoaded += chunk.byteLength;
  46650. }
  46651. if (streamLoadData) {
  46652. checkAndLoadHeader();
  46653. checkAndLoadSectionHeaders();
  46654. checkAndLoadSections();
  46655. }
  46656. if (onProgress) onProgress(percent, percentStr, LoaderStatus.Downloading);
  46657. };
  46658. return fetchWithProgress(fileName, localOnProgress, !streamLoadData).then(fullBuffer => {
  46659. if (onProgress) onProgress(0, '0%', LoaderStatus.Processing);
  46660. var loadPromise = streamLoadData ? streamLoadPromise : KSplatLoader.loadFromFileData(fullBuffer);
  46661. return loadPromise.then(splatBuffer => {
  46662. if (onProgress) onProgress(100, '100%', LoaderStatus.Done);
  46663. return splatBuffer;
  46664. });
  46665. });
  46666. }
  46667. static loadFromFileData(fileData) {
  46668. return delayedExecute(() => {
  46669. KSplatLoader.checkVersion(fileData);
  46670. return new SplatBuffer(fileData);
  46671. });
  46672. }
  46673. }
  46674. _defineProperty(KSplatLoader, "downloadFile", function () {
  46675. var downLoadLink;
  46676. return function (splatBuffer, fileName) {
  46677. var blob = new Blob([splatBuffer.bufferData], {
  46678. type: 'application/octet-stream'
  46679. });
  46680. if (!downLoadLink) {
  46681. downLoadLink = document.createElement('a');
  46682. document.body.appendChild(downLoadLink);
  46683. }
  46684. downLoadLink.download = fileName;
  46685. downLoadLink.href = URL.createObjectURL(blob);
  46686. downLoadLink.click();
  46687. };
  46688. }());
  46689. var SceneFormat = {
  46690. 'Splat': 0,
  46691. 'KSplat': 1,
  46692. 'Ply': 2
  46693. };
  46694. var sceneFormatFromPath = path => {
  46695. if (path.endsWith('.ply')) return SceneFormat.Ply;else if (path.endsWith('.splat')) return SceneFormat.Splat;else if (path.endsWith('.ksplat')) return SceneFormat.KSplat;
  46696. return null;
  46697. };
  46698. var Utils$1 = /*#__PURE__*/Object.freeze({
  46699. __proto__: null,
  46700. sceneFormatFromPath: sceneFormatFromPath
  46701. });
  46702. /*
  46703. Copyright © 2010-2024 three.js authors & Mark Kellogg
  46704. Permission is hereby granted, free of charge, to any person obtaining a copy
  46705. of this software and associated documentation files (the "Software"), to deal
  46706. in the Software without restriction, including without limitation the rights
  46707. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  46708. copies of the Software, and to permit persons to whom the Software is
  46709. furnished to do so, subject to the following conditions:
  46710. The above copyright notice and this permission notice shall be included in
  46711. all copies or substantial portions of the Software.
  46712. */
  46713. // OrbitControls performs orbiting, dollying (zooming), and panning.
  46714. // Unlike TrackballControls, it maintains the "up" direction object.up (+Y by default).
  46715. //
  46716. // Orbit - left mouse / touch: one-finger move
  46717. // Zoom - middle mouse, or mousewheel / touch: two-finger spread or squish
  46718. // Pan - right mouse, or left mouse + ctrl/meta/shiftKey, or arrow keys / touch: two-finger move
  46719. var _changeEvent = {
  46720. type: 'change'
  46721. };
  46722. var _startEvent = {
  46723. type: 'start'
  46724. };
  46725. var _endEvent = {
  46726. type: 'end'
  46727. };
  46728. var _ray$4 = new THREE$2.Ray();
  46729. var _plane = new THREE$2.Plane();
  46730. var TILT_LIMIT = Math.cos(70 * THREE$2.MathUtils.DEG2RAD);
  46731. class OrbitControls extends THREE$2.EventDispatcher {
  46732. constructor(object, domElement) {
  46733. super();
  46734. this.object = object;
  46735. this.domElement = domElement;
  46736. this.domElement.style.touchAction = 'none'; // disable touch scroll
  46737. // Set to false to disable this control
  46738. this.enabled = true;
  46739. // "target" sets the location of focus, where the object orbits around
  46740. this.target = new THREE$2.Vector3();
  46741. // How far you can dolly in and out ( PerspectiveCamera only )
  46742. this.minDistance = 0;
  46743. this.maxDistance = Infinity;
  46744. // How far you can zoom in and out ( OrthographicCamera only )
  46745. this.minZoom = 0;
  46746. this.maxZoom = Infinity;
  46747. // How far you can orbit vertically, upper and lower limits.
  46748. // Range is 0 to Math.PI radians.
  46749. this.minPolarAngle = 0; // radians
  46750. this.maxPolarAngle = Math.PI; // radians
  46751. // How far you can orbit horizontally, upper and lower limits.
  46752. // If set, the interval [min, max] must be a sub-interval of [- 2 PI, 2 PI], with ( max - min < 2 PI )
  46753. this.minAzimuthAngle = -Infinity; // radians
  46754. this.maxAzimuthAngle = Infinity; // radians
  46755. // Set to true to enable damping (inertia)
  46756. // If damping is enabled, you must call controls.update() in your animation loop
  46757. this.enableDamping = false;
  46758. this.dampingFactor = 0.05;
  46759. // This option actually enables dollying in and out; left as "zoom" for backwards compatibility.
  46760. // Set to false to disable zooming
  46761. this.enableZoom = true;
  46762. this.zoomSpeed = 1.0;
  46763. // Set to false to disable rotating
  46764. this.enableRotate = true;
  46765. this.rotateSpeed = 1.0;
  46766. // Set to false to disable panning
  46767. this.enablePan = true;
  46768. this.panSpeed = 1.0;
  46769. this.screenSpacePanning = true; // if false, pan orthogonal to world-space direction camera.up
  46770. this.keyPanSpeed = 7.0; // pixels moved per arrow key push
  46771. this.zoomToCursor = false;
  46772. // Set to true to automatically rotate around the target
  46773. // If auto-rotate is enabled, you must call controls.update() in your animation loop
  46774. this.autoRotate = false;
  46775. this.autoRotateSpeed = 2.0; // 30 seconds per orbit when fps is 60
  46776. // The four arrow keys
  46777. this.keys = {
  46778. LEFT: 'KeyA',
  46779. UP: 'KeyW',
  46780. RIGHT: 'KeyD',
  46781. BOTTOM: 'KeyS'
  46782. };
  46783. // Mouse buttons
  46784. this.mouseButtons = {
  46785. LEFT: THREE$2.MOUSE.ROTATE,
  46786. MIDDLE: THREE$2.MOUSE.DOLLY,
  46787. RIGHT: THREE$2.MOUSE.PAN
  46788. };
  46789. // Touch fingers
  46790. this.touches = {
  46791. ONE: THREE$2.TOUCH.ROTATE,
  46792. TWO: THREE$2.TOUCH.DOLLY_PAN
  46793. };
  46794. // for reset
  46795. this.target0 = this.target.clone();
  46796. this.position0 = this.object.position.clone();
  46797. this.zoom0 = this.object.zoom;
  46798. // the target DOM element for key events
  46799. this._domElementKeyEvents = null;
  46800. //
  46801. // public methods
  46802. //
  46803. this.getPolarAngle = function () {
  46804. return spherical.phi;
  46805. };
  46806. this.getAzimuthalAngle = function () {
  46807. return spherical.theta;
  46808. };
  46809. this.getDistance = function () {
  46810. return this.object.position.distanceTo(this.target);
  46811. };
  46812. this.listenToKeyEvents = function (domElement) {
  46813. domElement.addEventListener('keydown', onKeyDown);
  46814. this._domElementKeyEvents = domElement;
  46815. };
  46816. this.stopListenToKeyEvents = function () {
  46817. this._domElementKeyEvents.removeEventListener('keydown', onKeyDown);
  46818. this._domElementKeyEvents = null;
  46819. };
  46820. this.saveState = function () {
  46821. scope.target0.copy(scope.target);
  46822. scope.position0.copy(scope.object.position);
  46823. scope.zoom0 = scope.object.zoom;
  46824. };
  46825. this.reset = function () {
  46826. scope.target.copy(scope.target0);
  46827. scope.object.position.copy(scope.position0);
  46828. scope.object.zoom = scope.zoom0;
  46829. this.clearDampedRotation();
  46830. this.clearDampedPan();
  46831. scope.object.updateProjectionMatrix();
  46832. scope.dispatchEvent(_changeEvent);
  46833. scope.update();
  46834. state = STATE.NONE;
  46835. };
  46836. this.clearDampedRotation = function () {
  46837. sphericalDelta.theta = 0.0;
  46838. sphericalDelta.phi = 0.0;
  46839. };
  46840. this.clearDampedPan = function () {
  46841. panOffset.set(0, 0, 0);
  46842. };
  46843. // this method is exposed, but perhaps it would be better if we can make it private...
  46844. this.update = function () {
  46845. var offset = new THREE$2.Vector3();
  46846. // so camera.up is the orbit axis
  46847. var quat = new THREE$2.Quaternion().setFromUnitVectors(object.up, new THREE$2.Vector3(0, 1, 0));
  46848. var quatInverse = quat.clone().invert();
  46849. var lastPosition = new THREE$2.Vector3();
  46850. var lastQuaternion = new THREE$2.Quaternion();
  46851. var lastTargetPosition = new THREE$2.Vector3();
  46852. var twoPI = 2 * Math.PI;
  46853. return function update() {
  46854. quat.setFromUnitVectors(object.up, new THREE$2.Vector3(0, 1, 0));
  46855. quatInverse.copy(quat).invert();
  46856. var position = scope.object.position;
  46857. offset.copy(position).sub(scope.target);
  46858. // rotate offset to "y-axis-is-up" space
  46859. offset.applyQuaternion(quat);
  46860. // angle from z-axis around y-axis
  46861. spherical.setFromVector3(offset);
  46862. if (scope.autoRotate && state === STATE.NONE) {
  46863. rotateLeft(getAutoRotationAngle());
  46864. }
  46865. if (scope.enableDamping) {
  46866. spherical.theta += sphericalDelta.theta * scope.dampingFactor;
  46867. spherical.phi += sphericalDelta.phi * scope.dampingFactor;
  46868. } else {
  46869. spherical.theta += sphericalDelta.theta;
  46870. spherical.phi += sphericalDelta.phi;
  46871. }
  46872. // restrict theta to be between desired limits
  46873. var min = scope.minAzimuthAngle;
  46874. var max = scope.maxAzimuthAngle;
  46875. if (isFinite(min) && isFinite(max)) {
  46876. if (min < -Math.PI) min += twoPI;else if (min > Math.PI) min -= twoPI;
  46877. if (max < -Math.PI) max += twoPI;else if (max > Math.PI) max -= twoPI;
  46878. if (min <= max) {
  46879. spherical.theta = Math.max(min, Math.min(max, spherical.theta));
  46880. } else {
  46881. spherical.theta = spherical.theta > (min + max) / 2 ? Math.max(min, spherical.theta) : Math.min(max, spherical.theta);
  46882. }
  46883. }
  46884. // restrict phi to be between desired limits
  46885. spherical.phi = Math.max(scope.minPolarAngle, Math.min(scope.maxPolarAngle, spherical.phi));
  46886. spherical.makeSafe();
  46887. // move target to panned location
  46888. if (scope.enableDamping === true) {
  46889. scope.target.addScaledVector(panOffset, scope.dampingFactor);
  46890. } else {
  46891. scope.target.add(panOffset);
  46892. }
  46893. // adjust the camera position based on zoom only if we're not zooming to the cursor or if it's an ortho camera
  46894. // we adjust zoom later in these cases
  46895. if (scope.zoomToCursor && performCursorZoom || scope.object.isOrthographicCamera) {
  46896. spherical.radius = clampDistance(spherical.radius);
  46897. } else {
  46898. spherical.radius = clampDistance(spherical.radius * scale);
  46899. }
  46900. offset.setFromSpherical(spherical);
  46901. // rotate offset back to "camera-up-vector-is-up" space
  46902. offset.applyQuaternion(quatInverse);
  46903. position.copy(scope.target).add(offset);
  46904. scope.object.lookAt(scope.target);
  46905. if (scope.enableDamping === true) {
  46906. sphericalDelta.theta *= 1 - scope.dampingFactor;
  46907. sphericalDelta.phi *= 1 - scope.dampingFactor;
  46908. panOffset.multiplyScalar(1 - scope.dampingFactor);
  46909. } else {
  46910. sphericalDelta.set(0, 0, 0);
  46911. panOffset.set(0, 0, 0);
  46912. }
  46913. // adjust camera position
  46914. var zoomChanged = false;
  46915. if (scope.zoomToCursor && performCursorZoom) {
  46916. var newRadius = null;
  46917. if (scope.object.isPerspectiveCamera) {
  46918. // move the camera down the pointer ray
  46919. // this method avoids floating point error
  46920. var prevRadius = offset.length();
  46921. newRadius = clampDistance(prevRadius * scale);
  46922. var radiusDelta = prevRadius - newRadius;
  46923. scope.object.position.addScaledVector(dollyDirection, radiusDelta);
  46924. scope.object.updateMatrixWorld();
  46925. } else if (scope.object.isOrthographicCamera) {
  46926. // adjust the ortho camera position based on zoom changes
  46927. var mouseBefore = new THREE$2.Vector3(mouse.x, mouse.y, 0);
  46928. mouseBefore.unproject(scope.object);
  46929. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale));
  46930. scope.object.updateProjectionMatrix();
  46931. zoomChanged = true;
  46932. var mouseAfter = new THREE$2.Vector3(mouse.x, mouse.y, 0);
  46933. mouseAfter.unproject(scope.object);
  46934. scope.object.position.sub(mouseAfter).add(mouseBefore);
  46935. scope.object.updateMatrixWorld();
  46936. newRadius = offset.length();
  46937. } else {
  46938. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled.');
  46939. scope.zoomToCursor = false;
  46940. }
  46941. // handle the placement of the target
  46942. if (newRadius !== null) {
  46943. if (this.screenSpacePanning) {
  46944. // position the orbit target in front of the new camera position
  46945. scope.target.set(0, 0, -1).transformDirection(scope.object.matrix).multiplyScalar(newRadius).add(scope.object.position);
  46946. } else {
  46947. // get the ray and translation plane to compute target
  46948. _ray$4.origin.copy(scope.object.position);
  46949. _ray$4.direction.set(0, 0, -1).transformDirection(scope.object.matrix);
  46950. // if the camera is 20 degrees above the horizon then don't adjust the focus target to avoid
  46951. // extremely large values
  46952. if (Math.abs(scope.object.up.dot(_ray$4.direction)) < TILT_LIMIT) {
  46953. object.lookAt(scope.target);
  46954. } else {
  46955. _plane.setFromNormalAndCoplanarPoint(scope.object.up, scope.target);
  46956. _ray$4.intersectPlane(_plane, scope.target);
  46957. }
  46958. }
  46959. }
  46960. } else if (scope.object.isOrthographicCamera) {
  46961. scope.object.zoom = Math.max(scope.minZoom, Math.min(scope.maxZoom, scope.object.zoom / scale));
  46962. scope.object.updateProjectionMatrix();
  46963. zoomChanged = true;
  46964. }
  46965. scale = 1;
  46966. performCursorZoom = false;
  46967. // update condition is:
  46968. // min(camera displacement, camera rotation in radians)^2 > EPS
  46969. // using small-angle approximation cos(x/2) = 1 - x^2 / 8
  46970. if (zoomChanged || lastPosition.distanceToSquared(scope.object.position) > EPS || 8 * (1 - lastQuaternion.dot(scope.object.quaternion)) > EPS || lastTargetPosition.distanceToSquared(scope.target) > 0) {
  46971. scope.dispatchEvent(_changeEvent);
  46972. lastPosition.copy(scope.object.position);
  46973. lastQuaternion.copy(scope.object.quaternion);
  46974. lastTargetPosition.copy(scope.target);
  46975. zoomChanged = false;
  46976. return true;
  46977. }
  46978. return false;
  46979. };
  46980. }();
  46981. this.dispose = function () {
  46982. scope.domElement.removeEventListener('contextmenu', onContextMenu);
  46983. scope.domElement.removeEventListener('pointerdown', onPointerDown);
  46984. scope.domElement.removeEventListener('pointercancel', onPointerUp);
  46985. scope.domElement.removeEventListener('wheel', onMouseWheel);
  46986. scope.domElement.removeEventListener('pointermove', onPointerMove);
  46987. scope.domElement.removeEventListener('pointerup', onPointerUp);
  46988. if (scope._domElementKeyEvents !== null) {
  46989. scope._domElementKeyEvents.removeEventListener('keydown', onKeyDown);
  46990. scope._domElementKeyEvents = null;
  46991. }
  46992. };
  46993. //
  46994. // internals
  46995. //
  46996. var scope = this;
  46997. var STATE = {
  46998. NONE: -1,
  46999. ROTATE: 0,
  47000. DOLLY: 1,
  47001. PAN: 2,
  47002. TOUCH_ROTATE: 3,
  47003. TOUCH_PAN: 4,
  47004. TOUCH_DOLLY_PAN: 5,
  47005. TOUCH_DOLLY_ROTATE: 6
  47006. };
  47007. var state = STATE.NONE;
  47008. var EPS = 0.000001;
  47009. // current position in spherical coordinates
  47010. var spherical = new THREE$2.Spherical();
  47011. var sphericalDelta = new THREE$2.Spherical();
  47012. var scale = 1;
  47013. var panOffset = new THREE$2.Vector3();
  47014. var rotateStart = new THREE$2.Vector2();
  47015. var rotateEnd = new THREE$2.Vector2();
  47016. var rotateDelta = new THREE$2.Vector2();
  47017. var panStart = new THREE$2.Vector2();
  47018. var panEnd = new THREE$2.Vector2();
  47019. var panDelta = new THREE$2.Vector2();
  47020. var dollyStart = new THREE$2.Vector2();
  47021. var dollyEnd = new THREE$2.Vector2();
  47022. var dollyDelta = new THREE$2.Vector2();
  47023. var dollyDirection = new THREE$2.Vector3();
  47024. var mouse = new THREE$2.Vector2();
  47025. var performCursorZoom = false;
  47026. var pointers = [];
  47027. var pointerPositions = {};
  47028. function getAutoRotationAngle() {
  47029. return 2 * Math.PI / 60 / 60 * scope.autoRotateSpeed;
  47030. }
  47031. function getZoomScale() {
  47032. return Math.pow(0.95, scope.zoomSpeed);
  47033. }
  47034. function rotateLeft(angle) {
  47035. sphericalDelta.theta -= angle;
  47036. }
  47037. function rotateUp(angle) {
  47038. sphericalDelta.phi -= angle;
  47039. }
  47040. var panLeft = function () {
  47041. var v = new THREE$2.Vector3();
  47042. return function panLeft(distance, objectMatrix) {
  47043. v.setFromMatrixColumn(objectMatrix, 0); // get X column of objectMatrix
  47044. v.multiplyScalar(-distance);
  47045. panOffset.add(v);
  47046. };
  47047. }();
  47048. var panUp = function () {
  47049. var v = new THREE$2.Vector3();
  47050. return function panUp(distance, objectMatrix) {
  47051. if (scope.screenSpacePanning === true) {
  47052. v.setFromMatrixColumn(objectMatrix, 1);
  47053. } else {
  47054. v.setFromMatrixColumn(objectMatrix, 0);
  47055. v.crossVectors(scope.object.up, v);
  47056. }
  47057. v.multiplyScalar(distance);
  47058. panOffset.add(v);
  47059. };
  47060. }();
  47061. // deltaX and deltaY are in pixels; right and down are positive
  47062. var pan = function () {
  47063. var offset = new THREE$2.Vector3();
  47064. return function pan(deltaX, deltaY) {
  47065. var element = scope.domElement;
  47066. if (scope.object.isPerspectiveCamera) {
  47067. // perspective
  47068. var position = scope.object.position;
  47069. offset.copy(position).sub(scope.target);
  47070. var targetDistance = offset.length();
  47071. // half of the fov is center to top of screen
  47072. targetDistance *= Math.tan(scope.object.fov / 2 * Math.PI / 180.0);
  47073. // we use only clientHeight here so aspect ratio does not distort speed
  47074. panLeft(2 * deltaX * targetDistance / element.clientHeight, scope.object.matrix);
  47075. panUp(2 * deltaY * targetDistance / element.clientHeight, scope.object.matrix);
  47076. } else if (scope.object.isOrthographicCamera) {
  47077. // orthographic
  47078. panLeft(deltaX * (scope.object.right - scope.object.left) / scope.object.zoom / element.clientWidth, scope.object.matrix);
  47079. panUp(deltaY * (scope.object.top - scope.object.bottom) / scope.object.zoom / element.clientHeight, scope.object.matrix);
  47080. } else {
  47081. // camera neither orthographic nor perspective
  47082. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - pan disabled.');
  47083. scope.enablePan = false;
  47084. }
  47085. };
  47086. }();
  47087. function dollyOut(dollyScale) {
  47088. if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) {
  47089. scale /= dollyScale;
  47090. } else {
  47091. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  47092. scope.enableZoom = false;
  47093. }
  47094. }
  47095. function dollyIn(dollyScale) {
  47096. if (scope.object.isPerspectiveCamera || scope.object.isOrthographicCamera) {
  47097. scale *= dollyScale;
  47098. } else {
  47099. console.warn('WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled.');
  47100. scope.enableZoom = false;
  47101. }
  47102. }
  47103. function updateMouseParameters(event) {
  47104. if (!scope.zoomToCursor) {
  47105. return;
  47106. }
  47107. performCursorZoom = true;
  47108. var rect = scope.domElement.getBoundingClientRect();
  47109. var x = event.clientX - rect.left;
  47110. var y = event.clientY - rect.top;
  47111. var w = rect.width;
  47112. var h = rect.height;
  47113. mouse.x = x / w * 2 - 1;
  47114. mouse.y = -(y / h) * 2 + 1;
  47115. dollyDirection.set(mouse.x, mouse.y, 1).unproject(object).sub(object.position).normalize();
  47116. }
  47117. function clampDistance(dist) {
  47118. return Math.max(scope.minDistance, Math.min(scope.maxDistance, dist));
  47119. }
  47120. //
  47121. // event callbacks - update the object state
  47122. //
  47123. function handleMouseDownRotate(event) {
  47124. rotateStart.set(event.clientX, event.clientY);
  47125. }
  47126. function handleMouseDownDolly(event) {
  47127. updateMouseParameters(event);
  47128. dollyStart.set(event.clientX, event.clientY);
  47129. }
  47130. function handleMouseDownPan(event) {
  47131. panStart.set(event.clientX, event.clientY);
  47132. }
  47133. function handleMouseMoveRotate(event) {
  47134. rotateEnd.set(event.clientX, event.clientY);
  47135. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  47136. var element = scope.domElement;
  47137. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  47138. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  47139. rotateStart.copy(rotateEnd);
  47140. scope.update();
  47141. }
  47142. function handleMouseMoveDolly(event) {
  47143. dollyEnd.set(event.clientX, event.clientY);
  47144. dollyDelta.subVectors(dollyEnd, dollyStart);
  47145. if (dollyDelta.y > 0) {
  47146. dollyOut(getZoomScale());
  47147. } else if (dollyDelta.y < 0) {
  47148. dollyIn(getZoomScale());
  47149. }
  47150. dollyStart.copy(dollyEnd);
  47151. scope.update();
  47152. }
  47153. function handleMouseMovePan(event) {
  47154. panEnd.set(event.clientX, event.clientY);
  47155. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  47156. pan(panDelta.x, panDelta.y);
  47157. panStart.copy(panEnd);
  47158. scope.update();
  47159. }
  47160. function handleMouseWheel(event) {
  47161. updateMouseParameters(event);
  47162. if (event.deltaY < 0) {
  47163. dollyIn(getZoomScale());
  47164. } else if (event.deltaY > 0) {
  47165. dollyOut(getZoomScale());
  47166. }
  47167. scope.update();
  47168. }
  47169. function handleKeyDown(event) {
  47170. var needsUpdate = false;
  47171. switch (event.code) {
  47172. case scope.keys.UP:
  47173. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47174. rotateUp(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight);
  47175. } else {
  47176. pan(0, scope.keyPanSpeed);
  47177. }
  47178. needsUpdate = true;
  47179. break;
  47180. case scope.keys.BOTTOM:
  47181. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47182. rotateUp(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight);
  47183. } else {
  47184. pan(0, -scope.keyPanSpeed);
  47185. }
  47186. needsUpdate = true;
  47187. break;
  47188. case scope.keys.LEFT:
  47189. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47190. rotateLeft(2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight);
  47191. } else {
  47192. pan(scope.keyPanSpeed, 0);
  47193. }
  47194. needsUpdate = true;
  47195. break;
  47196. case scope.keys.RIGHT:
  47197. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47198. rotateLeft(-2 * Math.PI * scope.rotateSpeed / scope.domElement.clientHeight);
  47199. } else {
  47200. pan(-scope.keyPanSpeed, 0);
  47201. }
  47202. needsUpdate = true;
  47203. break;
  47204. }
  47205. if (needsUpdate) {
  47206. // prevent the browser from scrolling on cursor keys
  47207. event.preventDefault();
  47208. scope.update();
  47209. }
  47210. }
  47211. function handleTouchStartRotate() {
  47212. if (pointers.length === 1) {
  47213. rotateStart.set(pointers[0].pageX, pointers[0].pageY);
  47214. } else {
  47215. var x = 0.5 * (pointers[0].pageX + pointers[1].pageX);
  47216. var y = 0.5 * (pointers[0].pageY + pointers[1].pageY);
  47217. rotateStart.set(x, y);
  47218. }
  47219. }
  47220. function handleTouchStartPan() {
  47221. if (pointers.length === 1) {
  47222. panStart.set(pointers[0].pageX, pointers[0].pageY);
  47223. } else {
  47224. var x = 0.5 * (pointers[0].pageX + pointers[1].pageX);
  47225. var y = 0.5 * (pointers[0].pageY + pointers[1].pageY);
  47226. panStart.set(x, y);
  47227. }
  47228. }
  47229. function handleTouchStartDolly() {
  47230. var dx = pointers[0].pageX - pointers[1].pageX;
  47231. var dy = pointers[0].pageY - pointers[1].pageY;
  47232. var distance = Math.sqrt(dx * dx + dy * dy);
  47233. dollyStart.set(0, distance);
  47234. }
  47235. function handleTouchStartDollyPan() {
  47236. if (scope.enableZoom) handleTouchStartDolly();
  47237. if (scope.enablePan) handleTouchStartPan();
  47238. }
  47239. function handleTouchStartDollyRotate() {
  47240. if (scope.enableZoom) handleTouchStartDolly();
  47241. if (scope.enableRotate) handleTouchStartRotate();
  47242. }
  47243. function handleTouchMoveRotate(event) {
  47244. if (pointers.length == 1) {
  47245. rotateEnd.set(event.pageX, event.pageY);
  47246. } else {
  47247. var position = getSecondPointerPosition(event);
  47248. var x = 0.5 * (event.pageX + position.x);
  47249. var y = 0.5 * (event.pageY + position.y);
  47250. rotateEnd.set(x, y);
  47251. }
  47252. rotateDelta.subVectors(rotateEnd, rotateStart).multiplyScalar(scope.rotateSpeed);
  47253. var element = scope.domElement;
  47254. rotateLeft(2 * Math.PI * rotateDelta.x / element.clientHeight); // yes, height
  47255. rotateUp(2 * Math.PI * rotateDelta.y / element.clientHeight);
  47256. rotateStart.copy(rotateEnd);
  47257. }
  47258. function handleTouchMovePan(event) {
  47259. if (pointers.length === 1) {
  47260. panEnd.set(event.pageX, event.pageY);
  47261. } else {
  47262. var position = getSecondPointerPosition(event);
  47263. var x = 0.5 * (event.pageX + position.x);
  47264. var y = 0.5 * (event.pageY + position.y);
  47265. panEnd.set(x, y);
  47266. }
  47267. panDelta.subVectors(panEnd, panStart).multiplyScalar(scope.panSpeed);
  47268. pan(panDelta.x, panDelta.y);
  47269. panStart.copy(panEnd);
  47270. }
  47271. function handleTouchMoveDolly(event) {
  47272. var position = getSecondPointerPosition(event);
  47273. var dx = event.pageX - position.x;
  47274. var dy = event.pageY - position.y;
  47275. var distance = Math.sqrt(dx * dx + dy * dy);
  47276. dollyEnd.set(0, distance);
  47277. dollyDelta.set(0, Math.pow(dollyEnd.y / dollyStart.y, scope.zoomSpeed));
  47278. dollyOut(dollyDelta.y);
  47279. dollyStart.copy(dollyEnd);
  47280. }
  47281. function handleTouchMoveDollyPan(event) {
  47282. if (scope.enableZoom) handleTouchMoveDolly(event);
  47283. if (scope.enablePan) handleTouchMovePan(event);
  47284. }
  47285. function handleTouchMoveDollyRotate(event) {
  47286. if (scope.enableZoom) handleTouchMoveDolly(event);
  47287. if (scope.enableRotate) handleTouchMoveRotate(event);
  47288. }
  47289. //
  47290. // event handlers - FSM: listen for events and reset state
  47291. //
  47292. function onPointerDown(event) {
  47293. if (scope.enabled === false) return;
  47294. if (pointers.length === 0) {
  47295. scope.domElement.setPointerCapture(event.pointerId);
  47296. scope.domElement.addEventListener('pointermove', onPointerMove);
  47297. scope.domElement.addEventListener('pointerup', onPointerUp);
  47298. }
  47299. //
  47300. addPointer(event);
  47301. if (event.pointerType === 'touch') {
  47302. onTouchStart(event);
  47303. } else {
  47304. onMouseDown(event);
  47305. }
  47306. }
  47307. function onPointerMove(event) {
  47308. if (scope.enabled === false) return;
  47309. if (event.pointerType === 'touch') {
  47310. onTouchMove(event);
  47311. } else {
  47312. onMouseMove(event);
  47313. }
  47314. }
  47315. function onPointerUp(event) {
  47316. removePointer(event);
  47317. if (pointers.length === 0) {
  47318. scope.domElement.releasePointerCapture(event.pointerId);
  47319. scope.domElement.removeEventListener('pointermove', onPointerMove);
  47320. scope.domElement.removeEventListener('pointerup', onPointerUp);
  47321. }
  47322. scope.dispatchEvent(_endEvent);
  47323. state = STATE.NONE;
  47324. }
  47325. function onMouseDown(event) {
  47326. var mouseAction;
  47327. switch (event.button) {
  47328. case 0:
  47329. mouseAction = scope.mouseButtons.LEFT;
  47330. break;
  47331. case 1:
  47332. mouseAction = scope.mouseButtons.MIDDLE;
  47333. break;
  47334. case 2:
  47335. mouseAction = scope.mouseButtons.RIGHT;
  47336. break;
  47337. default:
  47338. mouseAction = -1;
  47339. }
  47340. switch (mouseAction) {
  47341. case THREE$2.MOUSE.DOLLY:
  47342. if (scope.enableZoom === false) return;
  47343. handleMouseDownDolly(event);
  47344. state = STATE.DOLLY;
  47345. break;
  47346. case THREE$2.MOUSE.ROTATE:
  47347. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47348. if (scope.enablePan === false) return;
  47349. handleMouseDownPan(event);
  47350. state = STATE.PAN;
  47351. } else {
  47352. if (scope.enableRotate === false) return;
  47353. handleMouseDownRotate(event);
  47354. state = STATE.ROTATE;
  47355. }
  47356. break;
  47357. case THREE$2.MOUSE.PAN:
  47358. if (event.ctrlKey || event.metaKey || event.shiftKey) {
  47359. if (scope.enableRotate === false) return;
  47360. handleMouseDownRotate(event);
  47361. state = STATE.ROTATE;
  47362. } else {
  47363. if (scope.enablePan === false) return;
  47364. handleMouseDownPan(event);
  47365. state = STATE.PAN;
  47366. }
  47367. break;
  47368. default:
  47369. state = STATE.NONE;
  47370. }
  47371. if (state !== STATE.NONE) {
  47372. scope.dispatchEvent(_startEvent);
  47373. }
  47374. }
  47375. function onMouseMove(event) {
  47376. switch (state) {
  47377. case STATE.ROTATE:
  47378. if (scope.enableRotate === false) return;
  47379. handleMouseMoveRotate(event);
  47380. break;
  47381. case STATE.DOLLY:
  47382. if (scope.enableZoom === false) return;
  47383. handleMouseMoveDolly(event);
  47384. break;
  47385. case STATE.PAN:
  47386. if (scope.enablePan === false) return;
  47387. handleMouseMovePan(event);
  47388. break;
  47389. }
  47390. }
  47391. function onMouseWheel(event) {
  47392. if (scope.enabled === false || scope.enableZoom === false || state !== STATE.NONE) return;
  47393. event.preventDefault();
  47394. scope.dispatchEvent(_startEvent);
  47395. handleMouseWheel(event);
  47396. scope.dispatchEvent(_endEvent);
  47397. }
  47398. function onKeyDown(event) {
  47399. if (scope.enabled === false || scope.enablePan === false) return;
  47400. handleKeyDown(event);
  47401. }
  47402. function onTouchStart(event) {
  47403. trackPointer(event);
  47404. switch (pointers.length) {
  47405. case 1:
  47406. switch (scope.touches.ONE) {
  47407. case THREE$2.TOUCH.ROTATE:
  47408. if (scope.enableRotate === false) return;
  47409. handleTouchStartRotate();
  47410. state = STATE.TOUCH_ROTATE;
  47411. break;
  47412. case THREE$2.TOUCH.PAN:
  47413. if (scope.enablePan === false) return;
  47414. handleTouchStartPan();
  47415. state = STATE.TOUCH_PAN;
  47416. break;
  47417. default:
  47418. state = STATE.NONE;
  47419. }
  47420. break;
  47421. case 2:
  47422. switch (scope.touches.TWO) {
  47423. case THREE$2.TOUCH.DOLLY_PAN:
  47424. if (scope.enableZoom === false && scope.enablePan === false) return;
  47425. handleTouchStartDollyPan();
  47426. state = STATE.TOUCH_DOLLY_PAN;
  47427. break;
  47428. case THREE$2.TOUCH.DOLLY_ROTATE:
  47429. if (scope.enableZoom === false && scope.enableRotate === false) return;
  47430. handleTouchStartDollyRotate();
  47431. state = STATE.TOUCH_DOLLY_ROTATE;
  47432. break;
  47433. default:
  47434. state = STATE.NONE;
  47435. }
  47436. break;
  47437. default:
  47438. state = STATE.NONE;
  47439. }
  47440. if (state !== STATE.NONE) {
  47441. scope.dispatchEvent(_startEvent);
  47442. }
  47443. }
  47444. function onTouchMove(event) {
  47445. trackPointer(event);
  47446. switch (state) {
  47447. case STATE.TOUCH_ROTATE:
  47448. if (scope.enableRotate === false) return;
  47449. handleTouchMoveRotate(event);
  47450. scope.update();
  47451. break;
  47452. case STATE.TOUCH_PAN:
  47453. if (scope.enablePan === false) return;
  47454. handleTouchMovePan(event);
  47455. scope.update();
  47456. break;
  47457. case STATE.TOUCH_DOLLY_PAN:
  47458. if (scope.enableZoom === false && scope.enablePan === false) return;
  47459. handleTouchMoveDollyPan(event);
  47460. scope.update();
  47461. break;
  47462. case STATE.TOUCH_DOLLY_ROTATE:
  47463. if (scope.enableZoom === false && scope.enableRotate === false) return;
  47464. handleTouchMoveDollyRotate(event);
  47465. scope.update();
  47466. break;
  47467. default:
  47468. state = STATE.NONE;
  47469. }
  47470. }
  47471. function onContextMenu(event) {
  47472. if (scope.enabled === false) return;
  47473. event.preventDefault();
  47474. }
  47475. function addPointer(event) {
  47476. pointers.push(event);
  47477. }
  47478. function removePointer(event) {
  47479. delete pointerPositions[event.pointerId];
  47480. for (var i = 0; i < pointers.length; i++) {
  47481. if (pointers[i].pointerId == event.pointerId) {
  47482. pointers.splice(i, 1);
  47483. return;
  47484. }
  47485. }
  47486. }
  47487. function trackPointer(event) {
  47488. var position = pointerPositions[event.pointerId];
  47489. if (position === undefined) {
  47490. position = new THREE$2.Vector2();
  47491. pointerPositions[event.pointerId] = position;
  47492. }
  47493. position.set(event.pageX, event.pageY);
  47494. }
  47495. function getSecondPointerPosition(event) {
  47496. var pointer = event.pointerId === pointers[0].pointerId ? pointers[1] : pointers[0];
  47497. return pointerPositions[pointer.pointerId];
  47498. }
  47499. //
  47500. scope.domElement.addEventListener('contextmenu', onContextMenu);
  47501. scope.domElement.addEventListener('pointerdown', onPointerDown);
  47502. scope.domElement.addEventListener('pointercancel', onPointerUp);
  47503. scope.domElement.addEventListener('wheel', onMouseWheel, {
  47504. passive: false
  47505. });
  47506. // force an update at start
  47507. this.update();
  47508. }
  47509. }
  47510. var fadeElement = (element, out, displayStyle, duration, onComplete) => {
  47511. var startTime = performance.now();
  47512. var startOpacity = element.style.display === 'none' ? 0 : parseFloat(element.style.opacity);
  47513. if (isNaN(startOpacity)) startOpacity = 1;
  47514. var interval = window.setInterval(() => {
  47515. var currentTime = performance.now();
  47516. var elapsed = currentTime - startTime;
  47517. var t = Math.min(elapsed / duration, 1.0);
  47518. if (t > 0.999) t = 1;
  47519. var opacity;
  47520. if (out) {
  47521. opacity = (1.0 - t) * startOpacity;
  47522. if (opacity < 0.0001) opacity = 0;
  47523. } else {
  47524. opacity = (1.0 - startOpacity) * t + startOpacity;
  47525. }
  47526. if (opacity > 0) {
  47527. element.style.display = displayStyle;
  47528. element.style.opacity = opacity;
  47529. } else {
  47530. element.style.display = 'none';
  47531. }
  47532. if (t >= 1) {
  47533. if (onComplete) onComplete();
  47534. window.clearInterval(interval);
  47535. }
  47536. }, 16);
  47537. return interval;
  47538. };
  47539. var cancelFade = interval => {
  47540. window.clearInterval(interval);
  47541. };
  47542. var STANDARD_FADE_DURATION = 500;
  47543. class LoadingSpinner {
  47544. constructor(message, container) {
  47545. this.taskIDGen = 0;
  47546. this.elementID = LoadingSpinner.elementIDGen++;
  47547. this.tasks = [];
  47548. this.message = message || 'Loading...';
  47549. this.container = container || document.body;
  47550. this.spinnerContainerOuter = document.createElement('div');
  47551. this.spinnerContainerOuter.className = "spinnerOuterContainer".concat(this.elementID);
  47552. this.spinnerContainerOuter.style.display = 'none';
  47553. this.spinnerContainerPrimary = document.createElement('div');
  47554. this.spinnerContainerPrimary.className = "spinnerContainerPrimary".concat(this.elementID);
  47555. this.spinnerPrimary = document.createElement('div');
  47556. this.spinnerPrimary.classList.add("spinner".concat(this.elementID), "spinnerPrimary".concat(this.elementID));
  47557. this.messageContainerPrimary = document.createElement('div');
  47558. this.messageContainerPrimary.classList.add("messageContainer".concat(this.elementID), "messageContainerPrimary".concat(this.elementID));
  47559. this.messageContainerPrimary.innerHTML = this.message;
  47560. this.spinnerContainerMin = document.createElement('div');
  47561. this.spinnerContainerMin.className = "spinnerContainerMin".concat(this.elementID);
  47562. this.spinnerMin = document.createElement('div');
  47563. this.spinnerMin.classList.add("spinner".concat(this.elementID), "spinnerMin".concat(this.elementID));
  47564. this.messageContainerMin = document.createElement('div');
  47565. this.messageContainerMin.classList.add("messageContainer".concat(this.elementID), "messageContainerMin".concat(this.elementID));
  47566. this.messageContainerMin.innerHTML = this.message;
  47567. this.spinnerContainerPrimary.appendChild(this.spinnerPrimary);
  47568. this.spinnerContainerPrimary.appendChild(this.messageContainerPrimary);
  47569. this.spinnerContainerOuter.appendChild(this.spinnerContainerPrimary);
  47570. this.spinnerContainerMin.appendChild(this.spinnerMin);
  47571. this.spinnerContainerMin.appendChild(this.messageContainerMin);
  47572. this.spinnerContainerOuter.appendChild(this.spinnerContainerMin);
  47573. var style = document.createElement('style');
  47574. style.innerHTML = "\n\n .spinnerOuterContainer".concat(this.elementID, " {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .messageContainer").concat(this.elementID, " {\n height: 20px;\n font-family: arial;\n font-size: 12pt;\n color: #ffffff;\n text-align: center;\n vertical-align: middle;\n }\n\n .spinner").concat(this.elementID, " {\n padding: 15px;\n background: #07e8d6;\n z-index:99999;\n \n aspect-ratio: 1;\n border-radius: 50%;\n --_m: \n conic-gradient(#0000,#000),\n linear-gradient(#000 0 0) content-box;\n -webkit-mask: var(--_m);\n mask: var(--_m);\n -webkit-mask-composite: source-out;\n mask-composite: subtract;\n box-sizing: border-box;\n animation: load 1s linear infinite;\n }\n\n .spinnerContainerPrimary").concat(this.elementID, " {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 10px;\n margin: 0;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-80px, -80px);\n width: 180px;\n pointer-events: auto;\n }\n\n .spinnerPrimary").concat(this.elementID, " {\n width: 120px;\n margin-left: 30px;\n }\n\n .messageContainerPrimary").concat(this.elementID, " {\n padding-top: 15px;\n }\n\n .spinnerContainerMin").concat(this.elementID, " {\n z-index:99999;\n background-color: rgba(128, 128, 128, 0.75);\n border: #666666 1px solid;\n border-radius: 5px;\n padding-top: 20px;\n padding-bottom: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n display: flex;\n flex-direction: left;\n pointer-events: auto;\n min-width: 250px;\n }\n\n .messageContainerMin").concat(this.elementID, " {\n margin-right: 15px;\n }\n\n .spinnerMin").concat(this.elementID, " {\n width: 50px;\n height: 50px;\n margin-left: 15px;\n margin-right: 25px;\n }\n\n .messageContainerMin").concat(this.elementID, " {\n padding-top: 15px;\n }\n \n @keyframes load {\n to{transform: rotate(1turn)}\n }\n\n ");
  47575. this.spinnerContainerOuter.appendChild(style);
  47576. this.container.appendChild(this.spinnerContainerOuter);
  47577. this.setMinimized(false, true);
  47578. this.fadeTransitions = [];
  47579. }
  47580. addTask(message) {
  47581. var newTask = {
  47582. 'message': message,
  47583. 'id': this.taskIDGen++
  47584. };
  47585. this.tasks.push(newTask);
  47586. this.update();
  47587. return newTask.id;
  47588. }
  47589. removeTask(id) {
  47590. var index = 0;
  47591. for (var task of this.tasks) {
  47592. if (task.id === id) {
  47593. this.tasks.splice(index, 1);
  47594. break;
  47595. }
  47596. index++;
  47597. }
  47598. this.update();
  47599. }
  47600. removeAllTasks() {
  47601. this.tasks = [];
  47602. this.update();
  47603. }
  47604. setMessageForTask(id, message) {
  47605. for (var task of this.tasks) {
  47606. if (task.id === id) {
  47607. task.message = message;
  47608. break;
  47609. }
  47610. }
  47611. this.update();
  47612. }
  47613. update() {
  47614. if (this.tasks.length > 0) {
  47615. this.show();
  47616. this.setMessage(this.tasks[this.tasks.length - 1].message);
  47617. } else {
  47618. this.hide();
  47619. }
  47620. }
  47621. show() {
  47622. this.spinnerContainerOuter.style.display = 'block';
  47623. this.visible = true;
  47624. }
  47625. hide() {
  47626. this.spinnerContainerOuter.style.display = 'none';
  47627. this.visible = false;
  47628. }
  47629. setContainer(container) {
  47630. if (this.container) {
  47631. this.container.removeChild(this.spinnerContainerOuter);
  47632. }
  47633. if (container) {
  47634. this.container = container;
  47635. this.container.appendChild(this.spinnerContainerOuter);
  47636. this.spinnerContainerOuter.style.zIndex = this.container.style.zIndex + 1;
  47637. }
  47638. }
  47639. setMinimized(minimized, instant) {
  47640. var showHideSpinner = (element, show, instant, displayStyle, fadeTransitionsIndex) => {
  47641. if (instant) {
  47642. element.style.display = show ? displayStyle : 'none';
  47643. } else {
  47644. this.fadeTransitions[fadeTransitionsIndex] = fadeElement(element, !show, displayStyle, STANDARD_FADE_DURATION, () => {
  47645. this.fadeTransitions[fadeTransitionsIndex] = null;
  47646. });
  47647. }
  47648. };
  47649. showHideSpinner(this.spinnerContainerPrimary, !minimized, instant, 'block', 0);
  47650. showHideSpinner(this.spinnerContainerMin, minimized, instant, 'flex', 1);
  47651. this.minimized = minimized;
  47652. }
  47653. setMessage(msg) {
  47654. this.messageContainerPrimary.innerHTML = msg;
  47655. this.messageContainerMin.innerHTML = msg;
  47656. }
  47657. }
  47658. _defineProperty(LoadingSpinner, "elementIDGen", 0);
  47659. class LoadingProgressBar {
  47660. constructor(container) {
  47661. this.idGen = 0;
  47662. this.tasks = [];
  47663. this.container = container || document.body;
  47664. this.progressBarContainerOuter = document.createElement('div');
  47665. this.progressBarContainerOuter.className = 'progressBarOuterContainer';
  47666. this.progressBarContainerOuter.style.display = 'none';
  47667. this.progressBarBox = document.createElement('div');
  47668. this.progressBarBox.className = 'progressBarBox';
  47669. this.progressBarBackground = document.createElement('div');
  47670. this.progressBarBackground.className = 'progressBarBackground';
  47671. this.progressBar = document.createElement('div');
  47672. this.progressBar.className = 'progressBar';
  47673. this.progressBarBackground.appendChild(this.progressBar);
  47674. this.progressBarBox.appendChild(this.progressBarBackground);
  47675. this.progressBarContainerOuter.appendChild(this.progressBarBox);
  47676. var style = document.createElement('style');
  47677. style.innerHTML = "\n\n .progressBarOuterContainer {\n width: 100%;\n height: 100%;\n margin: 0;\n top: 0;\n left: 0;\n position: absolute;\n pointer-events: none;\n }\n\n .progressBarBox {\n z-index:99999;\n padding: 7px 9px 5px 7px;\n background-color: rgba(190, 190, 190, 0.75);\n border: #555555 1px solid;\n border-radius: 15px;\n margin: 0;\n position: absolute;\n bottom: 50px;\n left: 50%;\n transform: translate(-50%, 0);\n width: 180px;\n height: 30px;\n pointer-events: auto;\n }\n\n .progressBarBackground {\n width: 100%;\n height: 25px;\n border-radius:10px;\n background-color: rgba(128, 128, 128, 0.75);\n border: #444444 1px solid;\n box-shadow: inset 0 0 10px #333333;\n }\n\n .progressBar {\n height: 25px;\n width: 0px;\n border-radius:10px;\n background-color: rgba(0, 200, 0, 0.75);\n box-shadow: inset 0 0 10px #003300;\n }\n\n ";
  47678. this.progressBarContainerOuter.appendChild(style);
  47679. this.container.appendChild(this.progressBarContainerOuter);
  47680. }
  47681. show() {
  47682. this.progressBarContainerOuter.style.display = 'block';
  47683. }
  47684. hide() {
  47685. this.progressBarContainerOuter.style.display = 'none';
  47686. }
  47687. setProgress(progress) {
  47688. this.progressBar.style.width = progress + '%';
  47689. }
  47690. setContainer(container) {
  47691. if (this.container) {
  47692. this.container.removeChild(this.progressBarContainerOuter);
  47693. }
  47694. if (container) {
  47695. this.container = container;
  47696. this.container.appendChild(this.progressBarContainerOuter);
  47697. this.progressBarContainerOuter.style.zIndex = this.container.style.zIndex + 1;
  47698. }
  47699. }
  47700. }
  47701. class InfoPanel {
  47702. constructor(container) {
  47703. _defineProperty(this, "update", function (renderDimensions, cameraPosition, cameraLookAtPosition, cameraUp, orthographicCamera, meshCursorPosition, currentFPS, splatCount, splatRenderCount, splatRenderCountPct, lastSortTime, focalAdjustment, splatScale, pointCloudMode) {
  47704. var cameraPosString = "".concat(cameraPosition.x.toFixed(5), ", ").concat(cameraPosition.y.toFixed(5), ", ").concat(cameraPosition.z.toFixed(5));
  47705. if (this.infoCells.cameraPosition.innerHTML !== cameraPosString) {
  47706. this.infoCells.cameraPosition.innerHTML = cameraPosString;
  47707. }
  47708. if (cameraLookAtPosition) {
  47709. var cla = cameraLookAtPosition;
  47710. var cameraLookAtString = "".concat(cla.x.toFixed(5), ", ").concat(cla.y.toFixed(5), ", ").concat(cla.z.toFixed(5));
  47711. if (this.infoCells.cameraLookAt.innerHTML !== cameraLookAtString) {
  47712. this.infoCells.cameraLookAt.innerHTML = cameraLookAtString;
  47713. }
  47714. }
  47715. var cameraUpString = "".concat(cameraUp.x.toFixed(5), ", ").concat(cameraUp.y.toFixed(5), ", ").concat(cameraUp.z.toFixed(5));
  47716. if (this.infoCells.cameraUp.innerHTML !== cameraUpString) {
  47717. this.infoCells.cameraUp.innerHTML = cameraUpString;
  47718. }
  47719. this.infoCells.orthographicCamera.innerHTML = orthographicCamera ? 'Orthographic' : 'Perspective';
  47720. if (meshCursorPosition) {
  47721. var cursPos = meshCursorPosition;
  47722. var cursorPosString = "".concat(cursPos.x.toFixed(5), ", ").concat(cursPos.y.toFixed(5), ", ").concat(cursPos.z.toFixed(5));
  47723. this.infoCells.cursorPosition.innerHTML = cursorPosString;
  47724. } else {
  47725. this.infoCells.cursorPosition.innerHTML = 'N/A';
  47726. }
  47727. this.infoCells.fps.innerHTML = currentFPS;
  47728. this.infoCells.renderWindow.innerHTML = "".concat(renderDimensions.x, " x ").concat(renderDimensions.y);
  47729. this.infoCells.renderSplatCount.innerHTML = "".concat(splatRenderCount, " splats out of ").concat(splatCount, " (").concat(splatRenderCountPct.toFixed(2), "%)");
  47730. this.infoCells.sortTime.innerHTML = "".concat(lastSortTime.toFixed(3), " ms");
  47731. this.infoCells.focalAdjustment.innerHTML = "".concat(focalAdjustment.toFixed(3));
  47732. this.infoCells.splatScale.innerHTML = "".concat(splatScale.toFixed(3));
  47733. this.infoCells.pointCloudMode.innerHTML = "".concat(pointCloudMode);
  47734. });
  47735. this.container = container || document.body;
  47736. this.infoCells = {};
  47737. var layout = [['Camera position', 'cameraPosition'], ['Camera look-at', 'cameraLookAt'], ['Camera up', 'cameraUp'], ['Camera mode', 'orthographicCamera'], ['Cursor position', 'cursorPosition'], ['FPS', 'fps'], ['Rendering:', 'renderSplatCount'], ['Sort time', 'sortTime'], ['Render window', 'renderWindow'], ['Focal adjustment', 'focalAdjustment'], ['Splat scale', 'splatScale'], ['Point cloud mode', 'pointCloudMode']];
  47738. this.infoPanelContainer = document.createElement('div');
  47739. var style = document.createElement('style');
  47740. style.innerHTML = "\n\n .infoPanel {\n width: 430px;\n padding: 10px;\n background-color: rgba(50, 50, 50, 0.85);\n border: #555555 2px solid;\n color: #dddddd;\n border-radius: 10px;\n z-index: 9999;\n font-family: arial;\n font-size: 11pt;\n text-align: left;\n margin: 0;\n top: 10px;\n left:10px;\n position: absolute;\n pointer-events: auto;\n }\n\n .info-panel-cell {\n margin-bottom: 5px;\n padding-bottom: 2px;\n }\n\n .label-cell {\n font-weight: bold;\n font-size: 12pt;\n width: 140px;\n }\n\n ";
  47741. this.infoPanelContainer.append(style);
  47742. this.infoPanel = document.createElement('div');
  47743. this.infoPanel.className = 'infoPanel';
  47744. var infoTable = document.createElement('div');
  47745. infoTable.style.display = 'table';
  47746. for (var layoutEntry of layout) {
  47747. var row = document.createElement('div');
  47748. row.style.display = 'table-row';
  47749. row.className = 'info-panel-row';
  47750. var labelCell = document.createElement('div');
  47751. labelCell.style.display = 'table-cell';
  47752. labelCell.innerHTML = "".concat(layoutEntry[0], ": ");
  47753. labelCell.classList.add('info-panel-cell', 'label-cell');
  47754. var spacerCell = document.createElement('div');
  47755. spacerCell.style.display = 'table-cell';
  47756. spacerCell.style.width = '10px';
  47757. spacerCell.innerHTML = ' ';
  47758. spacerCell.className = 'info-panel-cell';
  47759. var infoCell = document.createElement('div');
  47760. infoCell.style.display = 'table-cell';
  47761. infoCell.innerHTML = '';
  47762. infoCell.className = 'info-panel-cell';
  47763. this.infoCells[layoutEntry[1]] = infoCell;
  47764. row.appendChild(labelCell);
  47765. row.appendChild(spacerCell);
  47766. row.appendChild(infoCell);
  47767. infoTable.appendChild(row);
  47768. }
  47769. this.infoPanel.appendChild(infoTable);
  47770. this.infoPanelContainer.append(this.infoPanel);
  47771. this.infoPanelContainer.style.display = 'none';
  47772. this.container.appendChild(this.infoPanelContainer);
  47773. this.visible = false;
  47774. }
  47775. setContainer(container) {
  47776. if (this.container) {
  47777. this.container.removeChild(this.infoPanelContainer);
  47778. }
  47779. if (container) {
  47780. this.container = container;
  47781. this.container.appendChild(this.infoPanelContainer);
  47782. this.infoPanelContainer.style.zIndex = this.container.style.zIndex + 1;
  47783. }
  47784. }
  47785. show() {
  47786. this.infoPanelContainer.style.display = 'block';
  47787. this.visible = true;
  47788. }
  47789. hide() {
  47790. this.infoPanelContainer.style.display = 'none';
  47791. this.visible = false;
  47792. }
  47793. }
  47794. class ArrowHelper$1 extends THREE$2.Object3D {
  47795. constructor() {
  47796. var dir = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new THREE$2.Vector3(0, 0, 1);
  47797. var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE$2.Vector3(0, 0, 0);
  47798. var length = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  47799. var radius = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.1;
  47800. var color = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0xffff00;
  47801. var headLength = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : length * 0.2;
  47802. var headRadius = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : headLength * 0.2;
  47803. super();
  47804. this.type = 'ArrowHelper';
  47805. var lineGeometry = new THREE$2.CylinderGeometry(radius, radius, length, 32);
  47806. lineGeometry.translate(0, length / 2.0, 0);
  47807. var coneGeometry = new THREE$2.CylinderGeometry(0, headRadius, headLength, 32);
  47808. coneGeometry.translate(0, length, 0);
  47809. this.position.copy(origin);
  47810. this.line = new THREE$2.Mesh(lineGeometry, new THREE$2.MeshBasicMaterial({
  47811. color: color,
  47812. toneMapped: false
  47813. }));
  47814. this.line.matrixAutoUpdate = false;
  47815. this.add(this.line);
  47816. this.cone = new THREE$2.Mesh(coneGeometry, new THREE$2.MeshBasicMaterial({
  47817. color: color,
  47818. toneMapped: false
  47819. }));
  47820. this.cone.matrixAutoUpdate = false;
  47821. this.add(this.cone);
  47822. this.setDirection(dir);
  47823. }
  47824. setDirection(dir) {
  47825. if (dir.y > 0.99999) {
  47826. this.quaternion.set(0, 0, 0, 1);
  47827. } else if (dir.y < -0.99999) {
  47828. this.quaternion.set(1, 0, 0, 0);
  47829. } else {
  47830. _axis.set(dir.z, 0, -dir.x).normalize();
  47831. var radians = Math.acos(dir.y);
  47832. this.quaternion.setFromAxisAngle(_axis, radians);
  47833. }
  47834. }
  47835. setColor(color) {
  47836. this.line.material.color.set(color);
  47837. this.cone.material.color.set(color);
  47838. }
  47839. copy(source) {
  47840. super.copy(source, false);
  47841. this.line.copy(source.line);
  47842. this.cone.copy(source.cone);
  47843. return this;
  47844. }
  47845. dispose() {
  47846. this.line.geometry.dispose();
  47847. this.line.material.dispose();
  47848. this.cone.geometry.dispose();
  47849. this.cone.material.dispose();
  47850. }
  47851. }
  47852. class SceneHelper {
  47853. constructor(threeScene) {
  47854. _defineProperty(this, "updateFocusMarker", function () {
  47855. var tempPosition = new THREE$2.Vector3();
  47856. var tempMatrix = new THREE$2.Matrix4();
  47857. var toCamera = new THREE$2.Vector3();
  47858. return function (position, camera, viewport) {
  47859. tempMatrix.copy(camera.matrixWorld).invert();
  47860. tempPosition.copy(position).applyMatrix4(tempMatrix);
  47861. tempPosition.normalize().multiplyScalar(10);
  47862. tempPosition.applyMatrix4(camera.matrixWorld);
  47863. toCamera.copy(camera.position).sub(position);
  47864. var toCameraDistance = toCamera.length();
  47865. this.focusMarker.position.copy(position);
  47866. this.focusMarker.scale.set(toCameraDistance, toCameraDistance, toCameraDistance);
  47867. this.focusMarker.material.uniforms.realFocusPosition.value.copy(position);
  47868. this.focusMarker.material.uniforms.viewport.value.copy(viewport);
  47869. this.focusMarker.material.uniformsNeedUpdate = true;
  47870. };
  47871. }());
  47872. _defineProperty(this, "positionAndOrientControlPlane", function () {
  47873. var tempQuaternion = new THREE$2.Quaternion();
  47874. var defaultUp = new THREE$2.Vector3(0, 1, 0);
  47875. return function (position, up) {
  47876. tempQuaternion.setFromUnitVectors(defaultUp, up);
  47877. this.controlPlane.position.copy(position);
  47878. this.controlPlane.quaternion.copy(tempQuaternion);
  47879. };
  47880. }());
  47881. this.threeScene = threeScene;
  47882. this.splatRenderTarget = null;
  47883. this.renderTargetCopyQuad = null;
  47884. this.renderTargetCopyCamera = null;
  47885. this.meshCursor = null;
  47886. this.focusMarker = null;
  47887. this.controlPlane = null;
  47888. this.debugRoot = null;
  47889. this.secondaryDebugRoot = null;
  47890. }
  47891. updateSplatRenderTargetForRenderDimensions(width, height) {
  47892. this.destroySplatRendertarget();
  47893. this.splatRenderTarget = new THREE$2.WebGLRenderTarget(width, height, {
  47894. format: THREE$2.RGBAFormat,
  47895. stencilBuffer: false,
  47896. depthBuffer: true
  47897. });
  47898. this.splatRenderTarget.depthTexture = new THREE$2.DepthTexture(width, height);
  47899. this.splatRenderTarget.depthTexture.format = THREE$2.DepthFormat;
  47900. this.splatRenderTarget.depthTexture.type = THREE$2.UnsignedIntType;
  47901. }
  47902. destroySplatRendertarget() {
  47903. if (this.splatRenderTarget) {
  47904. this.splatRenderTarget = null;
  47905. }
  47906. }
  47907. setupRenderTargetCopyObjects() {
  47908. var uniforms = {
  47909. 'sourceColorTexture': {
  47910. 'type': 't',
  47911. 'value': null
  47912. },
  47913. 'sourceDepthTexture': {
  47914. 'type': 't',
  47915. 'value': null
  47916. }
  47917. };
  47918. var renderTargetCopyMaterial = new THREE$2.ShaderMaterial({
  47919. vertexShader: "\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = vec4( position.xy, 0.0, 1.0 ); \n }\n ",
  47920. fragmentShader: "\n #include <common>\n #include <packing>\n varying vec2 vUv;\n uniform sampler2D sourceColorTexture;\n uniform sampler2D sourceDepthTexture;\n void main() {\n vec4 color = texture2D(sourceColorTexture, vUv);\n float fragDepth = texture2D(sourceDepthTexture, vUv).x;\n gl_FragDepth = fragDepth;\n gl_FragColor = vec4(color.rgb, color.a * 2.0);\n }\n ",
  47921. uniforms: uniforms,
  47922. depthWrite: false,
  47923. depthTest: false,
  47924. transparent: true,
  47925. blending: THREE$2.CustomBlending,
  47926. blendSrc: THREE$2.SrcAlphaFactor,
  47927. blendSrcAlpha: THREE$2.SrcAlphaFactor,
  47928. blendDst: THREE$2.OneMinusSrcAlphaFactor,
  47929. blendDstAlpha: THREE$2.OneMinusSrcAlphaFactor
  47930. });
  47931. renderTargetCopyMaterial.extensions.fragDepth = true;
  47932. this.renderTargetCopyQuad = new THREE$2.Mesh(new THREE$2.PlaneGeometry(2, 2), renderTargetCopyMaterial);
  47933. this.renderTargetCopyCamera = new THREE$2.OrthographicCamera(-1, 1, 1, -1, 0, 1);
  47934. }
  47935. destroyRenderTargetCopyObjects() {
  47936. if (this.renderTargetCopyQuad) {
  47937. disposeAllMeshes(this.renderTargetCopyQuad);
  47938. this.renderTargetCopyQuad = null;
  47939. }
  47940. }
  47941. setupMeshCursor() {
  47942. if (!this.meshCursor) {
  47943. var coneGeometry = new THREE$2.ConeGeometry(0.5, 1.5, 32);
  47944. var coneMaterial = new THREE$2.MeshBasicMaterial({
  47945. color: 0xFFFFFF
  47946. });
  47947. var downArrow = new THREE$2.Mesh(coneGeometry, coneMaterial);
  47948. downArrow.rotation.set(0, 0, Math.PI);
  47949. downArrow.position.set(0, 1, 0);
  47950. var upArrow = new THREE$2.Mesh(coneGeometry, coneMaterial);
  47951. upArrow.position.set(0, -1, 0);
  47952. var leftArrow = new THREE$2.Mesh(coneGeometry, coneMaterial);
  47953. leftArrow.rotation.set(0, 0, Math.PI / 2.0);
  47954. leftArrow.position.set(1, 0, 0);
  47955. var rightArrow = new THREE$2.Mesh(coneGeometry, coneMaterial);
  47956. rightArrow.rotation.set(0, 0, -Math.PI / 2.0);
  47957. rightArrow.position.set(-1, 0, 0);
  47958. this.meshCursor = new THREE$2.Object3D();
  47959. this.meshCursor.add(downArrow);
  47960. this.meshCursor.add(upArrow);
  47961. this.meshCursor.add(leftArrow);
  47962. this.meshCursor.add(rightArrow);
  47963. this.meshCursor.scale.set(0.1, 0.1, 0.1);
  47964. this.threeScene.add(this.meshCursor);
  47965. this.meshCursor.visible = false;
  47966. }
  47967. }
  47968. destroyMeshCursor() {
  47969. if (this.meshCursor) {
  47970. disposeAllMeshes(this.meshCursor);
  47971. this.threeScene.remove(this.meshCursor);
  47972. this.meshCursor = null;
  47973. }
  47974. }
  47975. setMeshCursorVisibility(visible) {
  47976. this.meshCursor.visible = visible;
  47977. }
  47978. getMeschCursorVisibility() {
  47979. return this.meshCursor.visible;
  47980. }
  47981. setMeshCursorPosition(position) {
  47982. this.meshCursor.position.copy(position);
  47983. }
  47984. positionAndOrientMeshCursor(position, camera) {
  47985. this.meshCursor.position.copy(position);
  47986. this.meshCursor.up.copy(camera.up);
  47987. this.meshCursor.lookAt(camera.position);
  47988. }
  47989. setupFocusMarker() {
  47990. if (!this.focusMarker) {
  47991. var sphereGeometry = new THREE$2.SphereGeometry(.5, 32, 32);
  47992. var focusMarkerMaterial = SceneHelper.buildFocusMarkerMaterial();
  47993. focusMarkerMaterial.depthTest = false;
  47994. focusMarkerMaterial.depthWrite = false;
  47995. focusMarkerMaterial.transparent = true;
  47996. this.focusMarker = new THREE$2.Mesh(sphereGeometry, focusMarkerMaterial);
  47997. }
  47998. }
  47999. destroyFocusMarker() {
  48000. if (this.focusMarker) {
  48001. disposeAllMeshes(this.focusMarker);
  48002. this.focusMarker = null;
  48003. }
  48004. }
  48005. setFocusMarkerVisibility(visible) {
  48006. this.focusMarker.visible = visible;
  48007. }
  48008. setFocusMarkerOpacity(opacity) {
  48009. this.focusMarker.material.uniforms.opacity.value = opacity;
  48010. this.focusMarker.material.uniformsNeedUpdate = true;
  48011. }
  48012. getFocusMarkerOpacity() {
  48013. return this.focusMarker.material.uniforms.opacity.value;
  48014. }
  48015. setupControlPlane() {
  48016. if (!this.controlPlane) {
  48017. var planeGeometry = new THREE$2.PlaneGeometry(1, 1);
  48018. planeGeometry.rotateX(-Math.PI / 2);
  48019. var planeMaterial = new THREE$2.MeshBasicMaterial({
  48020. color: 0xffffff
  48021. });
  48022. planeMaterial.transparent = true;
  48023. planeMaterial.opacity = 0.6;
  48024. planeMaterial.depthTest = false;
  48025. planeMaterial.depthWrite = false;
  48026. planeMaterial.side = THREE$2.DoubleSide;
  48027. var planeMesh = new THREE$2.Mesh(planeGeometry, planeMaterial);
  48028. var arrowDir = new THREE$2.Vector3(0, 1, 0);
  48029. arrowDir.normalize();
  48030. var arrowOrigin = new THREE$2.Vector3(0, 0, 0);
  48031. var arrowLength = 0.5;
  48032. var arrowRadius = 0.01;
  48033. var arrowColor = 0x00dd00;
  48034. var arrowHelper = new ArrowHelper$1(arrowDir, arrowOrigin, arrowLength, arrowRadius, arrowColor, 0.1, 0.03);
  48035. this.controlPlane = new THREE$2.Object3D();
  48036. this.controlPlane.add(planeMesh);
  48037. this.controlPlane.add(arrowHelper);
  48038. }
  48039. }
  48040. destroyControlPlane() {
  48041. if (this.controlPlane) {
  48042. disposeAllMeshes(this.controlPlane);
  48043. this.controlPlane = null;
  48044. }
  48045. }
  48046. setControlPlaneVisibility(visible) {
  48047. this.controlPlane.visible = visible;
  48048. }
  48049. addDebugMeshes() {
  48050. this.debugRoot = this.createDebugMeshes();
  48051. this.secondaryDebugRoot = this.createSecondaryDebugMeshes();
  48052. this.threeScene.add(this.debugRoot);
  48053. this.threeScene.add(this.secondaryDebugRoot);
  48054. }
  48055. destroyDebugMeshes() {
  48056. for (var debugRoot of [this.debugRoot, this.secondaryDebugRoot]) {
  48057. if (debugRoot) {
  48058. disposeAllMeshes(debugRoot);
  48059. this.threeScene.remove(debugRoot);
  48060. }
  48061. }
  48062. this.debugRoot = null;
  48063. this.secondaryDebugRoot = null;
  48064. }
  48065. createDebugMeshes(renderOrder) {
  48066. var sphereGeometry = new THREE$2.SphereGeometry(1, 32, 32);
  48067. var debugMeshRoot = new THREE$2.Object3D();
  48068. var createMesh = (color, position) => {
  48069. var sphereMesh = new THREE$2.Mesh(sphereGeometry, SceneHelper.buildDebugMaterial(color));
  48070. sphereMesh.renderOrder = renderOrder;
  48071. debugMeshRoot.add(sphereMesh);
  48072. sphereMesh.position.fromArray(position);
  48073. };
  48074. createMesh(0xff0000, [-50, 0, 0]);
  48075. createMesh(0xff0000, [50, 0, 0]);
  48076. createMesh(0x00ff00, [0, 0, -50]);
  48077. createMesh(0x00ff00, [0, 0, 50]);
  48078. createMesh(0xffaa00, [5, 0, 5]);
  48079. return debugMeshRoot;
  48080. }
  48081. createSecondaryDebugMeshes(renderOrder) {
  48082. var boxGeometry = new THREE$2.BoxGeometry(3, 3, 3);
  48083. var debugMeshRoot = new THREE$2.Object3D();
  48084. var boxColor = 0xBBBBBB;
  48085. var createMesh = position => {
  48086. var boxMesh = new THREE$2.Mesh(boxGeometry, SceneHelper.buildDebugMaterial(boxColor));
  48087. boxMesh.renderOrder = renderOrder;
  48088. debugMeshRoot.add(boxMesh);
  48089. boxMesh.position.fromArray(position);
  48090. };
  48091. var separation = 10;
  48092. createMesh([-separation, 0, -separation]);
  48093. createMesh([-separation, 0, separation]);
  48094. createMesh([separation, 0, -separation]);
  48095. createMesh([separation, 0, separation]);
  48096. return debugMeshRoot;
  48097. }
  48098. static buildDebugMaterial(color) {
  48099. var vertexShaderSource = "\n #include <common>\n varying float ndcDepth;\n\n void main() {\n gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position.xyz, 1.0);\n ndcDepth = gl_Position.z / gl_Position.w;\n gl_Position.x = gl_Position.x / gl_Position.w;\n gl_Position.y = gl_Position.y / gl_Position.w;\n gl_Position.z = 0.0;\n gl_Position.w = 1.0;\n \n }\n ";
  48100. var fragmentShaderSource = "\n #include <common>\n uniform vec3 color;\n varying float ndcDepth;\n void main() {\n gl_FragDepth = (ndcDepth + 1.0) / 2.0;\n gl_FragColor = vec4(color.rgb, 0.0);\n }\n ";
  48101. var uniforms = {
  48102. 'color': {
  48103. 'type': 'v3',
  48104. 'value': new THREE$2.Color(color)
  48105. }
  48106. };
  48107. var material = new THREE$2.ShaderMaterial({
  48108. uniforms: uniforms,
  48109. vertexShader: vertexShaderSource,
  48110. fragmentShader: fragmentShaderSource,
  48111. transparent: false,
  48112. depthTest: true,
  48113. depthWrite: true,
  48114. side: THREE$2.FrontSide
  48115. });
  48116. material.extensions.fragDepth = true;
  48117. return material;
  48118. }
  48119. static buildFocusMarkerMaterial(color) {
  48120. var vertexShaderSource = "\n #include <common>\n\n uniform vec2 viewport;\n uniform vec3 realFocusPosition;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n float radius = 0.01;\n\n vec4 viewPosition = modelViewMatrix * vec4(position.xyz, 1.0);\n vec4 viewCenter = modelViewMatrix * vec4(0.0, 0.0, 0.0, 1.0);\n\n vec4 viewFocusPosition = modelViewMatrix * vec4(realFocusPosition, 1.0);\n\n ndcPosition = projectionMatrix * viewPosition;\n ndcPosition = ndcPosition * vec4(1.0 / ndcPosition.w);\n ndcCenter = projectionMatrix * viewCenter;\n ndcCenter = ndcCenter * vec4(1.0 / ndcCenter.w);\n\n ndcFocusPosition = projectionMatrix * viewFocusPosition;\n ndcFocusPosition = ndcFocusPosition * vec4(1.0 / ndcFocusPosition.w);\n\n gl_Position = projectionMatrix * viewPosition;\n\n }\n ";
  48121. var fragmentShaderSource = "\n #include <common>\n uniform vec3 color;\n uniform vec2 viewport;\n uniform float opacity;\n\n varying vec4 ndcPosition;\n varying vec4 ndcCenter;\n varying vec4 ndcFocusPosition;\n\n void main() {\n vec2 screenPosition = vec2(ndcPosition) * viewport;\n vec2 screenCenter = vec2(ndcCenter) * viewport;\n\n vec2 screenVec = screenPosition - screenCenter;\n\n float projectedRadius = length(screenVec);\n\n float lineWidth = 0.0005 * viewport.y;\n float aaRange = 0.0025 * viewport.y;\n float radius = 0.06 * viewport.y;\n float radDiff = abs(projectedRadius - radius) - lineWidth;\n float alpha = 1.0 - clamp(radDiff / 5.0, 0.0, 1.0); \n\n gl_FragColor = vec4(color.rgb, alpha * opacity);\n }\n ";
  48122. var uniforms = {
  48123. 'color': {
  48124. 'type': 'v3',
  48125. 'value': new THREE$2.Color(color)
  48126. },
  48127. 'realFocusPosition': {
  48128. 'type': 'v3',
  48129. 'value': new THREE$2.Vector3()
  48130. },
  48131. 'viewport': {
  48132. 'type': 'v2',
  48133. 'value': new THREE$2.Vector2()
  48134. },
  48135. 'opacity': {
  48136. 'value': 0.0
  48137. }
  48138. };
  48139. var material = new THREE$2.ShaderMaterial({
  48140. uniforms: uniforms,
  48141. vertexShader: vertexShaderSource,
  48142. fragmentShader: fragmentShaderSource,
  48143. transparent: true,
  48144. depthTest: false,
  48145. depthWrite: false,
  48146. side: THREE$2.FrontSide
  48147. });
  48148. return material;
  48149. }
  48150. dispose() {
  48151. this.destroyMeshCursor();
  48152. this.destroyFocusMarker();
  48153. this.destroyDebugMeshes();
  48154. this.destroyControlPlane();
  48155. this.destroyRenderTargetCopyObjects();
  48156. this.destroySplatRendertarget();
  48157. }
  48158. }
  48159. var VectorRight = new THREE$2.Vector3(1, 0, 0);
  48160. var VectorUp = new THREE$2.Vector3(0, 1, 0);
  48161. var VectorBackward = new THREE$2.Vector3(0, 0, 1);
  48162. class Ray$1 {
  48163. constructor() {
  48164. var origin = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new THREE$2.Vector3();
  48165. var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE$2.Vector3();
  48166. _defineProperty(this, "intersectBox", function () {
  48167. var planeIntersectionPoint = new THREE$2.Vector3();
  48168. var planeIntersectionPointArray = [];
  48169. var originArray = [];
  48170. var directionArray = [];
  48171. return function (box, outHit) {
  48172. originArray[0] = this.origin.x;
  48173. originArray[1] = this.origin.y;
  48174. originArray[2] = this.origin.z;
  48175. directionArray[0] = this.direction.x;
  48176. directionArray[1] = this.direction.y;
  48177. directionArray[2] = this.direction.z;
  48178. if (this.boxContainsPoint(box, this.origin, 0.0001)) {
  48179. if (outHit) {
  48180. outHit.origin.copy(this.origin);
  48181. outHit.normal.set(0, 0, 0);
  48182. outHit.distance = -1;
  48183. }
  48184. return true;
  48185. }
  48186. for (var i = 0; i < 3; i++) {
  48187. if (directionArray[i] == 0.0) continue;
  48188. var hitNormal = i == 0 ? VectorRight : i == 1 ? VectorUp : VectorBackward;
  48189. var extremeVec = directionArray[i] < 0 ? box.max : box.min;
  48190. var multiplier = -Math.sign(directionArray[i]);
  48191. planeIntersectionPointArray[0] = i == 0 ? extremeVec.x : i == 1 ? extremeVec.y : extremeVec.z;
  48192. var toSide = planeIntersectionPointArray[0] - originArray[i];
  48193. if (toSide * multiplier < 0) {
  48194. var idx1 = (i + 1) % 3;
  48195. var idx2 = (i + 2) % 3;
  48196. planeIntersectionPointArray[2] = directionArray[idx1] / directionArray[i] * toSide + originArray[idx1];
  48197. planeIntersectionPointArray[1] = directionArray[idx2] / directionArray[i] * toSide + originArray[idx2];
  48198. planeIntersectionPoint.set(planeIntersectionPointArray[i], planeIntersectionPointArray[idx2], planeIntersectionPointArray[idx1]);
  48199. if (this.boxContainsPoint(box, planeIntersectionPoint, 0.0001)) {
  48200. if (outHit) {
  48201. outHit.origin.copy(planeIntersectionPoint);
  48202. outHit.normal.copy(hitNormal).multiplyScalar(multiplier);
  48203. outHit.distance = planeIntersectionPoint.sub(this.origin).length();
  48204. }
  48205. return true;
  48206. }
  48207. }
  48208. }
  48209. return false;
  48210. };
  48211. }());
  48212. _defineProperty(this, "intersectSphere", function () {
  48213. var toSphereCenterVec = new THREE$2.Vector3();
  48214. return function (center, radius, outHit) {
  48215. toSphereCenterVec.copy(center).sub(this.origin);
  48216. var toClosestApproach = toSphereCenterVec.dot(this.direction);
  48217. var toClosestApproachSq = toClosestApproach * toClosestApproach;
  48218. var toSphereCenterSq = toSphereCenterVec.dot(toSphereCenterVec);
  48219. var diffSq = toSphereCenterSq - toClosestApproachSq;
  48220. var radiusSq = radius * radius;
  48221. if (diffSq > radiusSq) return false;
  48222. var thc = Math.sqrt(radiusSq - diffSq);
  48223. var t0 = toClosestApproach - thc;
  48224. var t1 = toClosestApproach + thc;
  48225. if (t1 < 0) return false;
  48226. var t = t0 < 0 ? t1 : t0;
  48227. if (outHit) {
  48228. outHit.origin.copy(this.origin).addScaledVector(this.direction, t);
  48229. outHit.normal.copy(outHit.origin).sub(center).normalize();
  48230. outHit.distance = t;
  48231. }
  48232. return true;
  48233. };
  48234. }());
  48235. this.origin = new THREE$2.Vector3();
  48236. this.direction = new THREE$2.Vector3();
  48237. this.setParameters(origin, direction);
  48238. }
  48239. setParameters(origin, direction) {
  48240. this.origin.copy(origin);
  48241. this.direction.copy(direction).normalize();
  48242. }
  48243. boxContainsPoint(box, point, epsilon) {
  48244. return point.x < box.min.x - epsilon || point.x > box.max.x + epsilon || point.y < box.min.y - epsilon || point.y > box.max.y + epsilon || point.z < box.min.z - epsilon || point.z > box.max.z + epsilon ? false : true;
  48245. }
  48246. }
  48247. class Hit {
  48248. constructor() {
  48249. this.origin = new THREE$2.Vector3();
  48250. this.normal = new THREE$2.Vector3();
  48251. this.distance = 0;
  48252. this.splatIndex = 0;
  48253. }
  48254. set(origin, normal, distance, splatIndex) {
  48255. this.origin.copy(origin);
  48256. this.normal.copy(normal);
  48257. this.distance = distance;
  48258. this.splatIndex = splatIndex;
  48259. }
  48260. clone() {
  48261. var hitClone = new Hit();
  48262. hitClone.origin.copy(this.origin);
  48263. hitClone.normal.copy(this.normal);
  48264. hitClone.distance = this.distance;
  48265. hitClone.splatIndex = this.splatIndex;
  48266. return hitClone;
  48267. }
  48268. }
  48269. class Raycaster$1 {
  48270. constructor(_origin, direction) {
  48271. var raycastAgainstTrueSplatEllipsoid = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  48272. _defineProperty(this, "setFromCameraAndScreenPosition", function () {
  48273. var ndcCoords = new THREE$2.Vector2();
  48274. return function (camera, screenPosition, screenDimensions) {
  48275. ndcCoords.x = screenPosition.x / screenDimensions.x * 2.0 - 1.0;
  48276. ndcCoords.y = (screenDimensions.y - screenPosition.y) / screenDimensions.y * 2.0 - 1.0;
  48277. if (camera.isPerspectiveCamera) {
  48278. this.ray.origin.setFromMatrixPosition(camera.matrixWorld);
  48279. this.ray.direction.set(ndcCoords.x, ndcCoords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();
  48280. this.camera = camera;
  48281. } else if (camera.isOrthographicCamera) {
  48282. this.ray.origin.set(ndcCoords.x, ndcCoords.y, (camera.near + camera.far) / (camera.near - camera.far)).unproject(camera);
  48283. this.ray.direction.set(0, 0, -1).transformDirection(camera.matrixWorld);
  48284. this.camera = camera;
  48285. } else {
  48286. throw new Error('Raycaster::setFromCameraAndScreenPosition() -> Unsupported camera type');
  48287. }
  48288. };
  48289. }());
  48290. _defineProperty(this, "intersectSplatMesh", function () {
  48291. var toLocal = new THREE$2.Matrix4();
  48292. var fromLocal = new THREE$2.Matrix4();
  48293. var sceneTransform = new THREE$2.Matrix4();
  48294. var localRay = new Ray$1();
  48295. var tempPoint = new THREE$2.Vector3();
  48296. return function (splatMesh) {
  48297. var outHits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  48298. var splatTree = splatMesh.getSplatTree();
  48299. if (!splatTree) return;
  48300. for (var s = 0; s < splatTree.subTrees.length; s++) {
  48301. var subTree = splatTree.subTrees[s];
  48302. fromLocal.copy(splatMesh.matrixWorld);
  48303. if (splatMesh.dynamicMode) {
  48304. splatMesh.getSceneTransform(s, sceneTransform);
  48305. fromLocal.multiply(sceneTransform);
  48306. }
  48307. toLocal.copy(fromLocal).invert();
  48308. //直接在ray上乘上模型变换
  48309. localRay.origin.copy(this.ray.origin).applyMatrix4(toLocal);
  48310. localRay.direction.copy(this.ray.origin).add(this.ray.direction);
  48311. localRay.direction.applyMatrix4(toLocal).sub(localRay.origin).normalize();
  48312. var outHitsForSubTree = [];
  48313. if (subTree.rootNode) {
  48314. this.castRayAtSplatTreeNode(localRay, splatTree, subTree.rootNode, outHitsForSubTree);
  48315. }
  48316. outHitsForSubTree.forEach(hit => {
  48317. hit.origin.applyMatrix4(fromLocal);
  48318. hit.normal.applyMatrix4(fromLocal).normalize();
  48319. hit.distance = tempPoint.copy(hit.origin).sub(this.ray.origin).length();
  48320. });
  48321. outHits.push(...outHitsForSubTree);
  48322. }
  48323. outHits.sort((a, b) => {
  48324. if (a.distance > b.distance) return 1;else return -1;
  48325. });
  48326. return outHits;
  48327. };
  48328. }());
  48329. _defineProperty(this, "castRayAtSplatTreeNode", function () {
  48330. var tempColor = new THREE$2.Vector4();
  48331. var tempCenter = new THREE$2.Vector3();
  48332. var tempScale = new THREE$2.Vector3();
  48333. var tempRotation = new THREE$2.Quaternion();
  48334. var tempHit = new Hit();
  48335. var scaleEpsilon = 0.0000001;
  48336. var origin = new THREE$2.Vector3(0, 0, 0);
  48337. var uniformScaleMatrix = new THREE$2.Matrix4();
  48338. var scaleMatrix = new THREE$2.Matrix4();
  48339. var rotationMatrix = new THREE$2.Matrix4();
  48340. var toSphereSpace = new THREE$2.Matrix4();
  48341. var fromSphereSpace = new THREE$2.Matrix4();
  48342. var tempRay = new Ray$1();
  48343. return function (ray, splatTree, node) {
  48344. var outHits = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : [];
  48345. if (!ray.intersectBox(node.boundingBox)) {
  48346. return;
  48347. }
  48348. if (node.data && node.data.indexes && node.data.indexes.length > 0) {
  48349. for (var i = 0; i < node.data.indexes.length; i++) {
  48350. var splatGlobalIndex = node.data.indexes[i];
  48351. splatTree.splatMesh.getSplatColor(splatGlobalIndex, tempColor);
  48352. splatTree.splatMesh.getSplatCenter(splatGlobalIndex, tempCenter);
  48353. splatTree.splatMesh.getSplatScaleAndRotation(splatGlobalIndex, tempScale, tempRotation);
  48354. if (tempScale.x <= scaleEpsilon || tempScale.y <= scaleEpsilon || tempScale.z <= scaleEpsilon) {
  48355. continue;
  48356. }
  48357. if (!this.raycastAgainstTrueSplatEllipsoid) {
  48358. //是只需得到近似值的意思吗
  48359. var radius = (tempScale.x + tempScale.y + tempScale.z) / 3; //椭球的平均半径
  48360. if (ray.intersectSphere(tempCenter, radius, tempHit)) {
  48361. //没细看,是pick球上哪个点?
  48362. var hitClone = tempHit.clone();
  48363. hitClone.splatIndex = splatGlobalIndex;
  48364. outHits.push(hitClone);
  48365. }
  48366. } else {
  48367. scaleMatrix.makeScale(tempScale.x, tempScale.y, tempScale.z);
  48368. rotationMatrix.makeRotationFromQuaternion(tempRotation);
  48369. var uniformScale = Math.log10(tempColor.w) * 2.0;
  48370. uniformScaleMatrix.makeScale(uniformScale, uniformScale, uniformScale);
  48371. fromSphereSpace.copy(uniformScaleMatrix).multiply(rotationMatrix).multiply(scaleMatrix);
  48372. toSphereSpace.copy(fromSphereSpace).invert();
  48373. tempRay.origin.copy(ray.origin).sub(tempCenter).applyMatrix4(toSphereSpace);
  48374. tempRay.direction.copy(ray.origin).add(ray.direction).sub(tempCenter);
  48375. tempRay.direction.applyMatrix4(toSphereSpace).sub(tempRay.origin).normalize();
  48376. if (tempRay.intersectSphere(origin, 1.0, tempHit)) {
  48377. var _hitClone = tempHit.clone();
  48378. _hitClone.splatIndex = splatGlobalIndex;
  48379. _hitClone.origin.applyMatrix4(fromSphereSpace).add(tempCenter);
  48380. outHits.push(_hitClone);
  48381. }
  48382. }
  48383. }
  48384. }
  48385. if (node.children && node.children.length > 0) {
  48386. for (var child of node.children) {
  48387. this.castRayAtSplatTreeNode(ray, splatTree, child, outHits);
  48388. }
  48389. }
  48390. return outHits;
  48391. };
  48392. }());
  48393. this.ray = new Ray$1(_origin, direction);
  48394. this.raycastAgainstTrueSplatEllipsoid = raycastAgainstTrueSplatEllipsoid;
  48395. }
  48396. }
  48397. /**
  48398. * SplatScene: Descriptor for a single splat scene managed by an instance of SplatMesh.
  48399. */
  48400. class SplatScene {
  48401. constructor(splatBuffer) {
  48402. var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new THREE$2.Vector3();
  48403. var quaternion = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : new THREE$2.Quaternion();
  48404. var scale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : new THREE$2.Vector3(1, 1, 1);
  48405. var minimumAlpha = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1;
  48406. this.splatBuffer = splatBuffer;
  48407. this.position = position.clone();
  48408. this.quaternion = quaternion.clone();
  48409. this.scale = scale.clone();
  48410. this.transform = new THREE$2.Matrix4();
  48411. this.minimumAlpha = minimumAlpha;
  48412. this.updateTransform();
  48413. }
  48414. copyTransformData(otherScene) {
  48415. this.position.copy(otherScene.position);
  48416. this.quaternion.copy(otherScene.quaternion);
  48417. this.scale.copy(otherScene.scale);
  48418. this.transform.copy(otherScene.transform);
  48419. }
  48420. updateTransform() {
  48421. this.transform.compose(this.position, this.quaternion, this.scale);
  48422. }
  48423. }
  48424. /*
  48425. 将点云中的点按照八叉树的方式一层层等分存储。
  48426. 每个子节点自动向下分割,直到层数到达最大,或者其点数量小于最大容纳点数为止。
  48427. */
  48428. class SplatTreeNode {
  48429. constructor(min, max, depth, id) {
  48430. this.min = new THREE$2.Vector3().copy(min);
  48431. this.max = new THREE$2.Vector3().copy(max);
  48432. this.boundingBox = new THREE$2.Box3(this.min, this.max);
  48433. this.center = new THREE$2.Vector3().copy(this.max).sub(this.min).multiplyScalar(0.5).add(this.min);
  48434. this.depth = depth;
  48435. this.children = [];
  48436. this.data = null;
  48437. this.id = id || SplatTreeNode.idGen++;
  48438. }
  48439. }
  48440. _defineProperty(SplatTreeNode, "idGen", 0);
  48441. class SplatSubTree {
  48442. constructor(maxDepth, maxCentersPerNode) {
  48443. this.maxDepth = maxDepth;
  48444. this.maxCentersPerNode = maxCentersPerNode;
  48445. this.sceneDimensions = new THREE$2.Vector3();
  48446. this.sceneMin = new THREE$2.Vector3();
  48447. this.sceneMax = new THREE$2.Vector3();
  48448. this.rootNode = null;
  48449. this.nodesWithIndexes = [];
  48450. this.splatMesh = null;
  48451. }
  48452. static convertWorkerSubTreeNode(workerSubTreeNode) {
  48453. var minVector = new THREE$2.Vector3().fromArray(workerSubTreeNode.min);
  48454. var maxVector = new THREE$2.Vector3().fromArray(workerSubTreeNode.max);
  48455. var convertedNode = new SplatTreeNode(minVector, maxVector, workerSubTreeNode.depth, workerSubTreeNode.id);
  48456. if (workerSubTreeNode.data.indexes) {
  48457. convertedNode.data = {
  48458. 'indexes': []
  48459. };
  48460. for (var index of workerSubTreeNode.data.indexes) {
  48461. convertedNode.data.indexes.push(index);
  48462. }
  48463. }
  48464. if (workerSubTreeNode.children) {
  48465. for (var child of workerSubTreeNode.children) {
  48466. convertedNode.children.push(SplatSubTree.convertWorkerSubTreeNode(child));
  48467. }
  48468. }
  48469. return convertedNode;
  48470. }
  48471. static convertWorkerSubTree(workerSubTree, splatMesh) {
  48472. var convertedSubTree = new SplatSubTree(workerSubTree.maxDepth, workerSubTree.maxCentersPerNode);
  48473. convertedSubTree.sceneMin = new THREE$2.Vector3().fromArray(workerSubTree.sceneMin);
  48474. convertedSubTree.sceneMax = new THREE$2.Vector3().fromArray(workerSubTree.sceneMax);
  48475. convertedSubTree.splatMesh = splatMesh;
  48476. convertedSubTree.rootNode = SplatSubTree.convertWorkerSubTreeNode(workerSubTree.rootNode);
  48477. var visitLeavesFromNode = (node, visitFunc) => {
  48478. if (node.children.length === 0) visitFunc(node);
  48479. for (var child of node.children) {
  48480. visitLeavesFromNode(child, visitFunc);
  48481. }
  48482. };
  48483. convertedSubTree.nodesWithIndexes = [];
  48484. visitLeavesFromNode(convertedSubTree.rootNode, node => {
  48485. if (node.data && node.data.indexes && node.data.indexes.length > 0) {
  48486. convertedSubTree.nodesWithIndexes.push(node);
  48487. }
  48488. });
  48489. return convertedSubTree;
  48490. }
  48491. }
  48492. function createSplatTreeWorker(self) {
  48493. var WorkerSplatTreeNodeIDGen = 0;
  48494. class WorkerBox3 {
  48495. constructor(min, max) {
  48496. this.min = [min[0], min[1], min[2]];
  48497. this.max = [max[0], max[1], max[2]];
  48498. }
  48499. containsPoint(point) {
  48500. return point[0] >= this.min[0] && point[0] <= this.max[0] && point[1] >= this.min[1] && point[1] <= this.max[1] && point[2] >= this.min[2] && point[2] <= this.max[2];
  48501. }
  48502. }
  48503. class WorkerSplatSubTree {
  48504. constructor(maxDepth, maxCentersPerNode) {
  48505. this.maxDepth = maxDepth;
  48506. this.maxCentersPerNode = maxCentersPerNode;
  48507. this.sceneDimensions = [];
  48508. this.sceneMin = [];
  48509. this.sceneMax = [];
  48510. this.rootNode = null;
  48511. this.addedIndexes = {};
  48512. this.nodesWithIndexes = [];
  48513. this.splatMesh = null;
  48514. this.disposed = false;
  48515. }
  48516. }
  48517. class WorkerSplatTreeNode {
  48518. constructor(min, max, depth, id) {
  48519. this.min = [min[0], min[1], min[2]];
  48520. this.max = [max[0], max[1], max[2]];
  48521. this.center = [(max[0] - min[0]) * 0.5 + min[0], (max[1] - min[1]) * 0.5 + min[1], (max[2] - min[2]) * 0.5 + min[2]];
  48522. this.depth = depth;
  48523. this.children = [];
  48524. this.data = null;
  48525. this.id = id || WorkerSplatTreeNodeIDGen++;
  48526. }
  48527. }
  48528. processSplatTreeNode = function (_processSplatTreeNode) {
  48529. function processSplatTreeNode(_x2, _x3, _x4, _x5) {
  48530. return _processSplatTreeNode.apply(this, arguments);
  48531. }
  48532. processSplatTreeNode.toString = function () {
  48533. return _processSplatTreeNode.toString();
  48534. };
  48535. return processSplatTreeNode;
  48536. }(function (tree, node, indexToCenter, sceneCenters) {
  48537. var splatCount = node.data.indexes.length;
  48538. if (splatCount < tree.maxCentersPerNode || node.depth > tree.maxDepth) {
  48539. //该节点停止分割
  48540. var newIndexes = [];
  48541. for (var i = 0; i < node.data.indexes.length; i++) {
  48542. if (!tree.addedIndexes[node.data.indexes[i]]) {
  48543. newIndexes.push(node.data.indexes[i]);
  48544. tree.addedIndexes[node.data.indexes[i]] = true;
  48545. }
  48546. }
  48547. node.data.indexes = newIndexes;
  48548. node.data.indexes.sort((a, b) => {
  48549. if (a > b) return 1;else return -1;
  48550. });
  48551. tree.nodesWithIndexes.push(node);
  48552. return;
  48553. }
  48554. var nodeDimensions = [node.max[0] - node.min[0], node.max[1] - node.min[1], node.max[2] - node.min[2]];
  48555. var halfDimensions = [nodeDimensions[0] * 0.5, nodeDimensions[1] * 0.5, nodeDimensions[2] * 0.5];
  48556. var nodeCenter = [node.min[0] + halfDimensions[0], node.min[1] + halfDimensions[1], node.min[2] + halfDimensions[2]];
  48557. var childrenBounds = [
  48558. //分割成八块
  48559. // top section, clockwise from upper-left (looking from above, +Y)
  48560. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1], nodeCenter[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]), new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1], nodeCenter[2]], [nodeCenter[0], nodeCenter[1] + halfDimensions[1], nodeCenter[2] + halfDimensions[2]]),
  48561. // bottom section, clockwise from lower-left (looking from above, +Y)
  48562. new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0], nodeCenter[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2] - halfDimensions[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2]]), new WorkerBox3([nodeCenter[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]], [nodeCenter[0] + halfDimensions[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]]), new WorkerBox3([nodeCenter[0] - halfDimensions[0], nodeCenter[1] - halfDimensions[1], nodeCenter[2]], [nodeCenter[0], nodeCenter[1], nodeCenter[2] + halfDimensions[2]])];
  48563. var splatCounts = [];
  48564. var baseIndexes = [];
  48565. for (var _i10 = 0; _i10 < childrenBounds.length; _i10++) {
  48566. splatCounts[_i10] = 0;
  48567. baseIndexes[_i10] = [];
  48568. }
  48569. var center = [0, 0, 0];
  48570. for (var _i11 = 0; _i11 < splatCount; _i11++) {
  48571. //查找每一块包含的index
  48572. var splatGlobalIndex = node.data.indexes[_i11];
  48573. var centerBase = indexToCenter[splatGlobalIndex];
  48574. center[0] = sceneCenters[centerBase];
  48575. center[1] = sceneCenters[centerBase + 1];
  48576. center[2] = sceneCenters[centerBase + 2];
  48577. for (var j = 0; j < childrenBounds.length; j++) {
  48578. if (childrenBounds[j].containsPoint(center)) {
  48579. splatCounts[j]++;
  48580. baseIndexes[j].push(splatGlobalIndex);
  48581. break; //xzw!!!! add 防止ply转的如果都是000点,就会每块都有然后不停分割下去
  48582. }
  48583. }
  48584. }
  48585. for (var _i12 = 0; _i12 < childrenBounds.length; _i12++) {
  48586. var childNode = new WorkerSplatTreeNode(childrenBounds[_i12].min, childrenBounds[_i12].max, node.depth + 1); //创建子节点
  48587. childNode.data = {
  48588. 'indexes': baseIndexes[_i12]
  48589. };
  48590. node.children.push(childNode);
  48591. }
  48592. node.data = {}; //清空自身index
  48593. for (var child of node.children) {
  48594. processSplatTreeNode(tree, child, indexToCenter, sceneCenters); //继续分割
  48595. }
  48596. return;
  48597. });
  48598. var buildSubTree = (sceneCenters, maxDepth, maxCentersPerNode) => {
  48599. var sceneMin = [0, 0, 0];
  48600. var sceneMax = [0, 0, 0];
  48601. var indexes = [];
  48602. var centerCount = Math.floor(sceneCenters.length / 4);
  48603. for (var i = 0; i < centerCount; i++) {
  48604. var base = i * 4;
  48605. var x = sceneCenters[base];
  48606. var y = sceneCenters[base + 1];
  48607. var z = sceneCenters[base + 2];
  48608. var index = Math.round(sceneCenters[base + 3]);
  48609. if (i === 0 || x < sceneMin[0]) sceneMin[0] = x;
  48610. if (i === 0 || x > sceneMax[0]) sceneMax[0] = x;
  48611. if (i === 0 || y < sceneMin[1]) sceneMin[1] = y;
  48612. if (i === 0 || y > sceneMax[1]) sceneMax[1] = y;
  48613. if (i === 0 || z < sceneMin[2]) sceneMin[2] = z;
  48614. if (i === 0 || z > sceneMax[2]) sceneMax[2] = z;
  48615. indexes.push(index);
  48616. }
  48617. var subTree = new WorkerSplatSubTree(maxDepth, maxCentersPerNode);
  48618. subTree.sceneMin = sceneMin;
  48619. subTree.sceneMax = sceneMax;
  48620. subTree.rootNode = new WorkerSplatTreeNode(subTree.sceneMin, subTree.sceneMax, 0);
  48621. subTree.rootNode.data = {
  48622. 'indexes': indexes
  48623. };
  48624. return subTree;
  48625. };
  48626. function createSplatTree(allCenters, maxDepth, maxCentersPerNode) {
  48627. var indexToCenter = [];
  48628. for (var sceneCenters of allCenters) {
  48629. var centerCount = Math.floor(sceneCenters.length / 4);
  48630. for (var i = 0; i < centerCount; i++) {
  48631. var base = i * 4;
  48632. var index = Math.round(sceneCenters[base + 3]);
  48633. indexToCenter[index] = base;
  48634. }
  48635. }
  48636. var subTrees = [];
  48637. for (var _sceneCenters of allCenters) {
  48638. var subTree = buildSubTree(_sceneCenters, maxDepth, maxCentersPerNode); //建立树
  48639. subTrees.push(subTree);
  48640. processSplatTreeNode(subTree, subTree.rootNode, indexToCenter, _sceneCenters); //开始分割
  48641. }
  48642. self.postMessage({
  48643. 'subTrees': subTrees
  48644. });
  48645. }
  48646. self.onmessage = e => {
  48647. if (e.data.process) {
  48648. createSplatTree(e.data.process.centers, e.data.process.maxDepth, e.data.process.maxCentersPerNode);
  48649. }
  48650. };
  48651. }
  48652. function workerProcessCenters(splatTreeWorker, centers, transferBuffers, maxDepth, maxCentersPerNode) {
  48653. splatTreeWorker.postMessage({
  48654. 'process': {
  48655. 'centers': centers,
  48656. 'maxDepth': maxDepth,
  48657. 'maxCentersPerNode': maxCentersPerNode
  48658. }
  48659. }, transferBuffers);
  48660. }
  48661. function checkAndCreateWorker() {
  48662. var splatTreeWorker = new Worker(URL.createObjectURL(new Blob(['(', createSplatTreeWorker.toString(), ')(self)'], {
  48663. type: 'application/javascript'
  48664. })));
  48665. return splatTreeWorker;
  48666. }
  48667. /**
  48668. * SplatTree: Octree tailored to splat data from a SplatMesh instance
  48669. */
  48670. class SplatTree {
  48671. constructor(maxDepth, maxCentersPerNode) {
  48672. /**
  48673. * Construct this instance of SplatTree from an instance of SplatMesh.
  48674. *
  48675. * @param {SplatMesh} splatMesh The instance of SplatMesh from which to construct this splat tree.
  48676. * @param {function} filterFunc Optional function to filter out unwanted splats.
  48677. * @param {function} onIndexesUpload Function to be called when the upload of splat centers to the splat tree
  48678. * builder worker starts and finishes.
  48679. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  48680. * the format produced by the splat tree builder worker starts and ends.
  48681. * @return {undefined}
  48682. */
  48683. _defineProperty(this, "processSplatMesh", function (splatMesh) {
  48684. var filterFunc = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : () => true;
  48685. var onIndexesUpload = arguments.length > 2 ? arguments[2] : undefined;
  48686. var onSplatTreeConstruction = arguments.length > 3 ? arguments[3] : undefined;
  48687. if (!this.splatTreeWorker) this.splatTreeWorker = checkAndCreateWorker();
  48688. this.splatMesh = splatMesh;
  48689. this.subTrees = [];
  48690. var center = new THREE$2.Vector3();
  48691. var addCentersForScene = (splatOffset, splatCount) => {
  48692. var sceneCenters = new Float32Array(splatCount * 4);
  48693. var addedCount = 0;
  48694. for (var i = 0; i < splatCount; i++) {
  48695. var globalSplatIndex = i + splatOffset;
  48696. if (filterFunc(globalSplatIndex)) {
  48697. splatMesh.getSplatCenter(globalSplatIndex, center);
  48698. var addBase = addedCount * 4;
  48699. sceneCenters[addBase] = center.x;
  48700. sceneCenters[addBase + 1] = center.y;
  48701. sceneCenters[addBase + 2] = center.z;
  48702. sceneCenters[addBase + 3] = globalSplatIndex;
  48703. addedCount++;
  48704. }
  48705. }
  48706. return sceneCenters;
  48707. };
  48708. return new Promise(resolve => {
  48709. var checkForEarlyExit = () => {
  48710. if (this.disposed) {
  48711. this.diposeSplatTreeWorker();
  48712. resolve();
  48713. return true;
  48714. }
  48715. return false;
  48716. };
  48717. if (onIndexesUpload) onIndexesUpload(false);
  48718. delayedExecute(() => {
  48719. if (checkForEarlyExit()) return;
  48720. var allCenters = [];
  48721. if (splatMesh.dynamicMode) {
  48722. var splatOffset = 0;
  48723. for (var s = 0; s < splatMesh.scenes.length; s++) {
  48724. var scene = splatMesh.getScene(s);
  48725. var splatCount = scene.splatBuffer.getSplatCount();
  48726. var sceneCenters = addCentersForScene(splatOffset, splatCount);
  48727. allCenters.push(sceneCenters);
  48728. splatOffset += splatCount;
  48729. }
  48730. } else {
  48731. var _sceneCenters2 = addCentersForScene(0, splatMesh.getSplatCount());
  48732. allCenters.push(_sceneCenters2);
  48733. }
  48734. this.splatTreeWorker.onmessage = e => {
  48735. if (checkForEarlyExit()) return;
  48736. if (e.data.subTrees) {
  48737. if (onSplatTreeConstruction) onSplatTreeConstruction(false);
  48738. delayedExecute(() => {
  48739. if (checkForEarlyExit()) return;
  48740. for (var workerSubTree of e.data.subTrees) {
  48741. var convertedSubTree = SplatSubTree.convertWorkerSubTree(workerSubTree, splatMesh);
  48742. this.subTrees.push(convertedSubTree);
  48743. }
  48744. this.diposeSplatTreeWorker();
  48745. if (onSplatTreeConstruction) onSplatTreeConstruction(true);
  48746. delayedExecute(() => {
  48747. resolve();
  48748. });
  48749. });
  48750. }
  48751. };
  48752. delayedExecute(() => {
  48753. if (checkForEarlyExit()) return;
  48754. if (onIndexesUpload) onIndexesUpload(true);
  48755. var transferBuffers = allCenters.map(array => array.buffer);
  48756. workerProcessCenters(this.splatTreeWorker, allCenters, transferBuffers, this.maxDepth, this.maxCentersPerNode);
  48757. });
  48758. });
  48759. });
  48760. });
  48761. this.maxDepth = maxDepth;
  48762. this.maxCentersPerNode = maxCentersPerNode;
  48763. this.subTrees = [];
  48764. this.splatMesh = null;
  48765. }
  48766. dispose() {
  48767. this.diposeSplatTreeWorker();
  48768. this.disposed = true;
  48769. }
  48770. diposeSplatTreeWorker() {
  48771. if (this.splatTreeWorker) this.splatTreeWorker.terminate();
  48772. this.splatTreeWorker = null;
  48773. }
  48774. countLeaves() {
  48775. var leafCount = 0;
  48776. this.visitLeaves(() => {
  48777. leafCount++;
  48778. });
  48779. return leafCount;
  48780. }
  48781. visitLeaves(visitFunc) {
  48782. //traverse
  48783. var visitLeavesFromNode = (node, visitFunc) => {
  48784. if (node.children.length === 0) visitFunc(node);
  48785. for (var child of node.children) {
  48786. visitLeavesFromNode(child, visitFunc);
  48787. }
  48788. };
  48789. for (var subTree of this.subTrees) {
  48790. visitLeavesFromNode(subTree.rootNode, visitFunc);
  48791. }
  48792. }
  48793. }
  48794. function WebGLExtensions$1(gl) {
  48795. var extensions = {};
  48796. function getExtension(name) {
  48797. if (extensions[name] !== undefined) {
  48798. return extensions[name];
  48799. }
  48800. var extension;
  48801. switch (name) {
  48802. case 'WEBGL_depth_texture':
  48803. extension = gl.getExtension('WEBGL_depth_texture') || gl.getExtension('MOZ_WEBGL_depth_texture') || gl.getExtension('WEBKIT_WEBGL_depth_texture');
  48804. break;
  48805. case 'EXT_texture_filter_anisotropic':
  48806. extension = gl.getExtension('EXT_texture_filter_anisotropic') || gl.getExtension('MOZ_EXT_texture_filter_anisotropic') || gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic');
  48807. break;
  48808. case 'WEBGL_compressed_texture_s3tc':
  48809. extension = gl.getExtension('WEBGL_compressed_texture_s3tc') || gl.getExtension('MOZ_WEBGL_compressed_texture_s3tc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  48810. break;
  48811. case 'WEBGL_compressed_texture_pvrtc':
  48812. extension = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  48813. break;
  48814. default:
  48815. extension = gl.getExtension(name);
  48816. }
  48817. extensions[name] = extension;
  48818. return extension;
  48819. }
  48820. return {
  48821. has: function has(name) {
  48822. return getExtension(name) !== null;
  48823. },
  48824. init: function init(capabilities) {
  48825. if (capabilities.isWebGL2) {
  48826. getExtension('EXT_color_buffer_float');
  48827. getExtension('WEBGL_clip_cull_distance');
  48828. } else {
  48829. getExtension('WEBGL_depth_texture');
  48830. getExtension('OES_texture_float');
  48831. getExtension('OES_texture_half_float');
  48832. getExtension('OES_texture_half_float_linear');
  48833. getExtension('OES_standard_derivatives');
  48834. getExtension('OES_element_index_uint');
  48835. getExtension('OES_vertex_array_object');
  48836. getExtension('ANGLE_instanced_arrays');
  48837. }
  48838. getExtension('OES_texture_float_linear');
  48839. getExtension('EXT_color_buffer_half_float');
  48840. getExtension('WEBGL_multisampled_render_to_texture');
  48841. },
  48842. get: function get(name) {
  48843. var extension = getExtension(name);
  48844. if (extension === null) {
  48845. console.warn('THREE.WebGLRenderer: ' + name + ' extension not supported.');
  48846. }
  48847. return extension;
  48848. }
  48849. };
  48850. }
  48851. function WebGLCapabilities$1(gl, extensions, parameters) {
  48852. var maxAnisotropy;
  48853. function getMaxAnisotropy() {
  48854. if (maxAnisotropy !== undefined) return maxAnisotropy;
  48855. if (extensions.has('EXT_texture_filter_anisotropic') === true) {
  48856. var extension = extensions.get('EXT_texture_filter_anisotropic');
  48857. maxAnisotropy = gl.getParameter(extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  48858. } else {
  48859. maxAnisotropy = 0;
  48860. }
  48861. return maxAnisotropy;
  48862. }
  48863. function getMaxPrecision(precision) {
  48864. if (precision === 'highp') {
  48865. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT).precision > 0) {
  48866. return 'highp';
  48867. }
  48868. precision = 'mediump';
  48869. }
  48870. if (precision === 'mediump') {
  48871. if (gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT).precision > 0 && gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT).precision > 0) {
  48872. return 'mediump';
  48873. }
  48874. }
  48875. return 'lowp';
  48876. }
  48877. var isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  48878. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  48879. var maxPrecision = getMaxPrecision(precision);
  48880. if (maxPrecision !== precision) {
  48881. console.warn('THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.');
  48882. precision = maxPrecision;
  48883. }
  48884. var drawBuffers = isWebGL2 || extensions.has('WEBGL_draw_buffers');
  48885. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  48886. var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  48887. var maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  48888. var maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
  48889. var maxCubemapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  48890. var maxAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
  48891. var maxVertexUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
  48892. var maxVaryings = gl.getParameter(gl.MAX_VARYING_VECTORS);
  48893. var maxFragmentUniforms = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  48894. var vertexTextures = maxVertexTextures > 0;
  48895. var floatFragmentTextures = isWebGL2 || extensions.has('OES_texture_float');
  48896. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  48897. var maxSamples = isWebGL2 ? gl.getParameter(gl.MAX_SAMPLES) : 0;
  48898. return {
  48899. isWebGL2: isWebGL2,
  48900. drawBuffers: drawBuffers,
  48901. getMaxAnisotropy: getMaxAnisotropy,
  48902. getMaxPrecision: getMaxPrecision,
  48903. precision: precision,
  48904. logarithmicDepthBuffer: logarithmicDepthBuffer,
  48905. maxTextures: maxTextures,
  48906. maxVertexTextures: maxVertexTextures,
  48907. maxTextureSize: maxTextureSize,
  48908. maxCubemapSize: maxCubemapSize,
  48909. maxAttributes: maxAttributes,
  48910. maxVertexUniforms: maxVertexUniforms,
  48911. maxVaryings: maxVaryings,
  48912. maxFragmentUniforms: maxFragmentUniforms,
  48913. vertexTextures: vertexTextures,
  48914. floatFragmentTextures: floatFragmentTextures,
  48915. floatVertexTextures: floatVertexTextures,
  48916. maxSamples: maxSamples
  48917. };
  48918. }
  48919. var SceneRevealMode = {
  48920. Default: 0,
  48921. Gradual: 1,
  48922. Instant: 2
  48923. };
  48924. var LogLevel = {
  48925. None: 0,
  48926. Error: 1,
  48927. Warning: 2,
  48928. Info: 3,
  48929. Debug: 4
  48930. };
  48931. var dummyGeometry = new THREE$2.BufferGeometry();
  48932. var dummyMaterial = new THREE$2.MeshBasicMaterial();
  48933. var COVARIANCES_ELEMENTS_PER_SPLAT = 6;
  48934. var CENTER_COLORS_ELEMENTS_PER_SPLAT = 4;
  48935. var COVARIANCES_ELEMENTS_PER_TEXEL = 4;
  48936. var CENTER_COLORS_ELEMENTS_PER_TEXEL = 4;
  48937. var TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL = 1;
  48938. var SCENE_FADEIN_RATE_FAST = 0.012;
  48939. var SCENE_FADEIN_RATE_GRADUAL = 0.003;
  48940. var VISIBLE_REGION_EXPANSION_DELTA = 1;
  48941. /**
  48942. * SplatMesh: Container for one or more splat scenes, abstracting them into a single unified container for
  48943. * splat data. Additionally contains data structures and code to make the splat data renderable as a Three.js mesh.
  48944. */
  48945. class SplatMesh extends THREE$2.Mesh {
  48946. constructor() {
  48947. var dynamicMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  48948. var halfPrecisionCovariancesOnGPU = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  48949. var devicePixelRatio = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
  48950. var enableDistancesComputationOnGPU = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  48951. var integerBasedDistancesComputation = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  48952. var antialiased = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false;
  48953. var maxScreenSpaceSplatSize = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 2048;
  48954. var logLevel = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : LogLevel.None;
  48955. var sphericalHarmonicsDegree = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0;
  48956. super(dummyGeometry, dummyMaterial);
  48957. // Reference to a Three.js renderer
  48958. /**
  48959. * Build an instance of SplatTree (a specialized octree) for the given splat mesh.
  48960. * @param {Array<number>} minAlphas Array of minimum splat slphas for each scene
  48961. * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree
  48962. * builder worker starts and finishes.
  48963. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  48964. * the format produced by the splat tree builder worker starts and ends.
  48965. * @return {SplatTree}
  48966. */
  48967. _defineProperty(this, "buildSplatTree", function () {
  48968. var minAlphas = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  48969. var onSplatTreeIndexesUpload = arguments.length > 1 ? arguments[1] : undefined;
  48970. var onSplatTreeConstruction = arguments.length > 2 ? arguments[2] : undefined;
  48971. return new Promise(resolve => {
  48972. this.disposeSplatTree();
  48973. // TODO: expose SplatTree constructor parameters (maximumDepth and maxCentersPerNode) so that they can
  48974. // be configured on a per-scene basis
  48975. this.baseSplatTree = new SplatTree(8, 1000);
  48976. var buildStartTime = performance.now();
  48977. var splatColor = new THREE$2.Vector4();
  48978. this.baseSplatTree.processSplatMesh(this, splatIndex => {
  48979. this.getSplatColor(splatIndex, splatColor);
  48980. var sceneIndex = this.getSceneIndexForSplat(splatIndex);
  48981. var minAlpha = minAlphas[sceneIndex] || 1;
  48982. return splatColor.w >= minAlpha;
  48983. }, onSplatTreeIndexesUpload, onSplatTreeConstruction).then(() => {
  48984. var buildTime = performance.now() - buildStartTime;
  48985. if (this.logLevel >= LogLevel.Info) console.log('SplatTree build: ' + buildTime + ' ms');
  48986. if (this.disposed) {
  48987. resolve();
  48988. } else {
  48989. this.splatTree = this.baseSplatTree;
  48990. this.baseSplatTree = null;
  48991. var leavesWithVertices = 0;
  48992. var avgSplatCount = 0;
  48993. var maxSplatCount = 0;
  48994. var nodeCount = 0;
  48995. this.splatTree.visitLeaves(node => {
  48996. var nodeSplatCount = node.data.indexes.length;
  48997. if (nodeSplatCount > 0) {
  48998. avgSplatCount += nodeSplatCount;
  48999. maxSplatCount = Math.max(maxSplatCount, nodeSplatCount);
  49000. nodeCount++;
  49001. leavesWithVertices++;
  49002. }
  49003. });
  49004. if (this.logLevel >= LogLevel.Info) {
  49005. console.log("SplatTree leaves: ".concat(this.splatTree.countLeaves()));
  49006. console.log("SplatTree leaves with splats:".concat(leavesWithVertices));
  49007. avgSplatCount = avgSplatCount / nodeCount;
  49008. console.log("Avg splat count per node: ".concat(avgSplatCount));
  49009. console.log("Total splat count: ".concat(this.getSplatCount()));
  49010. }
  49011. resolve();
  49012. }
  49013. });
  49014. });
  49015. });
  49016. _defineProperty(this, "updateUniforms", function () {
  49017. var viewport = new THREE$2.Vector2();
  49018. return function (renderDimensions, cameraFocalLengthX, cameraFocalLengthY, orthographicMode, orthographicZoom, inverseFocalAdjustment) {
  49019. var splatCount = this.getSplatCount();
  49020. if (splatCount > 0) {
  49021. viewport.set(renderDimensions.x * this.devicePixelRatio, renderDimensions.y * this.devicePixelRatio);
  49022. this.material.uniforms.viewport.value.copy(viewport);
  49023. this.material.uniforms.basisViewport.value.set(1.0 / viewport.x, 1.0 / viewport.y);
  49024. this.material.uniforms.focal.value.set(cameraFocalLengthX, cameraFocalLengthY);
  49025. this.material.uniforms.orthographicMode.value = orthographicMode ? 1 : 0;
  49026. this.material.uniforms.orthoZoom.value = orthographicZoom;
  49027. this.material.uniforms.inverseFocalAdjustment.value = inverseFocalAdjustment;
  49028. if (this.dynamicMode) {
  49029. for (var i = 0; i < this.scenes.length; i++) {
  49030. this.material.uniforms.transforms.value[i].copy(this.getScene(i).transform);
  49031. }
  49032. }
  49033. this.material.uniformsNeedUpdate = true;
  49034. }
  49035. };
  49036. }());
  49037. _defineProperty(this, "setupDistancesComputationTransformFeedback", function () {
  49038. var currentMaxSplatCount;
  49039. return function () {
  49040. var maxSplatCount = this.getMaxSplatCount();
  49041. if (!this.renderer) return;
  49042. var rebuildGPUObjects = this.lastRenderer !== this.renderer;
  49043. var rebuildBuffers = currentMaxSplatCount !== maxSplatCount;
  49044. if (!rebuildGPUObjects && !rebuildBuffers) return;
  49045. if (rebuildGPUObjects) {
  49046. this.disposeDistancesComputationGPUResources();
  49047. } else if (rebuildBuffers) {
  49048. this.disposeDistancesComputationGPUBufferResources();
  49049. }
  49050. var gl = this.renderer.getContext();
  49051. var createShader = (gl, type, source) => {
  49052. var shader = gl.createShader(type);
  49053. if (!shader) {
  49054. console.error('Fatal error: gl could not create a shader object.');
  49055. return null;
  49056. }
  49057. gl.shaderSource(shader, source);
  49058. gl.compileShader(shader);
  49059. var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  49060. if (!compiled) {
  49061. var typeName = 'unknown';
  49062. if (type === gl.VERTEX_SHADER) typeName = 'vertex shader';else if (type === gl.FRAGMENT_SHADER) typeName = 'fragement shader';
  49063. var errors = gl.getShaderInfoLog(shader);
  49064. console.error('Failed to compile ' + typeName + ' with these errors:' + errors);
  49065. gl.deleteShader(shader);
  49066. return null;
  49067. }
  49068. return shader;
  49069. };
  49070. var vsSource;
  49071. if (this.integerBasedDistancesComputation) {
  49072. vsSource = "#version 300 es\n in ivec4 center;\n flat out int distance;";
  49073. if (this.dynamicMode) {
  49074. vsSource += "\n in uint transformIndex;\n uniform ivec4 transforms[".concat(Constants.MaxScenes, "];\n void main(void) {\n ivec4 transform = transforms[transformIndex];\n distance = center.x * transform.x + center.y * transform.y + center.z * transform.z + transform.w * center.w;\n }\n ");
  49075. } else {
  49076. vsSource += "\n uniform ivec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n ";
  49077. }
  49078. } else {
  49079. vsSource = "#version 300 es\n in vec4 center;\n flat out float distance;";
  49080. if (this.dynamicMode) {
  49081. vsSource += "\n in uint transformIndex;\n uniform mat4 transforms[".concat(Constants.MaxScenes, "];\n void main(void) {\n vec4 transformedCenter = transforms[transformIndex] * vec4(center.xyz, 1.0);\n distance = transformedCenter.z;\n }\n ");
  49082. } else {
  49083. vsSource += "\n uniform vec3 modelViewProj;\n void main(void) {\n distance = center.x * modelViewProj.x + center.y * modelViewProj.y + center.z * modelViewProj.z;\n }\n ";
  49084. }
  49085. }
  49086. var fsSource = "#version 300 es\n precision lowp float;\n out vec4 fragColor;\n void main(){}\n ";
  49087. var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  49088. var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);
  49089. var currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false;
  49090. if (rebuildGPUObjects) {
  49091. this.distancesTransformFeedback.vao = gl.createVertexArray();
  49092. }
  49093. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  49094. if (rebuildGPUObjects) {
  49095. var program = gl.createProgram();
  49096. var vertexShader = createShader(gl, gl.VERTEX_SHADER, vsSource);
  49097. var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fsSource);
  49098. if (!vertexShader || !fragmentShader) {
  49099. throw new Error('Could not compile shaders for distances computation on GPU.');
  49100. }
  49101. gl.attachShader(program, vertexShader);
  49102. gl.attachShader(program, fragmentShader);
  49103. gl.transformFeedbackVaryings(program, ['distance'], gl.SEPARATE_ATTRIBS);
  49104. gl.linkProgram(program);
  49105. var linked = gl.getProgramParameter(program, gl.LINK_STATUS);
  49106. if (!linked) {
  49107. var error = gl.getProgramInfoLog(program);
  49108. console.error('Fatal error: Failed to link program: ' + error);
  49109. gl.deleteProgram(program);
  49110. gl.deleteShader(fragmentShader);
  49111. gl.deleteShader(vertexShader);
  49112. throw new Error('Could not link shaders for distances computation on GPU.');
  49113. }
  49114. this.distancesTransformFeedback.program = program;
  49115. this.distancesTransformFeedback.vertexShader = vertexShader;
  49116. this.distancesTransformFeedback.vertexShader = fragmentShader;
  49117. }
  49118. gl.useProgram(this.distancesTransformFeedback.program);
  49119. this.distancesTransformFeedback.centersLoc = gl.getAttribLocation(this.distancesTransformFeedback.program, 'center');
  49120. if (this.dynamicMode) {
  49121. this.distancesTransformFeedback.transformIndexesLoc = gl.getAttribLocation(this.distancesTransformFeedback.program, 'transformIndex');
  49122. for (var i = 0; i < this.scenes.length; i++) {
  49123. this.distancesTransformFeedback.transformsLocs[i] = gl.getUniformLocation(this.distancesTransformFeedback.program, "transforms[".concat(i, "]"));
  49124. }
  49125. } else {
  49126. this.distancesTransformFeedback.modelViewProjLoc = gl.getUniformLocation(this.distancesTransformFeedback.program, 'modelViewProj');
  49127. }
  49128. if (rebuildGPUObjects || rebuildBuffers) {
  49129. this.distancesTransformFeedback.centersBuffer = gl.createBuffer();
  49130. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  49131. gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc);
  49132. if (this.integerBasedDistancesComputation) {
  49133. gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0);
  49134. } else {
  49135. gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0);
  49136. }
  49137. if (this.dynamicMode) {
  49138. this.distancesTransformFeedback.transformIndexesBuffer = gl.createBuffer();
  49139. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer);
  49140. gl.enableVertexAttribArray(this.distancesTransformFeedback.transformIndexesLoc);
  49141. gl.vertexAttribIPointer(this.distancesTransformFeedback.transformIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0);
  49142. }
  49143. }
  49144. if (rebuildGPUObjects || rebuildBuffers) {
  49145. this.distancesTransformFeedback.outDistancesBuffer = gl.createBuffer();
  49146. }
  49147. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer);
  49148. gl.bufferData(gl.ARRAY_BUFFER, maxSplatCount * 4, gl.STATIC_READ);
  49149. if (rebuildGPUObjects) {
  49150. this.distancesTransformFeedback.id = gl.createTransformFeedback();
  49151. }
  49152. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id);
  49153. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer);
  49154. if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram);
  49155. if (currentVao) gl.bindVertexArray(currentVao);
  49156. this.lastRenderer = this.renderer;
  49157. currentMaxSplatCount = maxSplatCount;
  49158. };
  49159. }());
  49160. /**
  49161. * Fill 'array' with the transforms for each scene in this splat mesh.
  49162. * @param {Array} array Empty array to be filled with scene transforms. If not empty, contents will be overwritten.
  49163. */
  49164. _defineProperty(this, "fillTransformsArray", function () {
  49165. var tempArray = [];
  49166. return function (array) {
  49167. if (tempArray.length !== array.length) tempArray.length = array.length;
  49168. for (var i = 0; i < this.scenes.length; i++) {
  49169. var sceneTransform = this.getScene(i).transform;
  49170. var sceneTransformElements = sceneTransform.elements;
  49171. for (var j = 0; j < 16; j++) {
  49172. tempArray[i * 16 + j] = sceneTransformElements[j];
  49173. }
  49174. }
  49175. array.set(tempArray);
  49176. };
  49177. }());
  49178. _defineProperty(this, "computeDistancesOnGPU", function () {
  49179. var tempMatrix = new THREE$2.Matrix4();
  49180. return function (modelViewProjMatrix, outComputedDistances) {
  49181. if (!this.renderer) return;
  49182. // console.time("gpu_compute_distances");
  49183. var gl = this.renderer.getContext();
  49184. var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  49185. var currentProgram = gl.getParameter(gl.CURRENT_PROGRAM);
  49186. var currentProgramDeleted = currentProgram ? gl.getProgramParameter(currentProgram, gl.DELETE_STATUS) : false;
  49187. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  49188. gl.useProgram(this.distancesTransformFeedback.program);
  49189. gl.enable(gl.RASTERIZER_DISCARD);
  49190. if (this.dynamicMode) {
  49191. for (var i = 0; i < this.scenes.length; i++) {
  49192. tempMatrix.copy(this.getScene(i).transform);
  49193. tempMatrix.premultiply(modelViewProjMatrix);
  49194. if (this.integerBasedDistancesComputation) {
  49195. var iTempMatrix = SplatMesh.getIntegerMatrixArray(tempMatrix);
  49196. var iTransform = [iTempMatrix[2], iTempMatrix[6], iTempMatrix[10], iTempMatrix[14]];
  49197. gl.uniform4i(this.distancesTransformFeedback.transformsLocs[i], iTransform[0], iTransform[1], iTransform[2], iTransform[3]);
  49198. } else {
  49199. gl.uniformMatrix4fv(this.distancesTransformFeedback.transformsLocs[i], false, tempMatrix.elements);
  49200. }
  49201. }
  49202. } else {
  49203. if (this.integerBasedDistancesComputation) {
  49204. var iViewProjMatrix = SplatMesh.getIntegerMatrixArray(modelViewProjMatrix);
  49205. var iViewProj = [iViewProjMatrix[2], iViewProjMatrix[6], iViewProjMatrix[10]];
  49206. gl.uniform3i(this.distancesTransformFeedback.modelViewProjLoc, iViewProj[0], iViewProj[1], iViewProj[2]);
  49207. } else {
  49208. var viewProj = [modelViewProjMatrix.elements[2], modelViewProjMatrix.elements[6], modelViewProjMatrix.elements[10]];
  49209. gl.uniform3f(this.distancesTransformFeedback.modelViewProjLoc, viewProj[0], viewProj[1], viewProj[2]);
  49210. }
  49211. }
  49212. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  49213. gl.enableVertexAttribArray(this.distancesTransformFeedback.centersLoc);
  49214. if (this.integerBasedDistancesComputation) {
  49215. gl.vertexAttribIPointer(this.distancesTransformFeedback.centersLoc, 4, gl.INT, 0, 0);
  49216. } else {
  49217. gl.vertexAttribPointer(this.distancesTransformFeedback.centersLoc, 4, gl.FLOAT, false, 0, 0);
  49218. }
  49219. if (this.dynamicMode) {
  49220. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer);
  49221. gl.enableVertexAttribArray(this.distancesTransformFeedback.transformIndexesLoc);
  49222. gl.vertexAttribIPointer(this.distancesTransformFeedback.transformIndexesLoc, 1, gl.UNSIGNED_INT, 0, 0);
  49223. }
  49224. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, this.distancesTransformFeedback.id);
  49225. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, this.distancesTransformFeedback.outDistancesBuffer);
  49226. gl.beginTransformFeedback(gl.POINTS);
  49227. gl.drawArrays(gl.POINTS, 0, this.getSplatCount());
  49228. gl.endTransformFeedback();
  49229. gl.bindBufferBase(gl.TRANSFORM_FEEDBACK_BUFFER, 0, null);
  49230. gl.bindTransformFeedback(gl.TRANSFORM_FEEDBACK, null);
  49231. gl.disable(gl.RASTERIZER_DISCARD);
  49232. var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
  49233. gl.flush();
  49234. var promise = new Promise(resolve => {
  49235. var checkSync = () => {
  49236. if (this.disposed) {
  49237. resolve();
  49238. } else {
  49239. var timeout = 0;
  49240. var bitflags = 0;
  49241. var status = gl.clientWaitSync(sync, bitflags, timeout);
  49242. switch (status) {
  49243. case gl.TIMEOUT_EXPIRED:
  49244. this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync);
  49245. return this.computeDistancesOnGPUSyncTimeout;
  49246. case gl.WAIT_FAILED:
  49247. throw new Error('should never get here');
  49248. default:
  49249. this.computeDistancesOnGPUSyncTimeout = null;
  49250. gl.deleteSync(sync);
  49251. var _currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  49252. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  49253. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.outDistancesBuffer);
  49254. gl.getBufferSubData(gl.ARRAY_BUFFER, 0, outComputedDistances);
  49255. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  49256. if (_currentVao) gl.bindVertexArray(_currentVao);
  49257. // console.timeEnd("gpu_compute_distances");
  49258. resolve();
  49259. }
  49260. }
  49261. };
  49262. this.computeDistancesOnGPUSyncTimeout = setTimeout(checkSync);
  49263. });
  49264. if (currentProgram && currentProgramDeleted !== true) gl.useProgram(currentProgram);
  49265. if (currentVao) gl.bindVertexArray(currentVao);
  49266. return promise;
  49267. };
  49268. }());
  49269. /**
  49270. * Get the center for a splat, transformed as appropriate.
  49271. * @param {number} globalIndex Global index of splat
  49272. * @param {THREE.Vector3} outCenter THREE.Vector3 instance in which to store splat center
  49273. * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at
  49274. * 'globalIndex' belongs will be applied to the splat center. If 'applySceneTransform' is true,
  49275. * the scene transform will always be applied and if 'applySceneTransform' is false, the
  49276. * scene transform will never be applied. If undefined, the default behavior will apply.
  49277. */
  49278. _defineProperty(this, "getSplatCenter", function () {
  49279. var paramsObj = {};
  49280. return function (globalIndex, outCenter, applySceneTransform) {
  49281. this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform);
  49282. paramsObj.splatBuffer.getSplatCenter(paramsObj.localIndex, outCenter, paramsObj.sceneTransform);
  49283. };
  49284. }());
  49285. /**
  49286. * Get the scale and rotation for a splat, transformed as appropriate.
  49287. * @param {number} globalIndex Global index of splat
  49288. * @param {THREE.Vector3} outScale THREE.Vector3 instance in which to store splat scale
  49289. * @param {THREE.Quaternion} outRotation THREE.Quaternion instance in which to store splat rotation
  49290. * @param {boolean} applySceneTransform By default, if the splat mesh is static, the transform of the scene to which the splat at
  49291. * 'globalIndex' belongs will be applied to the splat scale and rotation. If
  49292. * 'applySceneTransform' is true, the scene transform will always be applied and if
  49293. * 'applySceneTransform' is false, the scene transform will never be applied. If undefined,
  49294. * the default behavior will apply.
  49295. */
  49296. _defineProperty(this, "getSplatScaleAndRotation", function () {
  49297. var paramsObj = {};
  49298. return function (globalIndex, outScale, outRotation, applySceneTransform) {
  49299. this.getLocalSplatParameters(globalIndex, paramsObj, applySceneTransform);
  49300. paramsObj.splatBuffer.getSplatScaleAndRotation(paramsObj.localIndex, outScale, outRotation, paramsObj.sceneTransform);
  49301. };
  49302. }());
  49303. /**
  49304. * Get the color for a splat.
  49305. * @param {number} globalIndex Global index of splat
  49306. * @param {THREE.Vector4} outColor THREE.Vector4 instance in which to store splat color
  49307. */
  49308. _defineProperty(this, "getSplatColor", function () {
  49309. var paramsObj = {};
  49310. return function (globalIndex, outColor) {
  49311. this.getLocalSplatParameters(globalIndex, paramsObj);
  49312. paramsObj.splatBuffer.getSplatColor(paramsObj.localIndex, outColor);
  49313. };
  49314. }());
  49315. this.renderer = undefined;
  49316. // Use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit
  49317. this.halfPrecisionCovariancesOnGPU = halfPrecisionCovariancesOnGPU;
  49318. // When 'dynamicMode' is true, scenes are assumed to be non-static. Dynamic scenes are handled differently
  49319. // and certain optimizations cannot be made for them. Additionally, by default, all splat data retrieved from
  49320. // this splat mesh will not have their scene transform applied to them if the splat mesh is dynamic. That
  49321. // can be overriden via parameters to the individual functions that are used to retrieve splat data.
  49322. this.dynamicMode = dynamicMode;
  49323. // Ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device
  49324. this.devicePixelRatio = devicePixelRatio;
  49325. // Use a transform feedback to calculate splat distances from the camera
  49326. this.enableDistancesComputationOnGPU = enableDistancesComputationOnGPU;
  49327. // Use a faster integer-based approach for calculating splat distances from the camera
  49328. this.integerBasedDistancesComputation = integerBasedDistancesComputation;
  49329. // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a
  49330. // substantially different resolution than that at which they were rendered during training. This will only work correctly
  49331. // for models that were trained using a process that utilizes this compensation calculation. For more details:
  49332. // https://github.com/nerfstudio-project/gsplat/pull/117
  49333. // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093
  49334. this.antialiased = antialiased;
  49335. // Specify the maximum clip space splat size, can help deal with large splats that get too unwieldy
  49336. this.maxScreenSpaceSplatSize = maxScreenSpaceSplatSize;
  49337. // The verbosity of console logging
  49338. this.logLevel = logLevel;
  49339. // Degree 0 means no spherical harmonics
  49340. this.sphericalHarmonicsDegree = sphericalHarmonicsDegree;
  49341. this.minSphericalHarmonicsDegree = 0;
  49342. // The individual splat scenes stored in this splat mesh, each containing their own transform
  49343. this.scenes = [];
  49344. // Special octree tailored to SplatMesh instances
  49345. this.splatTree = null;
  49346. this.baseSplatTree = null;
  49347. // Textures in which splat data will be stored for rendering
  49348. this.splatDataTextures = {};
  49349. this.distancesTransformFeedback = {
  49350. 'id': null,
  49351. 'vertexShader': null,
  49352. 'fragmentShader': null,
  49353. 'program': null,
  49354. 'centersBuffer': null,
  49355. 'transformIndexesBuffer': null,
  49356. 'outDistancesBuffer': null,
  49357. 'centersLoc': -1,
  49358. 'modelViewProjLoc': -1,
  49359. 'transformIndexesLoc': -1,
  49360. 'transformsLocs': []
  49361. };
  49362. this.globalSplatIndexToLocalSplatIndexMap = [];
  49363. this.globalSplatIndexToSceneIndexMap = [];
  49364. this.lastBuildSplatCount = 0;
  49365. this.lastBuildScenes = [];
  49366. this.lastBuildMaxSplatCount = 0;
  49367. this.lastBuildSceneCount = 0;
  49368. this.firstRenderTime = -1;
  49369. this.finalBuild = false;
  49370. this.webGLUtils = null;
  49371. this.boundingBox = new THREE$2.Box3();
  49372. this.calculatedSceneCenter = new THREE$2.Vector3();
  49373. this.maxSplatDistanceFromSceneCenter = 0;
  49374. this.visibleRegionBufferRadius = 0;
  49375. this.visibleRegionRadius = 0;
  49376. this.visibleRegionFadeStartRadius = 0;
  49377. this.visibleRegionChanging = false;
  49378. this.splatScale = 1.0;
  49379. this.pointCloudModeEnabled = false;
  49380. this.disposed = false;
  49381. this.lastRenderer = null;
  49382. this.visible = false;
  49383. }
  49384. /**
  49385. * Build the Three.js material that is used to render the splats.
  49386. * @param {number} dynamicMode If true, it means the scene geometry represented by this splat mesh is not stationary or
  49387. * that the splat count might change
  49388. * @param {boolean} antialiased If true, calculate compensation factor to deal with gaussians being rendered at a significantly
  49389. * different resolution than that of their training
  49390. * @param {number} maxScreenSpaceSplatSize The maximum clip space splat size
  49391. * @param {number} splatScale Value by which all splats are scaled in screen-space (default is 1.0)
  49392. * @param {number} pointCloudModeEnabled Render all splats as screen-space circles
  49393. * @param {number} maxSphericalHarmonicsDegree Degree of spherical harmonics to utilize in rendering splats
  49394. * @return {THREE.ShaderMaterial}
  49395. */
  49396. static buildMaterial() {
  49397. var dynamicMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  49398. var antialiased = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  49399. var maxScreenSpaceSplatSize = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2048;
  49400. var splatScale = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1.0;
  49401. var pointCloudModeEnabled = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
  49402. var maxSphericalHarmonicsDegree = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  49403. // Contains the code to project 3D covariance to 2D and from there calculate the quad (using the eigen vectors of the
  49404. // 2D covariance) that is ultimately rasterized
  49405. var vertexShaderSource = "\n precision highp float;\n #include <common>\n\n attribute uint splatIndex;\n\n uniform highp sampler2D covariancesTexture;\n uniform highp usampler2D centersColorsTexture;\n uniform highp sampler2D sphericalHarmonicsTexture;";
  49406. if (dynamicMode) {
  49407. vertexShaderSource += "\n uniform highp usampler2D transformIndexesTexture;\n uniform highp mat4 transforms[".concat(Constants.MaxScenes, "];\n uniform vec2 transformIndexesTextureSize;\n ");
  49408. }
  49409. vertexShaderSource += "\n uniform vec2 focal;\n uniform float orthoZoom;\n uniform int orthographicMode;\n uniform int pointCloudModeEnabled;\n uniform float inverseFocalAdjustment;\n uniform vec2 viewport;\n uniform vec2 basisViewport;\n uniform vec2 covariancesTextureSize;\n uniform vec2 centersColorsTextureSize;\n uniform int sphericalHarmonicsDegree;\n uniform vec2 sphericalHarmonicsTextureSize;\n uniform int sphericalHarmonics8BitMode;\n uniform float visibleRegionRadius;\n uniform float visibleRegionFadeStartRadius;\n uniform float firstRenderTime;\n uniform float currentTime;\n uniform int fadeInComplete;\n uniform vec3 sceneCenter;\n uniform float splatScale;\n\n varying vec4 vColor;\n varying vec2 vUv;\n\n varying vec2 vPosition;\n\n const float sqrt8 = sqrt(8.0);\n const float minAlpha = 1.0 / 255.0;\n\n const vec4 encodeNorm4 = vec4(1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n const uvec4 mask4 = uvec4(uint(0x000000FF), uint(0x0000FF00), uint(0x00FF0000), uint(0xFF000000));\n const uvec4 shift4 = uvec4(0, 8, 16, 24);\n vec4 uintToRGBAVec (uint u) {\n uvec4 urgba = mask4 & u;\n urgba = urgba >> shift4;\n vec4 rgba = vec4(urgba) * encodeNorm4;\n return rgba;\n }\n\n vec2 getDataUV(in int stride, in int offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(splatIndex * uint(stride) + uint(offset)) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n vec2 getDataUVF(in uint sIndex, in float stride, in uint offset, in vec2 dimensions) {\n vec2 samplerUV = vec2(0.0, 0.0);\n float d = float(uint(float(sIndex) * stride) + offset) / dimensions.x;\n samplerUV.y = float(floor(d)) / dimensions.y;\n samplerUV.x = fract(d);\n return samplerUV;\n }\n\n const float SH_C1 = 0.4886025119029199f;\n const float[5] SH_C2 = float[](1.0925484, -1.0925484, 0.3153916, -1.0925484, 0.5462742);\n const vec3 vecOnes3 = vec3(1.0, 1.0, 1.0);\n\n void main () {\n\n uint oddOffset = splatIndex & uint(0x00000001);\n uint doubleOddOffset = oddOffset * uint(2);\n bool isEven = oddOffset == uint(0);\n uint nearestEvenIndex = splatIndex - oddOffset;\n float fOddOffset = float(oddOffset);\n\n uvec4 sampledCenterColor = texture(centersColorsTexture, getDataUV(1, 0, centersColorsTextureSize));\n vec3 splatCenter = uintBitsToFloat(uvec3(sampledCenterColor.gba));";
  49410. if (dynamicMode) {
  49411. vertexShaderSource += "\n uint transformIndex = texture(transformIndexesTexture, getDataUV(1, 0, transformIndexesTextureSize)).r;\n mat4 transform = transforms[transformIndex];\n mat4 transformModelViewMatrix = modelViewMatrix * transform;\n ";
  49412. } else {
  49413. vertexShaderSource += "mat4 transformModelViewMatrix = modelViewMatrix;";
  49414. }
  49415. vertexShaderSource += "\n vec4 viewCenter = transformModelViewMatrix * vec4(splatCenter, 1.0);\n\n vec4 clipCenter = projectionMatrix * viewCenter;\n\n float clip = 1.2 * clipCenter.w;\n if (clipCenter.z < -clip || clipCenter.x < -clip || clipCenter.x > clip || clipCenter.y < -clip || clipCenter.y > clip) {\n gl_Position = vec4(0.0, 0.0, 2.0, 1.0);\n return;\n }\n\n vPosition = position.xy;\n vColor = uintToRGBAVec(sampledCenterColor.r);\n\n ";
  49416. if (maxSphericalHarmonicsDegree >= 1) {
  49417. vertexShaderSource += " \n if (sphericalHarmonicsDegree >= 1) {\n ";
  49418. if (dynamicMode) {
  49419. vertexShaderSource += "\n mat4 mTransform = modelMatrix * transform;\n vec3 worldViewDir = normalize(splatCenter - vec3(inverse(mTransform) * vec4(cameraPosition, 1.0)));\n ";
  49420. } else {
  49421. vertexShaderSource += "\n vec3 worldViewDir = normalize(splatCenter - cameraPosition);\n ";
  49422. }
  49423. if (maxSphericalHarmonicsDegree >= 2) {
  49424. vertexShaderSource += "\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, getDataUV(6, 0, sphericalHarmonicsTextureSize));\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, getDataUV(6, 1, sphericalHarmonicsTextureSize));\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, getDataUV(6, 2, sphericalHarmonicsTextureSize));\n vec3 sh1 = sampledSH0123.rgb;\n vec3 sh2 = vec3(sampledSH0123.a, sampledSH4567.rg);\n vec3 sh3 = vec3(sampledSH4567.ba, sampledSH891011.r);\n ";
  49425. } else {
  49426. vertexShaderSource += "\n vec2 shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset, sphericalHarmonicsTextureSize);\n vec4 sampledSH0123 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(1), sphericalHarmonicsTextureSize);\n vec4 sampledSH4567 = texture(sphericalHarmonicsTexture, shUV);\n shUV = getDataUVF(nearestEvenIndex, 2.5, doubleOddOffset + uint(2), sphericalHarmonicsTextureSize);\n vec4 sampledSH891011 = texture(sphericalHarmonicsTexture, shUV);\n\n vec3 sh1 = vec3(sampledSH0123.rgb) * (1.0 - fOddOffset) + vec3(sampledSH0123.ba, sampledSH4567.r) * fOddOffset;\n vec3 sh2 = vec3(sampledSH0123.a, sampledSH4567.rg) * (1.0 - fOddOffset) + vec3(sampledSH4567.gba) * fOddOffset;\n vec3 sh3 = vec3(sampledSH4567.ba, sampledSH891011.r) * (1.0 - fOddOffset) + vec3(sampledSH891011.rgb) * fOddOffset;\n ";
  49427. }
  49428. vertexShaderSource += "\n if (sphericalHarmonics8BitMode == 1) {\n sh1 = sh1 * 2.0 - vecOnes3;\n sh2 = sh2 * 2.0 - vecOnes3;\n sh3 = sh3 * 2.0 - vecOnes3;\n }\n float x = worldViewDir.x;\n float y = worldViewDir.y;\n float z = worldViewDir.z;\n vColor.rgb += SH_C1 * (-sh1 * y + sh2 * z - sh3 * x);\n ";
  49429. if (maxSphericalHarmonicsDegree >= 2) {
  49430. vertexShaderSource += "\n if (sphericalHarmonicsDegree >= 2) {\n float xx = x * x;\n float yy = y * y;\n float zz = z * z;\n float xy = x * y;\n float yz = y * z;\n float xz = x * z;\n\n vec4 sampledSH12131415 = texture(sphericalHarmonicsTexture, getDataUV(6, 3, sphericalHarmonicsTextureSize));\n vec4 sampledSH16171819 = texture(sphericalHarmonicsTexture, getDataUV(6, 4, sphericalHarmonicsTextureSize));\n vec4 sampledSH20212223 = texture(sphericalHarmonicsTexture, getDataUV(6, 5, sphericalHarmonicsTextureSize));\n\n vec3 sh4 = sampledSH891011.gba;\n vec3 sh5 = sampledSH12131415.rgb;\n vec3 sh6 = vec3(sampledSH12131415.a, sampledSH16171819.rg);\n vec3 sh7 = vec3(sampledSH16171819.ba, sampledSH20212223.r);\n vec3 sh8 = sampledSH20212223.gba;\n\n if (sphericalHarmonics8BitMode == 1) {\n sh4 = sh4 * 2.0 - vecOnes3;\n sh5 = sh5 * 2.0 - vecOnes3;\n sh6 = sh6 * 2.0 - vecOnes3;\n sh7 = sh7 * 2.0 - vecOnes3;\n sh8 = sh8 * 2.0 - vecOnes3;\n }\n\n vColor.rgb +=\n (SH_C2[0] * xy) * sh4 +\n (SH_C2[1] * yz) * sh5 +\n (SH_C2[2] * (2.0 * zz - xx - yy)) * sh6 +\n (SH_C2[3] * xz) * sh7 +\n (SH_C2[4] * (xx - yy)) * sh8;\n }\n ";
  49431. }
  49432. vertexShaderSource += "\n }\n ";
  49433. }
  49434. vertexShaderSource += "\n\n vec4 sampledCovarianceA = texture(covariancesTexture,\n getDataUVF(nearestEvenIndex, 1.5, oddOffset, covariancesTextureSize));\n vec4 sampledCovarianceB = texture(covariancesTexture,\n getDataUVF(nearestEvenIndex, 1.5, oddOffset + uint(1), covariancesTextureSize));\n\n vec3 cov3D_M11_M12_M13 = vec3(sampledCovarianceA.rgb) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceA.ba, sampledCovarianceB.r) * fOddOffset;\n vec3 cov3D_M22_M23_M33 = vec3(sampledCovarianceA.a, sampledCovarianceB.rg) * (1.0 - fOddOffset) +\n vec3(sampledCovarianceB.gba) * fOddOffset;\n\n // Construct the 3D covariance matrix\n mat3 Vrk = mat3(\n cov3D_M11_M12_M13.x, cov3D_M11_M12_M13.y, cov3D_M11_M12_M13.z,\n cov3D_M11_M12_M13.y, cov3D_M22_M23_M33.x, cov3D_M22_M23_M33.y,\n cov3D_M11_M12_M13.z, cov3D_M22_M23_M33.y, cov3D_M22_M23_M33.z\n );\n\n \n // Construct the Jacobian\u884C\u5217\u5F0F of the affine\u4EFF\u5C04 approximation\u903C\u8FD1 of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result. (This assumes\u5047\u8BBE\n // the current projection is a perspective projection).\n //\u7FFB\u8BD1\u7ED3\u679C\uFF1A\u6784\u5EFA\u6295\u5F71\u77E9\u9635\u4EFF\u5C04\u8FD1\u4F3C\u7684\u96C5\u53EF\u6BD4\u77E9\u9635\u3002\u5B83\u5C06\u88AB\u7528\u6765\u53D8\u63623D\u534F\u65B9\u5DEE\u77E9\u9635\uFF0C\u800C\u4E0D\u662F\u76F4\u63A5\u4F7F\u7528\u5B9E\u9645\u7684\u6295\u5F71\u77E9\u9635\uFF0C\u56E0\u4E3A\u4F7F\u7528\u5B9E\u9645\u6295\u5F71\u77E9\u9635\u8FDB\u884C\u53D8\u6362\u9700\u8981\u5305\u542B\u975E\u7EBF\u6027\u6210\u5206\uFF08\u900F\u89C6\u9664\u6CD5\uFF09\uFF0C\u8FD9\u4F1A\u5BFC\u81F4\u975E\u9AD8\u65AF\u7684\u7ED3\u679C\u3002\u8FD9\u91CC\u5047\u8BBE\u5F53\u524D\u7684\u6295\u5F71\u4E3A\u900F\u89C6\u6295\u5F71\u3002\n //\u770B\u4E0D\u61C2 https://zhuanlan.zhihu.com/p/661569671\n\n \n mat3 J;\n if (orthographicMode == 1) {\n // Since the projection is linear, we don't need an approximation\n J = transpose(mat3(orthoZoom, 0.0, 0.0,\n 0.0, orthoZoom, 0.0,\n 0.0, 0.0, 0.0));\n } else {\n // Construct the Jacobian of the affine approximation of the projection matrix. It will be used to transform the\n // 3D covariance matrix instead of using the actual projection matrix because that transformation would\n // require a non-linear component (perspective division) which would yield a non-gaussian result.\n float s = 1.0 / (viewCenter.z * viewCenter.z);\n J = mat3(\n focal.x / viewCenter.z, 0., -(focal.x * viewCenter.x) * s,\n 0., focal.y / viewCenter.z, -(focal.y * viewCenter.y) * s,\n 0., 0., 0.\n );\n }\n\n // Concatenate the projection approximation with the model-view transformation\n mat3 W = transpose(mat3(transformModelViewMatrix));\n mat3 T = W * J;\n\n // Transform the 3D covariance matrix (Vrk) to compute the 2D covariance matrix\n mat3 cov2Dm = transpose(T) * Vrk * T;\n ";
  49435. if (antialiased) {
  49436. vertexShaderSource += "\n float detOrig = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n cov2Dm[0][0] += 0.3;\n cov2Dm[1][1] += 0.3;\n float detBlur = cov2Dm[0][0] * cov2Dm[1][1] - cov2Dm[0][1] * cov2Dm[0][1];\n float compensation = sqrt(max(detOrig / detBlur, 0.0));\n ";
  49437. } else {
  49438. vertexShaderSource += "\n cov2Dm[0][0] += 0.3;\n cov2Dm[1][1] += 0.3;\n float compensation = 1.0;\n ";
  49439. }
  49440. vertexShaderSource += "\n\n vColor.a *= compensation;\n\n if (vColor.a < minAlpha) return;\n\n // We are interested in the upper-left 2x2 portion of the projected 3D covariance matrix because\n // we only care about the X and Y values. We want the X-diagonal, cov2Dm[0][0],\n // the Y-diagonal, cov2Dm[1][1], and the correlation between the two cov2Dm[0][1]. We don't\n // need cov2Dm[1][0] because it is a symetric matrix.\n vec3 cov2Dv = vec3(cov2Dm[0][0], cov2Dm[0][1], cov2Dm[1][1]);\n\n vec3 ndcCenter = clipCenter.xyz / clipCenter.w;\n\n // We now need to solve for the eigen-values and eigen vectors of the 2D covariance matrix\n // so that we can determine the 2D basis for the splat. This is done using the method described\n // here: https://people.math.harvard.edu/~knill/teaching/math21b2004/exhibits/2dmatrices/index.html \u516C\u5F0F\u51FA\u5904\n // After calculating the eigen-values and eigen-vectors, we calculate the basis for rendering the splat\n // by normalizing the eigen-vectors and then multiplying them by (sqrt(8) * eigen-value), which is\n // equal to scaling them by sqrt(8) standard deviations.\n //\n // This is a different approach than in the original work at INRIA. In that work they compute the\n // max extents of the projected splat in screen space to form a screen-space aligned bounding rectangle\n // which forms the geometry that is actually rasterized. The dimensions of that bounding box are 3.0\n // times the maximum eigen-value, or 3 standard deviations. They then use the inverse 2D covariance\n // matrix (called 'conic') in the CUDA rendering thread to determine fragment opacity by calculating the\n // full gaussian: exp(-0.5 * (X - mean) * conic * (X - mean)) * splat opacity\n float a = cov2Dv.x;\n float d = cov2Dv.z;\n float b = cov2Dv.y;\n float D = a * d - b * b;\n float trace = a + d; //\u8FFD\u8E2A\n float traceOver2 = 0.5 * trace;\n float term2 = sqrt(max(0.1f, traceOver2 * traceOver2 - D));\n float eigenValue1 = traceOver2 + term2; //\u7279\u5F81\u503CL1\n float eigenValue2 = traceOver2 - term2; //\u7279\u5F81\u503CL1\n\n if (pointCloudModeEnabled == 1) {// each splat is rendered as a filled circle\n eigenValue1 = eigenValue2 = 0.2;\n }\n\n if (eigenValue2 <= 0.0) return;\n\n vec2 eigenVector1 = normalize(vec2(b, eigenValue1 - a));\n // since the eigen vectors are orthogonal, we derive the second one from the first \u7531\u4E8E\u672C\u5F81\u5411\u91CF\u662F\u6B63\u4EA4\u7684\uFF0C\u56E0\u6B64\u6211\u4EEC\u4ECE\u7B2C\u4E00\u4E2A\u5BFC\u51FA\u7B2C\u4E8C\u4E2A\n vec2 eigenVector2 = vec2(eigenVector1.y, -eigenVector1.x);\n\n // We use sqrt(8) standard deviations\u504F\u5DEE instead of 3 to eliminate\u6D88\u9664 more of the splat with a very low opacity.\n vec2 basisVector1 = eigenVector1 * splatScale * min(sqrt8 * sqrt(eigenValue1), ".concat(parseInt(maxScreenSpaceSplatSize), ".0);\n vec2 basisVector2 = eigenVector2 * splatScale * min(sqrt8 * sqrt(eigenValue2), ").concat(parseInt(maxScreenSpaceSplatSize), ".0);\n\n if (fadeInComplete == 0) {\n float opacityAdjust = 1.0;\n float centerDist = length(splatCenter - sceneCenter);\n float renderTime = max(currentTime - firstRenderTime, 0.0);\n\n float fadeDistance = 0.75;\n float distanceLoadFadeInFactor = step(visibleRegionFadeStartRadius, centerDist);\n distanceLoadFadeInFactor = (1.0 - distanceLoadFadeInFactor) +\n (1.0 - clamp((centerDist - visibleRegionFadeStartRadius) / fadeDistance, 0.0, 1.0)) *\n distanceLoadFadeInFactor;\n opacityAdjust *= distanceLoadFadeInFactor;\n vColor.a *= opacityAdjust;\n }\n\n vec2 ndcOffset = vec2(vPosition.x * basisVector1 + vPosition.y * basisVector2) *\n basisViewport * 2.0 * inverseFocalAdjustment;\n\n vec4 quadPos = vec4(ndcCenter.xy + ndcOffset, ndcCenter.z , 1.0);\n gl_Position = quadPos; //\u5C06\u6574\u4E2A\u6B63\u65B9\u5F62\u505A\u4E00\u5B9A\u7684\u62C9\u4F38\u5F62\u53D8\uFF0C\u4E4B\u540E\u5728fs\u4E2D\u56E0\u4E3A\u53EA\u663E\u793A\u4E2D\u95F4\u7684\u5706\uFF0C\u6240\u4EE5\u4E5F\u5C31\u662F\u663E\u793A\u62C9\u4F38\u540E\u7684\u5706\u3002\uFF08vs\u53EA\u8BA1\u7B97\u56DB\u4E2A\u9876\u70B9\u7684\u5177\u4F53\u4F4D\u7F6E\uFF0C\u5176\u4ED6\u4F4D\u7F6E\u662F\u63D2\u503C\u5F97\u5230\u7684\uFF09\n\n // Scale the position data we send to the fragment shader\n vPosition *= sqrt8;\n }");
  49441. //面片模拟椭球,总是有厚度
  49442. var fragmentShaderSource = "\n precision highp float;\n #include <common>\n \n uniform vec3 debugColor;\n\n varying vec4 vColor;\n varying vec2 vUv;\n\n varying vec2 vPosition;\n\n void main () {\n // Compute the positional squared distance from the center of the splat to the current fragment.\n float A = dot(vPosition, vPosition);\n // Since the positional data in vPosition has been scaled by sqrt(8), the squared result will be\n // scaled by a factor of 8. If the squared result is larger than 8, it means it is outside the ellipse\n // defined by the rectangle formed by vPosition. It also means it's farther\n // away than sqrt(8) standard deviations from the mean.\n if (A > 8.0) discard; //position\u7684\u8303\u56F4\u534A\u5F84\u4E3A1\u3002\u6307\u4E00\u4E2Arectangle\u9762\u4E2D\u7684\u8303\u56F4\u3002\u692D\u5706\u5916\u7684\u5B8C\u5168\u900F\u660E\n vec3 color = vColor.rgb;\n\n // Since the rendered splat is scaled by sqrt(8), the inverse covariance matrix that is part of\n // the gaussian formula becomes the identity matrix. We're then left with (X - mean) * (X - mean),\n // and since 'mean' is zero, we have X * X, which is the same as A:\n float opacity = exp(-0.5 * A) * vColor.a; //\u5468\u56F4\u7684\u900F\u660E\u5EA6\u964D\u4F4E\n\n gl_FragColor = vec4(color.rgb, opacity);\n //\u4E0D\u77E5\u9053\u4E3A\u4F55ply\u8F6C\u8FC7\u6765\u7684vColor.a\u662F0\uFF0C(\u4F46\u662F\u5728\u5916\u9762\u8BBF\u95EE\u7684opacity\u5E76\u4E0D\u662F0), \u5BFC\u81F4\u5168\u662F\u9ED1\u8272\n }";
  49443. var uniforms = {
  49444. 'sceneCenter': {
  49445. 'type': 'v3',
  49446. 'value': new THREE$2.Vector3()
  49447. },
  49448. 'fadeInComplete': {
  49449. 'type': 'i',
  49450. 'value': 0
  49451. },
  49452. 'orthographicMode': {
  49453. 'type': 'i',
  49454. 'value': 0
  49455. },
  49456. 'visibleRegionFadeStartRadius': {
  49457. 'type': 'f',
  49458. 'value': 0.0
  49459. },
  49460. 'visibleRegionRadius': {
  49461. 'type': 'f',
  49462. 'value': 0.0
  49463. },
  49464. 'currentTime': {
  49465. 'type': 'f',
  49466. 'value': 0.0
  49467. },
  49468. 'firstRenderTime': {
  49469. 'type': 'f',
  49470. 'value': 0.0
  49471. },
  49472. 'covariancesTexture': {
  49473. //协方差
  49474. 'type': 't',
  49475. 'value': null
  49476. },
  49477. 'centersColorsTexture': {
  49478. 'type': 't',
  49479. 'value': null
  49480. },
  49481. 'sphericalHarmonicsTexture': {
  49482. 'type': 't',
  49483. 'value': null
  49484. },
  49485. 'focal': {
  49486. 'type': 'v2',
  49487. 'value': new THREE$2.Vector2()
  49488. },
  49489. 'orthoZoom': {
  49490. 'type': 'f',
  49491. 'value': 1.0
  49492. },
  49493. 'inverseFocalAdjustment': {
  49494. 'type': 'f',
  49495. 'value': 1.0
  49496. },
  49497. 'viewport': {
  49498. 'type': 'v2',
  49499. 'value': new THREE$2.Vector2()
  49500. },
  49501. 'basisViewport': {
  49502. 'type': 'v2',
  49503. 'value': new THREE$2.Vector2()
  49504. },
  49505. 'debugColor': {
  49506. 'type': 'v3',
  49507. 'value': new THREE$2.Color()
  49508. },
  49509. 'covariancesTextureSize': {
  49510. 'type': 'v2',
  49511. 'value': new THREE$2.Vector2(1024, 1024)
  49512. },
  49513. 'centersColorsTextureSize': {
  49514. 'type': 'v2',
  49515. 'value': new THREE$2.Vector2(1024, 1024)
  49516. },
  49517. 'sphericalHarmonicsDegree': {
  49518. 'type': 'i',
  49519. 'value': maxSphericalHarmonicsDegree
  49520. },
  49521. 'sphericalHarmonicsTextureSize': {
  49522. 'type': 'v2',
  49523. 'value': new THREE$2.Vector2(1024, 1024)
  49524. },
  49525. 'sphericalHarmonics8BitMode': {
  49526. 'type': 'i',
  49527. 'value': 0
  49528. },
  49529. 'splatScale': {
  49530. 'type': 'f',
  49531. 'value': splatScale
  49532. },
  49533. 'pointCloudModeEnabled': {
  49534. 'type': 'i',
  49535. 'value': pointCloudModeEnabled ? 1 : 0
  49536. }
  49537. };
  49538. if (dynamicMode) {
  49539. uniforms['transformIndexesTexture'] = {
  49540. 'type': 't',
  49541. 'value': null
  49542. };
  49543. var transformMatrices = [];
  49544. for (var i = 0; i < Constants.MaxScenes; i++) {
  49545. transformMatrices.push(new THREE$2.Matrix4());
  49546. }
  49547. uniforms['transforms'] = {
  49548. 'type': 'mat4',
  49549. 'value': transformMatrices
  49550. };
  49551. uniforms['transformIndexesTextureSize'] = {
  49552. 'type': 'v2',
  49553. 'value': new THREE$2.Vector2(1024, 1024)
  49554. };
  49555. }
  49556. var material = new THREE$2.ShaderMaterial({
  49557. uniforms: uniforms,
  49558. vertexShader: vertexShaderSource,
  49559. fragmentShader: fragmentShaderSource,
  49560. transparent: true,
  49561. alphaTest: 1.0,
  49562. blending: THREE$2.NormalBlending,
  49563. depthTest: true,
  49564. depthWrite: false,
  49565. side: THREE$2.DoubleSide
  49566. });
  49567. return material;
  49568. }
  49569. /**
  49570. * Build the Three.js geometry that will be used to render the splats. The geometry is instanced and is made up of
  49571. * vertices for a single quad as well as an attribute buffer for the splat indexes.
  49572. * @param {number} maxSplatCount The maximum number of splats that the geometry will need to accomodate
  49573. * @return {THREE.InstancedBufferGeometry}
  49574. */
  49575. static buildGeomtery(maxSplatCount) {
  49576. var baseGeometry = new THREE$2.BufferGeometry();
  49577. baseGeometry.setIndex([0, 1, 2, 0, 2, 3]);
  49578. // Vertices for the instanced quad
  49579. var positionsArray = new Float32Array(4 * 3);
  49580. var positions = new THREE$2.BufferAttribute(positionsArray, 3);
  49581. baseGeometry.setAttribute('position', positions);
  49582. positions.setXYZ(0, -1.0, -1.0, 0.0);
  49583. positions.setXYZ(1, -1.0, 1.0, 0.0);
  49584. positions.setXYZ(2, 1.0, 1.0, 0.0);
  49585. positions.setXYZ(3, 1.0, -1.0, 0.0);
  49586. positions.needsUpdate = true;
  49587. var geometry = new THREE$2.InstancedBufferGeometry().copy(baseGeometry);
  49588. // Splat index buffer
  49589. var splatIndexArray = new Uint32Array(maxSplatCount);
  49590. var splatIndexes = new THREE$2.InstancedBufferAttribute(splatIndexArray, 1, false);
  49591. splatIndexes.setUsage(THREE$2.DynamicDrawUsage);
  49592. geometry.setAttribute('splatIndex', splatIndexes);
  49593. geometry.instanceCount = 0;
  49594. return geometry;
  49595. }
  49596. /**
  49597. * Build a container for each scene managed by this splat mesh based on an instance of SplatBuffer, along with optional
  49598. * transform data (position, scale, rotation) passed to the splat mesh during the build process.
  49599. * @param {Array<THREE.Matrix4>} splatBuffers SplatBuffer instances containing splats for each scene
  49600. * @param {Array<object>} sceneOptions Array of options objects: {
  49601. *
  49602. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  49603. *
  49604. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  49605. *
  49606. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  49607. * }
  49608. * @return {Array<THREE.Matrix4>}
  49609. */
  49610. static buildScenes(splatBuffers, sceneOptions) {
  49611. var scenes = [];
  49612. scenes.length = splatBuffers.length;
  49613. for (var i = 0; i < splatBuffers.length; i++) {
  49614. var splatBuffer = splatBuffers[i];
  49615. var _options = sceneOptions[i] || {};
  49616. var positionArray = _options['position'] || [0, 0, 0];
  49617. var rotationArray = _options['rotation'] || [0, 0, 0, 1];
  49618. var scaleArray = _options['scale'] || [1, 1, 1];
  49619. var position = new THREE$2.Vector3().fromArray(positionArray);
  49620. var rotation = new THREE$2.Quaternion().fromArray(rotationArray);
  49621. var scale = new THREE$2.Vector3().fromArray(scaleArray);
  49622. scenes[i] = SplatMesh.createScene(splatBuffer, position, rotation, scale, _options.splatAlphaRemovalThreshold || 1);
  49623. }
  49624. return scenes;
  49625. }
  49626. static createScene(splatBuffer, position, rotation, scale, minimumAlpha) {
  49627. return new SplatScene(splatBuffer, position, rotation, scale, minimumAlpha);
  49628. }
  49629. /**
  49630. * Build data structures that map global splat indexes (based on a unified index across all splat buffers) to
  49631. * local data within a single scene.
  49632. * @param {Array<SplatBuffer>} splatBuffers Instances of SplatBuffer off which to build the maps
  49633. * @return {object}
  49634. */
  49635. static buildSplatIndexMaps(splatBuffers) {
  49636. var localSplatIndexMap = [];
  49637. var sceneIndexMap = [];
  49638. var totalSplatCount = 0;
  49639. for (var s = 0; s < splatBuffers.length; s++) {
  49640. var splatBuffer = splatBuffers[s];
  49641. var maxSplatCount = splatBuffer.getMaxSplatCount();
  49642. for (var i = 0; i < maxSplatCount; i++) {
  49643. localSplatIndexMap[totalSplatCount] = i;
  49644. sceneIndexMap[totalSplatCount] = s;
  49645. totalSplatCount++;
  49646. }
  49647. }
  49648. return {
  49649. localSplatIndexMap,
  49650. sceneIndexMap
  49651. };
  49652. }
  49653. /**
  49654. * Construct this instance of SplatMesh.
  49655. * @param {Array<SplatBuffer>} splatBuffers The base splat data, instances of SplatBuffer
  49656. * @param {Array<object>} sceneOptions Dynamic options for each scene {
  49657. *
  49658. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  49659. * value (valid range: 0 - 255), defaults to 1
  49660. *
  49661. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  49662. *
  49663. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  49664. *
  49665. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  49666. *
  49667. * }
  49668. * @param {boolean} keepSceneTransforms For a scene that already exists and is being overwritten, this flag
  49669. * says to keep the transform from the existing scene.
  49670. * @param {boolean} finalBuild Will the splat mesh be in its final state after this build?
  49671. * @param {function} onSplatTreeIndexesUpload Function to be called when the upload of splat centers to the splat tree
  49672. * builder worker starts and finishes.
  49673. * @param {function} onSplatTreeConstruction Function to be called when the conversion of the local splat tree from
  49674. * the format produced by the splat tree builder worker starts and ends.
  49675. * @return {object} Object containing info about the splats that are updated
  49676. */
  49677. build(splatBuffers, sceneOptions) {
  49678. var keepSceneTransforms = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  49679. var finalBuild = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  49680. var onSplatTreeIndexesUpload = arguments.length > 4 ? arguments[4] : undefined;
  49681. var onSplatTreeConstruction = arguments.length > 5 ? arguments[5] : undefined;
  49682. this.sceneOptions = sceneOptions;
  49683. this.finalBuild = finalBuild;
  49684. var maxSplatCount = SplatMesh.getTotalMaxSplatCountForSplatBuffers(splatBuffers);
  49685. var newScenes = SplatMesh.buildScenes(splatBuffers, sceneOptions);
  49686. if (keepSceneTransforms) {
  49687. for (var i = 0; i < this.scenes.length && i < newScenes.length; i++) {
  49688. var newScene = newScenes[i];
  49689. var existingScene = this.getScene(i);
  49690. newScene.copyTransformData(existingScene);
  49691. }
  49692. }
  49693. this.scenes = newScenes;
  49694. var minSphericalHarmonicsDegree = 3;
  49695. for (var splatBuffer of splatBuffers) {
  49696. var splatBufferSphericalHarmonicsDegree = splatBuffer.getMinSphericalHarmonicsDegree();
  49697. if (splatBufferSphericalHarmonicsDegree < minSphericalHarmonicsDegree) {
  49698. minSphericalHarmonicsDegree = splatBufferSphericalHarmonicsDegree;
  49699. }
  49700. }
  49701. this.minSphericalHarmonicsDegree = Math.min(minSphericalHarmonicsDegree, this.sphericalHarmonicsDegree);
  49702. var splatBuffersChanged = false;
  49703. if (splatBuffers.length !== this.lastBuildScenes.length) {
  49704. splatBuffersChanged = true;
  49705. } else {
  49706. for (var _i13 = 0; _i13 < splatBuffers.length; _i13++) {
  49707. var _splatBuffer = splatBuffers[_i13];
  49708. if (_splatBuffer !== this.lastBuildScenes[_i13].splatBuffer) {
  49709. splatBuffersChanged = true;
  49710. break;
  49711. }
  49712. }
  49713. }
  49714. var isUpdateBuild = true;
  49715. if (this.scenes.length !== 1 || this.lastBuildSceneCount !== this.scenes.length || this.lastBuildMaxSplatCount !== maxSplatCount || splatBuffersChanged) {
  49716. isUpdateBuild = false;
  49717. }
  49718. if (!isUpdateBuild) {
  49719. this.boundingBox = new THREE$2.Box3();
  49720. this.maxSplatDistanceFromSceneCenter = 0;
  49721. this.visibleRegionBufferRadius = 0;
  49722. this.visibleRegionRadius = 0;
  49723. this.visibleRegionFadeStartRadius = 0;
  49724. this.firstRenderTime = -1;
  49725. this.lastBuildScenes = [];
  49726. this.lastBuildSplatCount = 0;
  49727. this.lastBuildMaxSplatCount = 0;
  49728. this.disposeMeshData();
  49729. this.geometry = SplatMesh.buildGeomtery(maxSplatCount);
  49730. this.material = SplatMesh.buildMaterial(this.dynamicMode, this.antialiased, this.maxScreenSpaceSplatSize, this.splatScale, this.pointCloudModeEnabled, this.minSphericalHarmonicsDegree);
  49731. var indexMaps = SplatMesh.buildSplatIndexMaps(splatBuffers);
  49732. this.globalSplatIndexToLocalSplatIndexMap = indexMaps.localSplatIndexMap;
  49733. this.globalSplatIndexToSceneIndexMap = indexMaps.sceneIndexMap;
  49734. }
  49735. var splatCount = this.getSplatCount();
  49736. if (this.enableDistancesComputationOnGPU) this.setupDistancesComputationTransformFeedback();
  49737. var dataUpdateResults = this.refreshGPUDataFromSplatBuffers(isUpdateBuild);
  49738. for (var _i14 = 0; _i14 < this.scenes.length; _i14++) {
  49739. this.lastBuildScenes[_i14] = this.scenes[_i14];
  49740. }
  49741. this.lastBuildSplatCount = splatCount;
  49742. this.lastBuildMaxSplatCount = this.getMaxSplatCount();
  49743. this.lastBuildSceneCount = this.scenes.length;
  49744. if (finalBuild && this.scenes.length > 0) {
  49745. this.buildSplatTree(sceneOptions.map(options => options.splatAlphaRemovalThreshold || 1), onSplatTreeIndexesUpload, onSplatTreeConstruction).then(() => {
  49746. if (this.onSplatTreeReadyCallback) this.onSplatTreeReadyCallback(this.splatTree);
  49747. });
  49748. }
  49749. this.visible = this.scenes.length > 0;
  49750. return dataUpdateResults;
  49751. }
  49752. /**
  49753. * Dispose all resources held by the splat mesh
  49754. */
  49755. dispose() {
  49756. this.disposeMeshData();
  49757. this.disposeTextures();
  49758. this.disposeSplatTree();
  49759. if (this.enableDistancesComputationOnGPU) {
  49760. if (this.computeDistancesOnGPUSyncTimeout) {
  49761. clearTimeout(this.computeDistancesOnGPUSyncTimeout);
  49762. this.computeDistancesOnGPUSyncTimeout = null;
  49763. }
  49764. this.disposeDistancesComputationGPUResources();
  49765. }
  49766. this.scenes = [];
  49767. this.distancesTransformFeedback = {
  49768. 'id': null,
  49769. 'vertexShader': null,
  49770. 'fragmentShader': null,
  49771. 'program': null,
  49772. 'centersBuffer': null,
  49773. 'transformIndexesBuffer': null,
  49774. 'outDistancesBuffer': null,
  49775. 'centersLoc': -1,
  49776. 'modelViewProjLoc': -1,
  49777. 'transformIndexesLoc': -1,
  49778. 'transformsLocs': []
  49779. };
  49780. this.renderer = null;
  49781. this.globalSplatIndexToLocalSplatIndexMap = [];
  49782. this.globalSplatIndexToSceneIndexMap = [];
  49783. this.lastBuildSplatCount = 0;
  49784. this.lastBuildScenes = [];
  49785. this.lastBuildMaxSplatCount = 0;
  49786. this.lastBuildSceneCount = 0;
  49787. this.firstRenderTime = -1;
  49788. this.finalBuild = false;
  49789. this.webGLUtils = null;
  49790. this.boundingBox = new THREE$2.Box3();
  49791. this.calculatedSceneCenter = new THREE$2.Vector3();
  49792. this.maxSplatDistanceFromSceneCenter = 0;
  49793. this.visibleRegionBufferRadius = 0;
  49794. this.visibleRegionRadius = 0;
  49795. this.visibleRegionFadeStartRadius = 0;
  49796. this.visibleRegionChanging = false;
  49797. this.splatScale = 1.0;
  49798. this.pointCloudModeEnabled = false;
  49799. this.disposed = true;
  49800. this.lastRenderer = null;
  49801. this.visible = false;
  49802. }
  49803. /**
  49804. * Dispose of only the Three.js mesh resources (geometry, material, and texture)
  49805. */
  49806. disposeMeshData() {
  49807. if (this.geometry && this.geometry !== dummyGeometry) {
  49808. this.geometry.dispose();
  49809. this.geometry = null;
  49810. }
  49811. if (this.material) {
  49812. this.material.dispose();
  49813. this.material = null;
  49814. }
  49815. }
  49816. disposeTextures() {
  49817. for (var textureKey in this.splatDataTextures) {
  49818. if (this.splatDataTextures.hasOwnProperty(textureKey)) {
  49819. var textureContainer = this.splatDataTextures[textureKey];
  49820. if (textureContainer.texture) {
  49821. textureContainer.texture.dispose();
  49822. textureContainer.texture = null;
  49823. }
  49824. }
  49825. }
  49826. this.splatDataTextures = null;
  49827. }
  49828. disposeSplatTree() {
  49829. if (this.splatTree) {
  49830. this.splatTree.dispose();
  49831. this.splatTree = null;
  49832. } else if (this.baseSplatTree) {
  49833. this.baseSplatTree.dispose();
  49834. this.baseSplatTree = null;
  49835. }
  49836. }
  49837. getSplatTree() {
  49838. return this.splatTree;
  49839. }
  49840. onSplatTreeReady(callback) {
  49841. this.onSplatTreeReadyCallback = callback;
  49842. }
  49843. /**
  49844. * Get copies of data that are necessary for splat distance computation: splat center positions and splat
  49845. * scene indexes (necessary for applying dynamic scene transformations during distance computation)
  49846. * @param {*} start The index at which to start copying data
  49847. * @param {*} end The index at which to stop copying data
  49848. * @return {object}
  49849. */
  49850. getDataForDistancesComputation(start, end) {
  49851. var centers = this.integerBasedDistancesComputation ? this.getIntegerCenters(start, end, true) : this.getFloatCenters(start, end, true);
  49852. var sceneIndexes = this.getSceneIndexes(start, end);
  49853. return {
  49854. centers,
  49855. sceneIndexes
  49856. };
  49857. }
  49858. /**
  49859. * Refresh data textures and GPU buffers with splat data from the splat buffers belonging to this mesh.
  49860. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  49861. * @return {object}
  49862. */
  49863. refreshGPUDataFromSplatBuffers(sinceLastBuildOnly) {
  49864. var splatCount = this.getSplatCount();
  49865. this.refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly);
  49866. var updateStart = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  49867. var {
  49868. centers,
  49869. sceneIndexes
  49870. } = this.getDataForDistancesComputation(updateStart, splatCount - 1);
  49871. if (this.enableDistancesComputationOnGPU) {
  49872. this.refreshGPUBuffersForDistancesComputation(centers, sceneIndexes, sinceLastBuildOnly);
  49873. }
  49874. return {
  49875. 'from': updateStart,
  49876. 'to': splatCount - 1,
  49877. 'count': splatCount - updateStart,
  49878. 'centers': centers,
  49879. 'sceneIndexes': sceneIndexes
  49880. };
  49881. }
  49882. /**
  49883. * Update the GPU buffers that are used for computing splat distances on the GPU.
  49884. * @param {Array<number>} centers Splat center positions
  49885. * @param {Array<number>} sceneIndexes Indexes of the scene to which each splat belongs
  49886. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  49887. */
  49888. refreshGPUBuffersForDistancesComputation(centers, sceneIndexes) {
  49889. var sinceLastBuildOnly = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  49890. var offset = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  49891. this.updateGPUCentersBufferForDistancesComputation(sinceLastBuildOnly, centers, offset);
  49892. this.updateGPUTransformIndexesBufferForDistancesComputation(sinceLastBuildOnly, sceneIndexes, offset);
  49893. }
  49894. /**
  49895. * Refresh data textures with data from the splat buffers for this mesh.
  49896. * @param {boolean} sinceLastBuildOnly Specify whether or not to only update for splats that have been added since the last build.
  49897. */
  49898. refreshDataTexturesFromSplatBuffers(sinceLastBuildOnly) {
  49899. if (!sinceLastBuildOnly) {
  49900. this.setupDataTextures();
  49901. } else {
  49902. this.updateDataTextures();
  49903. }
  49904. this.updateVisibleRegion(sinceLastBuildOnly);
  49905. }
  49906. setupDataTextures() {
  49907. var maxSplatCount = this.getMaxSplatCount();
  49908. var splatCount = this.getSplatCount();
  49909. this.disposeTextures();
  49910. var computeDataTextureSize = (elementsPerTexel, elementsPerSplatl) => {
  49911. var texSize = new THREE$2.Vector2(4096, 1024);
  49912. while (texSize.x * texSize.y * elementsPerTexel < maxSplatCount * elementsPerSplatl) texSize.y *= 2;
  49913. return texSize;
  49914. };
  49915. var covarianceCompressionLevel = this.getTargetCovarianceCompressionLevel();
  49916. var sphericalHarmonicsCompressionLevel = this.getTargetSphericalHarmonicsCompressionLevel();
  49917. var covariances = new Float32Array(maxSplatCount * COVARIANCES_ELEMENTS_PER_SPLAT);
  49918. var centers = new Float32Array(maxSplatCount * 3);
  49919. var colors = new Uint8Array(maxSplatCount * 4);
  49920. var SphericalHarmonicsArrayType = Float32Array;
  49921. if (sphericalHarmonicsCompressionLevel === 1) SphericalHarmonicsArrayType = Uint16Array;else if (sphericalHarmonicsCompressionLevel === 2) SphericalHarmonicsArrayType = Uint8Array;
  49922. var sphericalHarmonicsComponentCount = getSphericalHarmonicsComponentCountForDegree(this.minSphericalHarmonicsDegree);
  49923. var paddedSphericalHarmonicsComponentCount = sphericalHarmonicsComponentCount;
  49924. if (paddedSphericalHarmonicsComponentCount % 2 !== 0) paddedSphericalHarmonicsComponentCount++;
  49925. var sphericalHarmonics = this.minSphericalHarmonicsDegree ? new SphericalHarmonicsArrayType(maxSplatCount * sphericalHarmonicsComponentCount) : undefined;
  49926. this.fillSplatDataArrays(covariances, centers, colors, sphericalHarmonics, undefined, covarianceCompressionLevel, sphericalHarmonicsCompressionLevel);
  49927. // set up covariances data texture
  49928. var covTexSize = computeDataTextureSize(COVARIANCES_ELEMENTS_PER_TEXEL, 6);
  49929. var CovariancesDataType = covarianceCompressionLevel >= 1 ? Uint16Array : Float32Array;
  49930. var covariancesTextureType = covarianceCompressionLevel >= 1 ? THREE$2.HalfFloatType : THREE$2.FloatType;
  49931. var paddedCovariances = new CovariancesDataType(covTexSize.x * covTexSize.y * COVARIANCES_ELEMENTS_PER_TEXEL);
  49932. paddedCovariances.set(covariances);
  49933. var covTex = new THREE$2.DataTexture(paddedCovariances, covTexSize.x, covTexSize.y, THREE$2.RGBAFormat, covariancesTextureType);
  49934. covTex.needsUpdate = true;
  49935. this.material.uniforms.covariancesTexture.value = covTex;
  49936. this.material.uniforms.covariancesTextureSize.value.copy(covTexSize);
  49937. // set up centers/colors data texture
  49938. var centersColsTexSize = computeDataTextureSize(CENTER_COLORS_ELEMENTS_PER_TEXEL, 4);
  49939. var paddedCentersCols = new Uint32Array(centersColsTexSize.x * centersColsTexSize.y * CENTER_COLORS_ELEMENTS_PER_TEXEL);
  49940. SplatMesh.updateCenterColorsPaddedData(0, splatCount, centers, colors, paddedCentersCols);
  49941. var centersColsTex = new THREE$2.DataTexture(paddedCentersCols, centersColsTexSize.x, centersColsTexSize.y, THREE$2.RGBAIntegerFormat, THREE$2.UnsignedIntType);
  49942. centersColsTex.internalFormat = 'RGBA32UI';
  49943. centersColsTex.needsUpdate = true;
  49944. this.material.uniforms.centersColorsTexture.value = centersColsTex;
  49945. this.material.uniforms.centersColorsTextureSize.value.copy(centersColsTexSize);
  49946. this.material.uniformsNeedUpdate = true;
  49947. this.splatDataTextures = {
  49948. 'baseData': {
  49949. 'covariances': covariances,
  49950. 'centers': centers,
  49951. 'colors': colors,
  49952. 'sphericalHarmonics': sphericalHarmonics
  49953. },
  49954. 'covariances': {
  49955. 'data': paddedCovariances,
  49956. 'texture': covTex,
  49957. 'size': covTexSize,
  49958. 'compressionLevel': covarianceCompressionLevel
  49959. },
  49960. 'centerColors': {
  49961. 'data': paddedCentersCols,
  49962. 'texture': centersColsTex,
  49963. 'size': centersColsTexSize
  49964. }
  49965. };
  49966. if (sphericalHarmonics) {
  49967. var sphericalHarmonicsElementsPerTexel = 4;
  49968. var sphericalHarmonicsTexSize = computeDataTextureSize(sphericalHarmonicsElementsPerTexel, paddedSphericalHarmonicsComponentCount);
  49969. var paddedSHArraySize = sphericalHarmonicsTexSize.x * sphericalHarmonicsTexSize.y * sphericalHarmonicsElementsPerTexel;
  49970. var paddedSHArray = new SphericalHarmonicsArrayType(paddedSHArraySize);
  49971. for (var c = 0; c < splatCount; c++) {
  49972. var srcBase = sphericalHarmonicsComponentCount * c;
  49973. var destBase = paddedSphericalHarmonicsComponentCount * c;
  49974. for (var i = 0; i < sphericalHarmonicsComponentCount; i++) {
  49975. paddedSHArray[destBase + i] = sphericalHarmonics[srcBase + i];
  49976. }
  49977. }
  49978. var textureType = sphericalHarmonicsCompressionLevel === 2 ? THREE$2.UnsignedByteType : THREE$2.HalfFloatType;
  49979. var sphericalHarmonicsTex = new THREE$2.DataTexture(paddedSHArray, sphericalHarmonicsTexSize.x, sphericalHarmonicsTexSize.y, THREE$2.RGBAFormat, textureType);
  49980. sphericalHarmonicsTex.needsUpdate = true;
  49981. this.material.uniforms.sphericalHarmonicsTexture.value = sphericalHarmonicsTex;
  49982. this.material.uniforms.sphericalHarmonicsTextureSize.value.copy(sphericalHarmonicsTexSize);
  49983. if (sphericalHarmonicsCompressionLevel === 2) {
  49984. this.material.uniforms.sphericalHarmonics8BitMode.value = 1;
  49985. }
  49986. this.material.uniformsNeedUpdate = true;
  49987. this.splatDataTextures['sphericalHarmonics'] = {
  49988. 'componentCount': sphericalHarmonicsComponentCount,
  49989. 'paddedComponentCount': paddedSphericalHarmonicsComponentCount,
  49990. 'data': paddedSHArray,
  49991. 'texture': sphericalHarmonicsTex,
  49992. 'size': sphericalHarmonicsTexSize,
  49993. 'compressionLevel': sphericalHarmonicsCompressionLevel
  49994. };
  49995. }
  49996. if (this.dynamicMode) {
  49997. var transformIndexesTexSize = computeDataTextureSize(TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL, 4);
  49998. var paddedTransformIndexes = new Uint32Array(transformIndexesTexSize.x * transformIndexesTexSize.y * TRANSFORM_INDEXES_ELEMENTS_PER_TEXEL);
  49999. for (var _c = 0; _c < splatCount; _c++) paddedTransformIndexes[_c] = this.globalSplatIndexToSceneIndexMap[_c];
  50000. var transformIndexesTexture = new THREE$2.DataTexture(paddedTransformIndexes, transformIndexesTexSize.x, transformIndexesTexSize.y, THREE$2.RedIntegerFormat, THREE$2.UnsignedIntType);
  50001. transformIndexesTexture.internalFormat = 'R32UI';
  50002. transformIndexesTexture.needsUpdate = true;
  50003. this.material.uniforms.transformIndexesTexture.value = transformIndexesTexture;
  50004. this.material.uniforms.transformIndexesTextureSize.value.copy(transformIndexesTexSize);
  50005. this.material.uniformsNeedUpdate = true;
  50006. this.splatDataTextures['tansformIndexes'] = {
  50007. 'data': paddedTransformIndexes,
  50008. 'texture': transformIndexesTexture,
  50009. 'size': transformIndexesTexSize
  50010. };
  50011. }
  50012. }
  50013. updateDataTextures() {
  50014. var splatCount = this.getSplatCount();
  50015. var covarianceCompressionLevel = this.splatDataTextures['covariances'].compressionLevel;
  50016. var sphericalHarmonicsTextureDesc = this.splatDataTextures['sphericalHarmonics'];
  50017. var sphericalHarmonicsCompressionLevel = sphericalHarmonicsTextureDesc ? sphericalHarmonicsTextureDesc.compressionLevel : 0;
  50018. this.fillSplatDataArrays(this.splatDataTextures.baseData.covariances, this.splatDataTextures.baseData.centers, this.splatDataTextures.baseData.colors, this.splatDataTextures.baseData.sphericalHarmonics, undefined, covarianceCompressionLevel, sphericalHarmonicsCompressionLevel, this.lastBuildSplatCount, splatCount - 1, this.lastBuildSplatCount);
  50019. var covariancesTextureDescriptor = this.splatDataTextures['covariances'];
  50020. var paddedCovariances = covariancesTextureDescriptor.data;
  50021. var covariancesTexture = covariancesTextureDescriptor.texture;
  50022. var covarancesStartSplat = this.lastBuildSplatCount * COVARIANCES_ELEMENTS_PER_SPLAT;
  50023. var covariancesEndSplat = splatCount * COVARIANCES_ELEMENTS_PER_SPLAT;
  50024. for (var i = covarancesStartSplat; i < covariancesEndSplat; i++) {
  50025. var covariance = this.splatDataTextures.baseData.covariances[i];
  50026. paddedCovariances[i] = covariance;
  50027. }
  50028. var covariancesTextureProps = this.renderer ? this.renderer.properties.get(covariancesTexture) : null;
  50029. if (!covariancesTextureProps || !covariancesTextureProps.__webglTexture) {
  50030. covariancesTexture.needsUpdate = true;
  50031. } else {
  50032. var covaranceBytesPerElement = covarianceCompressionLevel ? 2 : 4;
  50033. this.updateDataTexture(paddedCovariances, covariancesTextureDescriptor, covariancesTextureProps, COVARIANCES_ELEMENTS_PER_TEXEL, COVARIANCES_ELEMENTS_PER_SPLAT, covaranceBytesPerElement, this.lastBuildSplatCount, splatCount - 1);
  50034. }
  50035. var centerColorsTextureDescriptor = this.splatDataTextures['centerColors'];
  50036. var paddedCenterColors = centerColorsTextureDescriptor.data;
  50037. var centerColorsTexture = centerColorsTextureDescriptor.texture;
  50038. SplatMesh.updateCenterColorsPaddedData(this.lastBuildSplatCount, splatCount, this.splatDataTextures.baseData.centers, this.splatDataTextures.baseData.colors, paddedCenterColors);
  50039. var centerColorsTextureProps = this.renderer ? this.renderer.properties.get(centerColorsTexture) : null;
  50040. if (!centerColorsTextureProps || !centerColorsTextureProps.__webglTexture) {
  50041. centerColorsTexture.needsUpdate = true;
  50042. } else {
  50043. this.updateDataTexture(paddedCenterColors, centerColorsTextureDescriptor, centerColorsTextureProps, CENTER_COLORS_ELEMENTS_PER_TEXEL, CENTER_COLORS_ELEMENTS_PER_SPLAT, 4, this.lastBuildSplatCount, splatCount - 1);
  50044. }
  50045. if (this.splatDataTextures.baseData.sphericalHarmonics) {
  50046. var sphericalHarmonicsComponentCount = sphericalHarmonicsTextureDesc.componentCount;
  50047. var paddedSphericalHarmonicsComponentCount = sphericalHarmonicsTextureDesc.paddedComponentCount;
  50048. var paddedSHArray = sphericalHarmonicsTextureDesc.data;
  50049. for (var c = this.lastBuildSplatCount; c < splatCount; c++) {
  50050. var srcBase = sphericalHarmonicsComponentCount * c;
  50051. var destBase = paddedSphericalHarmonicsComponentCount * c;
  50052. for (var _i15 = 0; _i15 < sphericalHarmonicsComponentCount; _i15++) {
  50053. paddedSHArray[destBase + _i15] = this.splatDataTextures.baseData.sphericalHarmonics[srcBase + _i15];
  50054. }
  50055. }
  50056. var sphericalHarmonicsTex = sphericalHarmonicsTextureDesc.texture;
  50057. var sphericalHarmonicsTextureProps = this.renderer ? this.renderer.properties.get(sphericalHarmonicsTex) : null;
  50058. if (!sphericalHarmonicsTextureProps || !sphericalHarmonicsTextureProps.__webglTexture) {
  50059. sphericalHarmonicsTex.needsUpdate = true;
  50060. } else {
  50061. var sphericalHarmonicsElementsPerTexel = 4;
  50062. var sphericalHarmonicsBytesPerElement = 4;
  50063. if (sphericalHarmonicsCompressionLevel === 1) sphericalHarmonicsBytesPerElement = 2;else if (sphericalHarmonicsCompressionLevel === 2) sphericalHarmonicsBytesPerElement = 1;
  50064. this.updateDataTexture(paddedSHArray, sphericalHarmonicsTextureDesc, sphericalHarmonicsTextureProps, sphericalHarmonicsElementsPerTexel, paddedSphericalHarmonicsComponentCount, sphericalHarmonicsBytesPerElement, this.lastBuildSplatCount, splatCount - 1);
  50065. }
  50066. }
  50067. if (this.dynamicMode) {
  50068. var transformIndexesTexDesc = this.splatDataTextures['tansformIndexes'];
  50069. var paddedTransformIndexes = transformIndexesTexDesc.data;
  50070. for (var _c2 = this.lastBuildSplatCount; _c2 < splatCount; _c2++) {
  50071. paddedTransformIndexes[_c2] = this.globalSplatIndexToSceneIndexMap[_c2];
  50072. }
  50073. var transformIndexesTexture = transformIndexesTexDesc.texture;
  50074. var transformIndexesTextureProps = this.renderer ? this.renderer.properties.get(transformIndexesTexture) : null;
  50075. if (!transformIndexesTextureProps || !transformIndexesTextureProps.__webglTexture) {
  50076. transformIndexesTexture.needsUpdate = true;
  50077. } else {
  50078. this.updateDataTexture(paddedTransformIndexes, transformIndexesTexDesc, transformIndexesTextureProps, 1, 1, 1, this.lastBuildSplatCount, splatCount - 1);
  50079. }
  50080. }
  50081. }
  50082. getTargetCovarianceCompressionLevel() {
  50083. return this.halfPrecisionCovariancesOnGPU ? 1 : 0;
  50084. }
  50085. getTargetSphericalHarmonicsCompressionLevel() {
  50086. return Math.max(1, this.getMaximumSplatBufferCompressionLevel());
  50087. }
  50088. getMaximumSplatBufferCompressionLevel() {
  50089. var maxCompressionLevel;
  50090. for (var i = 0; i < this.scenes.length; i++) {
  50091. var scene = this.getScene(i);
  50092. var splatBuffer = scene.splatBuffer;
  50093. if (i === 0 || splatBuffer.compressionLevel > maxCompressionLevel) {
  50094. maxCompressionLevel = splatBuffer.compressionLevel;
  50095. }
  50096. }
  50097. return maxCompressionLevel;
  50098. }
  50099. getMinimumSplatBufferCompressionLevel() {
  50100. var minCompressionLevel;
  50101. for (var i = 0; i < this.scenes.length; i++) {
  50102. var scene = this.getScene(i);
  50103. var splatBuffer = scene.splatBuffer;
  50104. if (i === 0 || splatBuffer.compressionLevel < minCompressionLevel) {
  50105. minCompressionLevel = splatBuffer.compressionLevel;
  50106. }
  50107. }
  50108. return minCompressionLevel;
  50109. }
  50110. static computeTextureUpdateRegion(startSplat, endSplat, textureWidth, elementsPerTexel, elementsPerSplat) {
  50111. var texelsPerSplat = elementsPerSplat / elementsPerTexel;
  50112. var startSplatTexels = startSplat * texelsPerSplat;
  50113. var startRow = Math.floor(startSplatTexels / textureWidth);
  50114. var startRowElement = startRow * textureWidth * elementsPerTexel;
  50115. var endSplatTexels = endSplat * texelsPerSplat;
  50116. var endRow = Math.floor(endSplatTexels / textureWidth);
  50117. var endRowEndElement = endRow * textureWidth * elementsPerTexel + textureWidth * elementsPerTexel;
  50118. return {
  50119. 'dataStart': startRowElement,
  50120. 'dataEnd': endRowEndElement,
  50121. 'startRow': startRow,
  50122. 'endRow': endRow
  50123. };
  50124. }
  50125. //局部纹理刷新
  50126. updateDataTexture(paddedData, textureDesc, textureProps, elementsPerTexel, elementsPerSplat, bytesPerElement, from, to) {
  50127. var gl = this.renderer.getContext();
  50128. var updateRegion = SplatMesh.computeTextureUpdateRegion(from, to, textureDesc.size.x, elementsPerTexel, elementsPerSplat);
  50129. var updateElementCount = updateRegion.dataEnd - updateRegion.dataStart;
  50130. var updateDataView = new paddedData.constructor(paddedData.buffer, updateRegion.dataStart * bytesPerElement, updateElementCount);
  50131. var updateHeight = updateRegion.endRow - updateRegion.startRow + 1;
  50132. var dataTexture = textureDesc.texture;
  50133. var glType = this.webGLUtils.convert(dataTexture.type);
  50134. var glFormat = this.webGLUtils.convert(dataTexture.format, dataTexture.colorSpace);
  50135. var currentTexture = gl.getParameter(gl.TEXTURE_BINDING_2D);
  50136. gl.bindTexture(gl.TEXTURE_2D, textureProps.__webglTexture);
  50137. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, updateRegion.startRow, textureDesc.size.x, updateHeight, glFormat, glType, updateDataView);
  50138. //(target, level, xoffset, yoffset, width, height, format, type, pixels);
  50139. gl.bindTexture(gl.TEXTURE_2D, currentTexture);
  50140. }
  50141. static updateCenterColorsPaddedData(to, from, centers, colors, paddedCenterColors) {
  50142. for (var c = to; c < from; c++) {
  50143. var colorsBase = c * 4;
  50144. var centersBase = c * 3;
  50145. var centerColorsBase = c * 4;
  50146. paddedCenterColors[centerColorsBase] = rgbaArrayToInteger(colors, colorsBase);
  50147. paddedCenterColors[centerColorsBase + 1] = uintEncodedFloat(centers[centersBase]);
  50148. paddedCenterColors[centerColorsBase + 2] = uintEncodedFloat(centers[centersBase + 1]);
  50149. paddedCenterColors[centerColorsBase + 3] = uintEncodedFloat(centers[centersBase + 2]);
  50150. }
  50151. }
  50152. updateVisibleRegion(sinceLastBuildOnly) {
  50153. var splatCount = this.getSplatCount();
  50154. var tempCenter = new THREE$2.Vector3();
  50155. if (!sinceLastBuildOnly) {
  50156. var avgCenter = new THREE$2.Vector3();
  50157. this.scenes.forEach(scene => {
  50158. avgCenter.add(scene.splatBuffer.sceneCenter);
  50159. });
  50160. avgCenter.multiplyScalar(1.0 / this.scenes.length);
  50161. this.calculatedSceneCenter.copy(avgCenter);
  50162. this.material.uniforms.sceneCenter.value.copy(this.calculatedSceneCenter);
  50163. this.material.uniformsNeedUpdate = true;
  50164. }
  50165. var startSplatFormMaxDistanceCalc = sinceLastBuildOnly ? this.lastBuildSplatCount : 0;
  50166. for (var i = startSplatFormMaxDistanceCalc; i < splatCount; i++) {
  50167. this.getSplatCenter(i, tempCenter, false);
  50168. var distFromCSceneCenter = tempCenter.sub(this.calculatedSceneCenter).length();
  50169. if (distFromCSceneCenter > this.maxSplatDistanceFromSceneCenter) this.maxSplatDistanceFromSceneCenter = distFromCSceneCenter;
  50170. }
  50171. if (this.maxSplatDistanceFromSceneCenter - this.visibleRegionBufferRadius > VISIBLE_REGION_EXPANSION_DELTA) {
  50172. this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter;
  50173. this.visibleRegionRadius = Math.max(this.visibleRegionBufferRadius - VISIBLE_REGION_EXPANSION_DELTA, 0.0);
  50174. }
  50175. if (this.finalBuild) this.visibleRegionRadius = this.visibleRegionBufferRadius = this.maxSplatDistanceFromSceneCenter;
  50176. this.updateVisibleRegionFadeDistance();
  50177. }
  50178. updateVisibleRegionFadeDistance() {
  50179. var sceneRevealMode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : SceneRevealMode.Default;
  50180. var fastFadeRate = SCENE_FADEIN_RATE_FAST;
  50181. var gradualFadeRate = SCENE_FADEIN_RATE_GRADUAL;
  50182. var defaultFadeInRate = this.finalBuild ? fastFadeRate : gradualFadeRate;
  50183. var fadeInRate = sceneRevealMode === SceneRevealMode.Default ? defaultFadeInRate : gradualFadeRate;
  50184. this.visibleRegionFadeStartRadius = (this.visibleRegionRadius - this.visibleRegionFadeStartRadius) * fadeInRate + this.visibleRegionFadeStartRadius;
  50185. var fadeInPercentage = this.visibleRegionBufferRadius > 0 ? this.visibleRegionFadeStartRadius / this.visibleRegionBufferRadius : 0;
  50186. var fadeInComplete = fadeInPercentage > 0.99;
  50187. var shaderFadeInComplete = fadeInComplete || sceneRevealMode === SceneRevealMode.Instant ? 1 : 0;
  50188. this.material.uniforms.visibleRegionFadeStartRadius.value = this.visibleRegionFadeStartRadius;
  50189. this.material.uniforms.visibleRegionRadius.value = this.visibleRegionRadius;
  50190. this.material.uniforms.firstRenderTime.value = this.firstRenderTime;
  50191. this.material.uniforms.currentTime.value = performance.now();
  50192. this.material.uniforms.fadeInComplete.value = shaderFadeInComplete;
  50193. this.material.uniformsNeedUpdate = true;
  50194. this.visibleRegionChanging = !fadeInComplete;
  50195. }
  50196. /**
  50197. * Set the indexes of splats that should be rendered; should be sorted in desired render order.
  50198. * @param {Uint32Array} globalIndexes Sorted index list of splats to be rendered
  50199. * @param {number} renderSplatCount Total number of splats to be rendered. Necessary because we may not want to render
  50200. * every splat.
  50201. */
  50202. updateRenderIndexes(globalIndexes, renderSplatCount) {
  50203. //仅渲染前renderSplatCount个点,在前renderSplatCount的顺序是否可以打乱?
  50204. var geometry = this.geometry;
  50205. geometry.attributes.splatIndex.set(globalIndexes);
  50206. geometry.attributes.splatIndex.needsUpdate = true;
  50207. if (renderSplatCount > 0 && this.firstRenderTime === -1) this.firstRenderTime = performance.now();
  50208. geometry.instanceCount = renderSplatCount;
  50209. } //注:假设全部点都渲染的话,是无所谓index的顺序的,可以直接第0个为0,第n个为n……
  50210. /**
  50211. * Update the transforms for each scene in this splat mesh from their individual components (position,
  50212. * quaternion, and scale)
  50213. */
  50214. updateTransforms() {
  50215. for (var i = 0; i < this.scenes.length; i++) {
  50216. var scene = this.getScene(i);
  50217. scene.updateTransform();
  50218. }
  50219. }
  50220. setSplatScale() {
  50221. var splatScale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  50222. this.splatScale = splatScale;
  50223. this.material.uniforms.splatScale.value = splatScale;
  50224. this.material.uniformsNeedUpdate = true;
  50225. }
  50226. getSplatScale() {
  50227. return this.splatScale;
  50228. }
  50229. setPointCloudModeEnabled(enabled) {
  50230. this.pointCloudModeEnabled = enabled;
  50231. this.material.uniforms.pointCloudModeEnabled.value = enabled ? 1 : 0;
  50232. this.material.uniformsNeedUpdate = true;
  50233. }
  50234. getPointCloudModeEnabled() {
  50235. return this.pointCloudModeEnabled;
  50236. }
  50237. getSplatDataTextures() {
  50238. return this.splatDataTextures;
  50239. }
  50240. getSplatCount() {
  50241. return SplatMesh.getTotalSplatCountForScenes(this.scenes);
  50242. }
  50243. static getTotalSplatCountForScenes(scenes) {
  50244. var totalSplatCount = 0;
  50245. for (var scene of scenes) {
  50246. if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getSplatCount();
  50247. }
  50248. return totalSplatCount;
  50249. }
  50250. static getTotalSplatCountForSplatBuffers(splatBuffers) {
  50251. var totalSplatCount = 0;
  50252. for (var splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getSplatCount();
  50253. return totalSplatCount;
  50254. }
  50255. getMaxSplatCount() {
  50256. return SplatMesh.getTotalMaxSplatCountForScenes(this.scenes);
  50257. }
  50258. static getTotalMaxSplatCountForScenes(scenes) {
  50259. var totalSplatCount = 0;
  50260. for (var scene of scenes) {
  50261. if (scene && scene.splatBuffer) totalSplatCount += scene.splatBuffer.getMaxSplatCount();
  50262. }
  50263. return totalSplatCount;
  50264. }
  50265. static getTotalMaxSplatCountForSplatBuffers(splatBuffers) {
  50266. var totalSplatCount = 0;
  50267. for (var splatBuffer of splatBuffers) totalSplatCount += splatBuffer.getMaxSplatCount();
  50268. return totalSplatCount;
  50269. }
  50270. disposeDistancesComputationGPUResources() {
  50271. if (!this.renderer) return;
  50272. var gl = this.renderer.getContext();
  50273. if (this.distancesTransformFeedback.vao) {
  50274. gl.deleteVertexArray(this.distancesTransformFeedback.vao);
  50275. this.distancesTransformFeedback.vao = null;
  50276. }
  50277. if (this.distancesTransformFeedback.program) {
  50278. gl.deleteProgram(this.distancesTransformFeedback.program);
  50279. gl.deleteShader(this.distancesTransformFeedback.vertexShader);
  50280. gl.deleteShader(this.distancesTransformFeedback.fragmentShader);
  50281. this.distancesTransformFeedback.program = null;
  50282. this.distancesTransformFeedback.vertexShader = null;
  50283. this.distancesTransformFeedback.fragmentShader = null;
  50284. }
  50285. this.disposeDistancesComputationGPUBufferResources();
  50286. if (this.distancesTransformFeedback.id) {
  50287. gl.deleteTransformFeedback(this.distancesTransformFeedback.id);
  50288. this.distancesTransformFeedback.id = null;
  50289. }
  50290. }
  50291. disposeDistancesComputationGPUBufferResources() {
  50292. if (!this.renderer) return;
  50293. var gl = this.renderer.getContext();
  50294. if (this.distancesTransformFeedback.centersBuffer) {
  50295. this.distancesTransformFeedback.centersBuffer = null;
  50296. gl.deleteBuffer(this.distancesTransformFeedback.centersBuffer);
  50297. }
  50298. if (this.distancesTransformFeedback.outDistancesBuffer) {
  50299. gl.deleteBuffer(this.distancesTransformFeedback.outDistancesBuffer);
  50300. this.distancesTransformFeedback.outDistancesBuffer = null;
  50301. }
  50302. }
  50303. /**
  50304. * Set the Three.js renderer used by this splat mesh
  50305. * @param {THREE.WebGLRenderer} renderer Instance of THREE.WebGLRenderer
  50306. */
  50307. setRenderer(renderer) {
  50308. if (renderer !== this.renderer) {
  50309. this.renderer = renderer;
  50310. var gl = this.renderer.getContext();
  50311. var extensions = new WebGLExtensions$1(gl);
  50312. var capabilities = new WebGLCapabilities$1(gl, extensions, {});
  50313. extensions.init(capabilities);
  50314. this.webGLUtils = new THREE$2.WebGLUtils(gl, extensions, capabilities);
  50315. if (this.enableDistancesComputationOnGPU && this.getSplatCount() > 0) {
  50316. this.setupDistancesComputationTransformFeedback();
  50317. var {
  50318. centers: _centers,
  50319. sceneIndexes
  50320. } = this.getDataForDistancesComputation(0, this.getSplatCount() - 1);
  50321. this.refreshGPUBuffersForDistancesComputation(_centers, sceneIndexes);
  50322. }
  50323. }
  50324. }
  50325. /**
  50326. * Refresh GPU buffers used for computing splat distances with centers data from the scenes for this mesh.
  50327. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill
  50328. * @param {Array<number>} centers The splat centers data
  50329. * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats
  50330. */
  50331. updateGPUCentersBufferForDistancesComputation(isUpdate, centers, offsetSplats) {
  50332. if (!this.renderer) return;
  50333. var gl = this.renderer.getContext();
  50334. var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  50335. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  50336. var ArrayType = this.integerBasedDistancesComputation ? Uint32Array : Float32Array;
  50337. var attributeBytesPerCenter = 16;
  50338. var subBufferOffset = offsetSplats * attributeBytesPerCenter;
  50339. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.centersBuffer);
  50340. if (isUpdate) {
  50341. gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, centers);
  50342. } else {
  50343. var maxArray = new ArrayType(this.getMaxSplatCount() * attributeBytesPerCenter);
  50344. maxArray.set(centers);
  50345. gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW);
  50346. }
  50347. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  50348. if (currentVao) gl.bindVertexArray(currentVao);
  50349. }
  50350. /**
  50351. * Refresh GPU buffers used for pre-computing splat distances with centers data from the scenes for this mesh.
  50352. * @param {boolean} isUpdate Specify whether or not to update the GPU buffer or to initialize & fill
  50353. * @param {Array<number>} transformIndexes The splat transform indexes
  50354. * @param {number} offsetSplats Offset in the GPU buffer at which to start updating data, specified in splats
  50355. */
  50356. updateGPUTransformIndexesBufferForDistancesComputation(isUpdate, transformIndexes, offsetSplats) {
  50357. if (!this.renderer || !this.dynamicMode) return;
  50358. var gl = this.renderer.getContext();
  50359. var currentVao = gl.getParameter(gl.VERTEX_ARRAY_BINDING);
  50360. gl.bindVertexArray(this.distancesTransformFeedback.vao);
  50361. var subBufferOffset = offsetSplats * 4;
  50362. gl.bindBuffer(gl.ARRAY_BUFFER, this.distancesTransformFeedback.transformIndexesBuffer);
  50363. if (isUpdate) {
  50364. gl.bufferSubData(gl.ARRAY_BUFFER, subBufferOffset, transformIndexes);
  50365. } else {
  50366. var maxArray = new Uint32Array(this.getMaxSplatCount() * 4);
  50367. maxArray.set(transformIndexes);
  50368. gl.bufferData(gl.ARRAY_BUFFER, maxArray, gl.STATIC_DRAW);
  50369. }
  50370. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  50371. if (currentVao) gl.bindVertexArray(currentVao);
  50372. }
  50373. /**
  50374. * Get a typed array containing a mapping from global splat indexes to their scene index.
  50375. * @param {number} start Starting splat index to store
  50376. * @param {number} end Ending splat index to store
  50377. * @return {Uint32Array}
  50378. */
  50379. getSceneIndexes(start, end) {
  50380. var sceneIndexes;
  50381. var fillCount = end - start + 1;
  50382. sceneIndexes = new Uint32Array(fillCount);
  50383. for (var i = start; i <= end; i++) {
  50384. sceneIndexes[i] = this.globalSplatIndexToSceneIndexMap[i];
  50385. }
  50386. return sceneIndexes;
  50387. }
  50388. /**
  50389. * Given a global splat index, return corresponding local data (splat buffer, index of splat in that splat
  50390. * buffer, and the corresponding transform)
  50391. * @param {number} globalIndex Global splat index
  50392. * @param {object} paramsObj Object in which to store local data
  50393. * @param {boolean} returnSceneTransform By default, the transform of the scene to which the splat at 'globalIndex' belongs will be
  50394. * returned via the 'sceneTransform' property of 'paramsObj' only if the splat mesh is static.
  50395. * If 'returnSceneTransform' is true, the 'sceneTransform' property will always contain the scene
  50396. * transform, and if 'returnSceneTransform' is false, the 'sceneTransform' property will always
  50397. * be null.
  50398. */
  50399. getLocalSplatParameters(globalIndex, paramsObj, returnSceneTransform) {
  50400. if (returnSceneTransform === undefined || returnSceneTransform === null) {
  50401. returnSceneTransform = this.dynamicMode ? false : true;
  50402. }
  50403. paramsObj.splatBuffer = this.getSplatBufferForSplat(globalIndex);
  50404. paramsObj.localIndex = this.getSplatLocalIndex(globalIndex);
  50405. paramsObj.sceneTransform = returnSceneTransform ? this.getSceneTransformForSplat(globalIndex) : null;
  50406. }
  50407. /**
  50408. * Fill arrays with splat data and apply transforms if appropriate. Each array is optional.
  50409. * @param {Float32Array} covariances Target storage for splat covariances
  50410. * @param {Float32Array} centers Target storage for splat centers
  50411. * @param {Uint8Array} colors Target storage for splat colors
  50412. * @param {Float32Array} sphericalHarmonics Target storage for spherical harmonics
  50413. * @param {boolean} applySceneTransform By default, scene transforms are applied to relevant splat data only if the splat mesh is
  50414. * static. If 'applySceneTransform' is true, scene transforms will always be applied and if
  50415. * it is false, they will never be applied. If undefined, the default behavior will apply.
  50416. * @param {number} covarianceCompressionLevel The compression level for covariances in the destination array
  50417. * @param {number} sphericalHarmonicsCompressionLevel The compression level for spherical harmonics in the destination array
  50418. * @param {number} srcStart The start location from which to pull source data
  50419. * @param {number} srcEnd The end location from which to pull source data
  50420. * @param {number} destStart The start location from which to write data
  50421. */
  50422. fillSplatDataArrays(covariances, centers, colors, sphericalHarmonics, applySceneTransform) {
  50423. var covarianceCompressionLevel = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0;
  50424. var sphericalHarmonicsCompressionLevel = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 1;
  50425. var srcStart = arguments.length > 7 ? arguments[7] : undefined;
  50426. var srcEnd = arguments.length > 8 ? arguments[8] : undefined;
  50427. var destStart = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : 0;
  50428. for (var i = 0; i < this.scenes.length; i++) {
  50429. if (applySceneTransform === undefined || applySceneTransform === null) {
  50430. applySceneTransform = this.dynamicMode ? false : true;
  50431. }
  50432. var scene = this.getScene(i);
  50433. var splatBuffer = scene.splatBuffer;
  50434. var sceneTransform = applySceneTransform ? scene.transform : null;
  50435. if (covariances) {
  50436. splatBuffer.fillSplatCovarianceArray(covariances, sceneTransform, srcStart, srcEnd, destStart, covarianceCompressionLevel);
  50437. }
  50438. if (centers) splatBuffer.fillSplatCenterArray(centers, sceneTransform, srcStart, srcEnd, destStart);
  50439. if (colors) splatBuffer.fillSplatColorArray(colors, scene.minimumAlpha, srcStart, srcEnd, destStart);
  50440. if (sphericalHarmonics) {
  50441. splatBuffer.fillSphericalHarmonicsArray(sphericalHarmonics, this.minSphericalHarmonicsDegree, sceneTransform, srcStart, srcEnd, destStart, sphericalHarmonicsCompressionLevel);
  50442. }
  50443. destStart += splatBuffer.getSplatCount();
  50444. }
  50445. }
  50446. /**
  50447. * Convert splat centers, which are floating point values, to an array of integers and multiply
  50448. * each by 1000. Centers will get transformed as appropriate before conversion to integer.
  50449. * @param {number} start The index at which to start retrieving data
  50450. * @param {number} end The index at which to stop retrieving data
  50451. * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values
  50452. * @return {Int32Array}
  50453. */
  50454. getIntegerCenters(start, end) {
  50455. var padFour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  50456. var splatCount = end - start + 1;
  50457. var floatCenters = new Float32Array(splatCount * 3);
  50458. this.fillSplatDataArrays(null, floatCenters, null, null, undefined, undefined, undefined, start);
  50459. var intCenters;
  50460. var componentCount = padFour ? 4 : 3;
  50461. intCenters = new Int32Array(splatCount * componentCount);
  50462. for (var i = 0; i < splatCount; i++) {
  50463. for (var t = 0; t < 3; t++) {
  50464. intCenters[i * componentCount + t] = Math.round(floatCenters[i * 3 + t] * 1000.0);
  50465. }
  50466. if (padFour) intCenters[i * componentCount + 3] = 1000;
  50467. }
  50468. return intCenters;
  50469. }
  50470. /**
  50471. * Returns an array of splat centers, transformed as appropriate, optionally padded.
  50472. * @param {number} start The index at which to start retrieving data
  50473. * @param {number} end The index at which to stop retrieving data
  50474. * @param {boolean} padFour Enforce alignment of 4 by inserting a 1 after every 3 values
  50475. * @return {Float32Array}
  50476. */
  50477. getFloatCenters(start, end) {
  50478. var padFour = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  50479. var splatCount = end - start + 1;
  50480. var floatCenters = new Float32Array(splatCount * 3);
  50481. this.fillSplatDataArrays(null, floatCenters, null, null, undefined, undefined, undefined, start);
  50482. if (!padFour) return floatCenters;
  50483. var paddedFloatCenters = new Float32Array(splatCount * 4);
  50484. for (var i = 0; i < splatCount; i++) {
  50485. for (var t = 0; t < 3; t++) {
  50486. paddedFloatCenters[i * 4 + t] = floatCenters[i * 3 + t];
  50487. }
  50488. paddedFloatCenters[i * 4 + 3] = 1.0;
  50489. }
  50490. return paddedFloatCenters;
  50491. }
  50492. /**
  50493. * Store the transform of the scene at 'sceneIndex' in 'outTransform'.
  50494. * @param {number} sceneIndex Index of the desired scene
  50495. * @param {THREE.Matrix4} outTransform Instance of THREE.Matrix4 in which to store the scene's transform
  50496. */
  50497. getSceneTransform(sceneIndex, outTransform) {
  50498. var scene = this.getScene(sceneIndex);
  50499. scene.updateTransform();
  50500. outTransform.copy(scene.transform);
  50501. }
  50502. /**
  50503. * Get the scene at 'sceneIndex'.
  50504. * @param {number} sceneIndex Index of the desired scene
  50505. * @return {SplatScene}
  50506. */
  50507. getScene(sceneIndex) {
  50508. if (sceneIndex < 0 || sceneIndex >= this.scenes.length) {
  50509. throw new Error('SplatMesh::getScene() -> Invalid scene index.');
  50510. }
  50511. return this.scenes[sceneIndex];
  50512. }
  50513. getSplatBufferForSplat(globalIndex) {
  50514. return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).splatBuffer;
  50515. }
  50516. getSceneIndexForSplat(globalIndex) {
  50517. return this.globalSplatIndexToSceneIndexMap[globalIndex];
  50518. }
  50519. getSceneTransformForSplat(globalIndex) {
  50520. return this.getScene(this.globalSplatIndexToSceneIndexMap[globalIndex]).transform;
  50521. }
  50522. getSplatLocalIndex(globalIndex) {
  50523. return this.globalSplatIndexToLocalSplatIndexMap[globalIndex];
  50524. }
  50525. static getIntegerMatrixArray(matrix) {
  50526. var matrixElements = matrix.elements;
  50527. var intMatrixArray = [];
  50528. for (var i = 0; i < 16; i++) {
  50529. intMatrixArray[i] = Math.round(matrixElements[i] * 1000.0);
  50530. }
  50531. return intMatrixArray;
  50532. }
  50533. }
  50534. var SorterWasm = "AGFzbQEAAAAADAZkeWxpbmsAAAAAAAEbA2AAAGAQf39/f39/f39/f39/f39/fwBgAAF/AhIBA2VudgZtZW1vcnkCAwCAgAQDBAMAAQIHOQMRX193YXNtX2NhbGxfY3RvcnMAAAtzb3J0SW5kZXhlcwABE2Vtc2NyaXB0ZW5fdGxzX2luaXQAAgrHEAMDAAELuxAFAXwDewJ/A30CfiALIAprIQwCQCAOBEAgDQRAQfj///8HIQ5BiICAgHghDSALIAxNDQIgDCEBA0AgAyABQQJ0IgVqIAIgACAFaigCAEECdGooAgAiBTYCACAFIA4gBSAOSBshDiAFIA0gBSANShshDSABQQFqIgEgC0cNAAsMAgsgDwRAQfj///8HIQ5BiICAgHghDSALIAxNDQJBfyEPIAwhAgNAIA8gByAAIAJBAnQiFGooAgAiFUECdGooAgAiCkcEQAJ+IAX9CQIIIAggCkEGdGoiD/0JAgAgDyoCEP0gASAPKgIg/SACIA8qAjD9IAP95gEgBf0JAhggD/0JAgQgDyoCFP0gASAPKgIk/SACIA8qAjT9IAP95gH95AEgBf0JAiggD/0JAgggDyoCGP0gASAPKgIo/SACIA8qAjj9IAP95gH95AEgBf0JAjggD/0JAgwgDyoCHP0gASAPKgIs/SACIA8qAjz9IAP95gH95AEiEf0fArv9FCAR/R8Du/0iAf0MAAAAAABAj0AAAAAAAECPQCIS/fIBIhP9IQEiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwshGQJ+IBP9IQAiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwv9EiETAn4gEf0fALv9FCAR/R8Bu/0iASAS/fIBIhH9IQEiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwshGiATIBn9HgEhEgJ+IBH9IQAiEJlEAAAAAAAA4ENjBEAgELAMAQtCgICAgICAgICAfwv9EiAa/R4BIBL9DQABAgMICQoLEBESExgZGhshEiAKIQ8LIAMgFGogASAVQQR0av0AAAAgEv21ASIR/RsAIBH9GwFqIBH9GwJqIBH9GwNqIgo2AgAgCiAOIAogDkgbIQ4gCiANIAogDUobIQ0gAkEBaiICIAtHDQALDAILAn8gBSoCGLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEKAn8gBSoCCLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyECAn8gBSoCKLtEAAAAAABAj0CiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyEFQfj///8HIQ5BiICAgHghDSALIAxNDQEgAv0RIAr9HAEgBf0cAiESIAwhBQNAIAMgBUECdCICaiABIAAgAmooAgBBBHRq/QAAACAS/bUBIhH9GwAgEf0bAWogEf0bAmoiAjYCACACIA4gAiAOSBshDiACIA0gAiANShshDSAFQQFqIgUgC0cNAAsMAQsgDQRAQfj///8HIQ5BiICAgHghDSALIAxNDQEgDCEBA0AgAyABQQJ0IgVqAn8gAiAAIAVqKAIAQQJ0aioCALtEAAAAAAAAsECiIhCZRAAAAAAAAOBBYwRAIBCqDAELQYCAgIB4CyIKNgIAIAogDiAKIA5IGyEOIAogDSAKIA1KGyENIAFBAWoiASALRw0ACwwBCwJAIA9FBEAgCyAMSw0BQYiAgIB4IQ1B+P///wchDgwCC0H4////ByEOQYiAgIB4IQ0gCyAMTQ0BQX8hDyAMIQIDQCAPIAcgACACQQJ0IhRqKAIAQQJ0IhVqKAIAIgpHBEAgBf0JAgggCCAKQQZ0aiIP/QkCACAPKgIQ/SABIA8qAiD9IAIgDyoCMP0gA/3mASAF/QkCGCAP/QkCBCAPKgIU/SABIA8qAiT9IAIgDyoCNP0gA/3mAf3kASAF/QkCKCAP/QkCCCAPKgIY/SABIA8qAij9IAIgDyoCOP0gA/3mAf3kASAF/QkCOCAP/QkCDCAPKgIc/SABIA8qAiz9IAIgDyoCPP0gA/3mAf3kASERIAohDwsgAyAUagJ/IBEgASAVQQJ0IgpqKQIA/RL95gEiEv0fACAS/R8BkiARIBH9DQgJCgsMDQ4PAAAAAAAAAAAgASAKQQhyaikCAP0S/eYBIhL9HwCSIBL9HwGSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIgo2AgAgCiAOIAogDkgbIQ4gCiANIAogDUobIQ0gAkEBaiICIAtHDQALDAELIAUqAighFiAFKgIYIRcgBSoCCCEYQfj///8HIQ5BiICAgHghDSAMIQUDQAJ/IBggASAAIAVBAnQiB2ooAgBBBHRqIgIqAgCUIBcgAioCBJSSIBYgAioCCJSSu0QAAAAAAACwQKIiEJlEAAAAAAAA4EFjBEAgEKoMAQtBgICAgHgLIQogAyAHaiAKNgIAIAogDiAKIA5IGyEOIAogDSAKIA1KGyENIAVBAWoiBSALRw0ACwsgCyAMSwRAIAlBAWuzIA2yIA6yk5UhFiAMIQ0DQAJ/IBYgAyANQQJ0aiIBKAIAIA5rspQiF4tDAAAAT10EQCAXqAwBC0GAgICAeAshCiABIAo2AgAgBCAKQQJ0aiIBIAEoAgBBAWo2AgAgDUEBaiINIAtHDQALCyAJQQJPBEAgBCgCACENQQEhDgNAIAQgDkECdGoiASABKAIAIA1qIg02AgAgDkEBaiIOIAlHDQALCyAMQQBKBEAgDCEOA0AgBiAOQQFrIgFBAnQiAmogACACaigCADYCACAOQQFKIQIgASEOIAINAAsLIAsgDEoEQCALIQ4DQCAGIAsgBCADIA5BAWsiDkECdCIBaigCAEECdGoiAigCACIFa0ECdGogACABaigCADYCACACIAVBAWs2AgAgDCAOSA0ACwsLBABBAAs=";
  50535. //sortIndexes 按照深度排序
  50536. function sortWorker(self) {
  50537. var wasmInstance;
  50538. var wasmMemory;
  50539. var useSharedMemory;
  50540. var integerBasedSort;
  50541. var dynamicMode;
  50542. var splatCount;
  50543. var indexesToSortOffset; //存储首地址
  50544. var sortedIndexesOffset;
  50545. var transformIndexesOffset;
  50546. var transformsOffset;
  50547. var precomputedDistancesOffset;
  50548. var mappedDistancesOffset;
  50549. var frequenciesOffset;
  50550. var centersOffset;
  50551. var modelViewProjOffset;
  50552. var countsZero;
  50553. var sortedIndexesOut;
  50554. var Constants;
  50555. function sort(splatSortCount, splatRenderCount, modelViewProj, usePrecomputedDistances, copyIndexesToSort, copyPrecomputedDistances, copyTransforms) {
  50556. var sortStartTime = performance.now();
  50557. if (!useSharedMemory) {
  50558. var indexesToSort = new Uint32Array(wasmMemory, indexesToSortOffset, copyIndexesToSort.byteLength / Constants.BytesPerInt);
  50559. indexesToSort.set(copyIndexesToSort);
  50560. var transforms = new Float32Array(wasmMemory, transformsOffset, copyTransforms.byteLength / Constants.BytesPerFloat);
  50561. transforms.set(copyTransforms);
  50562. if (usePrecomputedDistances) {
  50563. var precomputedDistances;
  50564. if (integerBasedSort) {
  50565. precomputedDistances = new Int32Array(wasmMemory, precomputedDistancesOffset, copyPrecomputedDistances.byteLength / Constants.BytesPerInt);
  50566. } else {
  50567. precomputedDistances = new Float32Array(wasmMemory, precomputedDistancesOffset, copyPrecomputedDistances.byteLength / Constants.BytesPerFloat);
  50568. }
  50569. precomputedDistances.set(copyPrecomputedDistances);
  50570. }
  50571. }
  50572. if (!countsZero) countsZero = new Uint32Array(Constants.DepthMapRange);
  50573. new Float32Array(wasmMemory, modelViewProjOffset, 16).set(modelViewProj); //由于新数组已经与 WebAssembly 内存关联,实际上是将 modelViewProj 的数据复制到了 WebAssembly 内存的指定位置。
  50574. new Uint32Array(wasmMemory, frequenciesOffset, Constants.DepthMapRange).set(countsZero);
  50575. wasmInstance.exports.sortIndexes(indexesToSortOffset, centersOffset, precomputedDistancesOffset, mappedDistancesOffset, frequenciesOffset, modelViewProjOffset, sortedIndexesOffset, transformIndexesOffset, transformsOffset, Constants.DepthMapRange, splatSortCount, splatRenderCount, splatCount, usePrecomputedDistances, integerBasedSort, dynamicMode);
  50576. var sortMessage = {
  50577. 'sortDone': true,
  50578. 'splatSortCount': splatSortCount,
  50579. 'splatRenderCount': splatRenderCount,
  50580. 'sortTime': 0
  50581. };
  50582. if (!useSharedMemory) {
  50583. var sortedIndexes = new Uint32Array(wasmMemory, sortedIndexesOffset, splatRenderCount);
  50584. if (!sortedIndexesOut || sortedIndexesOut.length < splatRenderCount) {
  50585. sortedIndexesOut = new Uint32Array(splatRenderCount);
  50586. }
  50587. sortedIndexesOut.set(sortedIndexes);
  50588. sortMessage.sortedIndexes = sortedIndexesOut;
  50589. }
  50590. var sortEndTime = performance.now();
  50591. sortMessage.sortTime = sortEndTime - sortStartTime;
  50592. self.postMessage(sortMessage);
  50593. }
  50594. self.onmessage = e => {
  50595. if (e.data.centers) {
  50596. //填入坐标数据
  50597. centers = e.data.centers;
  50598. transformIndexes = e.data.transformIndexes;
  50599. if (integerBasedSort) {
  50600. new Int32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerInt * 4, e.data.range.count * 4).set(new Int32Array(centers));
  50601. } else {
  50602. new Float32Array(wasmMemory, centersOffset + e.data.range.from * Constants.BytesPerFloat * 4, e.data.range.count * 4).set(new Float32Array(centers));
  50603. }
  50604. if (dynamicMode) {
  50605. new Uint32Array(wasmMemory, transformIndexesOffset + e.data.range.from * 4, e.data.range.count).set(new Uint32Array(transformIndexes));
  50606. }
  50607. self.postMessage({
  50608. 'centerDataSet': true
  50609. });
  50610. } else if (e.data.sort) {
  50611. //请求sort
  50612. var renderCount = e.data.sort.splatRenderCount || 0;
  50613. var sortCount = e.data.sort.splatSortCount || 0;
  50614. var usePrecomputedDistances = e.data.sort.usePrecomputedDistances;
  50615. var copyIndexesToSort;
  50616. var copyPrecomputedDistances;
  50617. var copyTransforms;
  50618. if (!useSharedMemory) {
  50619. copyIndexesToSort = e.data.sort.indexesToSort;
  50620. copyTransforms = e.data.sort.transforms;
  50621. if (usePrecomputedDistances) copyPrecomputedDistances = e.data.sort.precomputedDistances;
  50622. }
  50623. sort(sortCount, renderCount, e.data.sort.modelViewProj, usePrecomputedDistances, copyIndexesToSort, copyPrecomputedDistances, copyTransforms);
  50624. } else if (e.data.init) {
  50625. //初始化 分配空间
  50626. // Yep, this is super hacky and gross :(
  50627. Constants = e.data.init.Constants;
  50628. splatCount = e.data.init.splatCount;
  50629. useSharedMemory = e.data.init.useSharedMemory;
  50630. integerBasedSort = e.data.init.integerBasedSort;
  50631. dynamicMode = e.data.init.dynamicMode;
  50632. var CENTERS_BYTES_PER_ENTRY = integerBasedSort ? Constants.BytesPerInt * 4 : Constants.BytesPerFloat * 4;
  50633. var sorterWasmBytes = new Uint8Array(e.data.init.sorterWasmBytes);
  50634. var matrixSize = 16 * Constants.BytesPerFloat;
  50635. var memoryRequiredForIndexesToSort = splatCount * Constants.BytesPerInt;
  50636. var memoryRequiredForCenters = splatCount * CENTERS_BYTES_PER_ENTRY;
  50637. var memoryRequiredForModelViewProjectionMatrix = matrixSize;
  50638. var memoryRequiredForPrecomputedDistances = integerBasedSort ? splatCount * Constants.BytesPerInt : splatCount * Constants.BytesPerFloat;
  50639. var memoryRequiredForMappedDistances = splatCount * Constants.BytesPerInt;
  50640. var memoryRequiredForSortedIndexes = splatCount * Constants.BytesPerInt;
  50641. var memoryRequiredForIntermediateSortBuffers = Constants.DepthMapRange * Constants.BytesPerInt * 2;
  50642. var memoryRequiredforTransformIndexes = dynamicMode ? splatCount * Constants.BytesPerInt : 0;
  50643. var memoryRequiredforTransforms = dynamicMode ? Constants.MaxScenes * matrixSize : 0;
  50644. var extraMemory = Constants.MemoryPageSize * 32;
  50645. var totalRequiredMemory = memoryRequiredForIndexesToSort + memoryRequiredForCenters + memoryRequiredForModelViewProjectionMatrix + memoryRequiredForPrecomputedDistances + memoryRequiredForMappedDistances + memoryRequiredForIntermediateSortBuffers + memoryRequiredForSortedIndexes + memoryRequiredforTransformIndexes + memoryRequiredforTransforms + extraMemory;
  50646. var totalPagesRequired = Math.floor(totalRequiredMemory / Constants.MemoryPageSize) + 1;
  50647. var sorterWasmImport = {
  50648. module: {},
  50649. env: {
  50650. memory: new WebAssembly.Memory({
  50651. initial: totalPagesRequired * 2,
  50652. //创建一个初始大小为 .. 页(每页64KiB)的内存实例
  50653. maximum: totalPagesRequired * 4,
  50654. shared: true
  50655. })
  50656. }
  50657. };
  50658. WebAssembly.compile(sorterWasmBytes).then(wasmModule => {
  50659. return WebAssembly.instantiate(wasmModule, sorterWasmImport);
  50660. }).then(instance => {
  50661. wasmInstance = instance;
  50662. indexesToSortOffset = 0;
  50663. centersOffset = indexesToSortOffset + memoryRequiredForIndexesToSort;
  50664. modelViewProjOffset = centersOffset + memoryRequiredForCenters;
  50665. precomputedDistancesOffset = modelViewProjOffset + memoryRequiredForModelViewProjectionMatrix;
  50666. mappedDistancesOffset = precomputedDistancesOffset + memoryRequiredForPrecomputedDistances;
  50667. frequenciesOffset = mappedDistancesOffset + memoryRequiredForMappedDistances;
  50668. sortedIndexesOffset = frequenciesOffset + memoryRequiredForIntermediateSortBuffers;
  50669. transformIndexesOffset = sortedIndexesOffset + memoryRequiredForSortedIndexes;
  50670. transformsOffset = transformIndexesOffset + memoryRequiredforTransformIndexes;
  50671. wasmMemory = sorterWasmImport.env.memory.buffer; //SharedArrayBuffer
  50672. if (useSharedMemory) {
  50673. self.postMessage({
  50674. 'sortSetupPhase1Complete': true,
  50675. 'indexesToSortBuffer': wasmMemory,
  50676. 'indexesToSortOffset': indexesToSortOffset,
  50677. 'sortedIndexesBuffer': wasmMemory,
  50678. //整理好的indexes
  50679. 'sortedIndexesOffset': sortedIndexesOffset,
  50680. 'precomputedDistancesBuffer': wasmMemory,
  50681. 'precomputedDistancesOffset': precomputedDistancesOffset,
  50682. 'transformsBuffer': wasmMemory,
  50683. 'transformsOffset': transformsOffset
  50684. });
  50685. } else {
  50686. self.postMessage({
  50687. 'sortSetupPhase1Complete': true
  50688. });
  50689. }
  50690. });
  50691. }
  50692. };
  50693. }
  50694. function createSortWorker(splatCount, useSharedMemory, integerBasedSort, dynamicMode) {
  50695. var worker = new Worker(URL.createObjectURL(new Blob(['(', sortWorker.toString(), ')(self)'], {
  50696. type: 'application/javascript'
  50697. })));
  50698. var sorterWasmBinaryString = atob(SorterWasm); //二进制代码
  50699. var sorterWasmBytes = new Uint8Array(sorterWasmBinaryString.length);
  50700. for (var i = 0; i < sorterWasmBinaryString.length; i++) {
  50701. sorterWasmBytes[i] = sorterWasmBinaryString.charCodeAt(i);
  50702. }
  50703. worker.postMessage({
  50704. 'init': {
  50705. 'sorterWasmBytes': sorterWasmBytes.buffer,
  50706. 'splatCount': splatCount,
  50707. 'useSharedMemory': useSharedMemory,
  50708. 'integerBasedSort': integerBasedSort,
  50709. 'dynamicMode': dynamicMode,
  50710. // Super hacky
  50711. 'Constants': {
  50712. 'BytesPerFloat': Constants.BytesPerFloat,
  50713. 'BytesPerInt': Constants.BytesPerInt,
  50714. 'DepthMapRange': Constants.DepthMapRange,
  50715. 'MemoryPageSize': Constants.MemoryPageSize,
  50716. 'MaxScenes': Constants.MaxScenes
  50717. }
  50718. }
  50719. });
  50720. return worker;
  50721. }
  50722. /*
  50723. 相关函数见 setupSortWorker updateSplatSort updateRenderIndexes addSplatBuffers
  50724. 为什么要手动排序?shader无法计算准确的深度吗
  50725. */
  50726. var WebXRMode = {
  50727. None: 0,
  50728. VR: 1,
  50729. AR: 2
  50730. };
  50731. /*
  50732. Copyright © 2010-2024 three.js authors & Mark Kellogg
  50733. Permission is hereby granted, free of charge, to any person obtaining a copy
  50734. of this software and associated documentation files (the "Software"), to deal
  50735. in the Software without restriction, including without limitation the rights
  50736. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  50737. copies of the Software, and to permit persons to whom the Software is
  50738. furnished to do so, subject to the following conditions:
  50739. The above copyright notice and this permission notice shall be included in
  50740. all copies or substantial portions of the Software.
  50741. */
  50742. class VRButton {
  50743. static createButton(renderer) {
  50744. var button = document.createElement('button');
  50745. function showEnterVR( /* device */
  50746. ) {
  50747. var currentSession = null;
  50748. function onSessionStarted(_x6) {
  50749. return _onSessionStarted.apply(this, arguments);
  50750. }
  50751. function _onSessionStarted() {
  50752. _onSessionStarted = _asyncToGenerator(function* (session) {
  50753. session.addEventListener('end', onSessionEnded);
  50754. yield renderer.xr.setSession(session);
  50755. button.textContent = 'EXIT VR';
  50756. currentSession = session;
  50757. });
  50758. return _onSessionStarted.apply(this, arguments);
  50759. }
  50760. function onSessionEnded( /* event */
  50761. ) {
  50762. currentSession.removeEventListener('end', onSessionEnded);
  50763. button.textContent = 'ENTER VR';
  50764. currentSession = null;
  50765. }
  50766. //
  50767. button.style.display = '';
  50768. button.style.cursor = 'pointer';
  50769. button.style.left = 'calc(50% - 50px)';
  50770. button.style.width = '100px';
  50771. button.textContent = 'ENTER VR';
  50772. // WebXR's requestReferenceSpace only works if the corresponding feature
  50773. // was requested at session creation time. For simplicity, just ask for
  50774. // the interesting ones as optional features, but be aware that the
  50775. // requestReferenceSpace call will fail if it turns out to be unavailable.
  50776. // ('local' is always available for immersive sessions and doesn't need to
  50777. // be requested separately.)
  50778. var sessionInit = {
  50779. optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking', 'layers']
  50780. };
  50781. button.onmouseenter = function () {
  50782. button.style.opacity = '1.0';
  50783. };
  50784. button.onmouseleave = function () {
  50785. button.style.opacity = '0.5';
  50786. };
  50787. button.onclick = function () {
  50788. if (currentSession === null) {
  50789. navigator.xr.requestSession('immersive-vr', sessionInit).then(onSessionStarted);
  50790. } else {
  50791. currentSession.end();
  50792. if (navigator.xr.offerSession !== undefined) {
  50793. navigator.xr.offerSession('immersive-vr', sessionInit).then(onSessionStarted).catch(err => {
  50794. console.warn(err);
  50795. });
  50796. }
  50797. }
  50798. };
  50799. if (navigator.xr.offerSession !== undefined) {
  50800. navigator.xr.offerSession('immersive-vr', sessionInit).then(onSessionStarted).catch(err => {
  50801. console.warn(err);
  50802. });
  50803. }
  50804. }
  50805. function disableButton() {
  50806. button.style.display = '';
  50807. button.style.cursor = 'auto';
  50808. button.style.left = 'calc(50% - 75px)';
  50809. button.style.width = '150px';
  50810. button.onmouseenter = null;
  50811. button.onmouseleave = null;
  50812. button.onclick = null;
  50813. }
  50814. function showWebXRNotFound() {
  50815. disableButton();
  50816. button.textContent = 'VR NOT SUPPORTED';
  50817. }
  50818. function showVRNotAllowed(exception) {
  50819. disableButton();
  50820. console.warn('Exception when trying to call xr.isSessionSupported', exception);
  50821. button.textContent = 'VR NOT ALLOWED';
  50822. }
  50823. function stylizeElement(element) {
  50824. element.style.position = 'absolute';
  50825. element.style.bottom = '20px';
  50826. element.style.padding = '12px 6px';
  50827. element.style.border = '1px solid #fff';
  50828. element.style.borderRadius = '4px';
  50829. element.style.background = 'rgba(0,0,0,0.1)';
  50830. element.style.color = '#fff';
  50831. element.style.font = 'normal 13px sans-serif';
  50832. element.style.textAlign = 'center';
  50833. element.style.opacity = '0.5';
  50834. element.style.outline = 'none';
  50835. element.style.zIndex = '999';
  50836. }
  50837. if ('xr' in navigator) {
  50838. button.id = 'VRButton';
  50839. button.style.display = 'none';
  50840. stylizeElement(button);
  50841. navigator.xr.isSessionSupported('immersive-vr').then(function (supported) {
  50842. supported ? showEnterVR() : showWebXRNotFound();
  50843. if (supported && VRButton.xrSessionIsGranted) {
  50844. button.click();
  50845. }
  50846. }).catch(showVRNotAllowed);
  50847. return button;
  50848. } else {
  50849. var message = document.createElement('a');
  50850. if (window.isSecureContext === false) {
  50851. message.href = document.location.href.replace(/^http:/, 'https:');
  50852. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  50853. } else {
  50854. message.href = 'https://immersiveweb.dev/';
  50855. message.innerHTML = 'WEBXR NOT AVAILABLE';
  50856. }
  50857. message.style.left = 'calc(50% - 90px)';
  50858. message.style.width = '180px';
  50859. message.style.textDecoration = 'none';
  50860. stylizeElement(message);
  50861. return message;
  50862. }
  50863. }
  50864. static registerSessionGrantedListener() {
  50865. if (typeof navigator !== 'undefined' && 'xr' in navigator) {
  50866. // WebXRViewer (based on Firefox) has a bug where addEventListener
  50867. // throws a silent exception and aborts execution entirely.
  50868. if (/WebXRViewer\//i.test(navigator.userAgent)) return;
  50869. navigator.xr.addEventListener('sessiongranted', () => {
  50870. VRButton.xrSessionIsGranted = true;
  50871. });
  50872. }
  50873. }
  50874. }
  50875. VRButton.xrSessionIsGranted = false;
  50876. VRButton.registerSessionGrantedListener();
  50877. /*
  50878. Copyright © 2010-2024 three.js authors & Mark Kellogg
  50879. Permission is hereby granted, free of charge, to any person obtaining a copy
  50880. of this software and associated documentation files (the "Software"), to deal
  50881. in the Software without restriction, including without limitation the rights
  50882. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  50883. copies of the Software, and to permit persons to whom the Software is
  50884. furnished to do so, subject to the following conditions:
  50885. The above copyright notice and this permission notice shall be included in
  50886. all copies or substantial portions of the Software.
  50887. */
  50888. class ARButton {
  50889. static createButton(renderer) {
  50890. var sessionInit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  50891. var button = document.createElement('button');
  50892. function showStartAR( /* device */
  50893. ) {
  50894. if (sessionInit.domOverlay === undefined) {
  50895. var overlay = document.createElement('div');
  50896. overlay.style.display = 'none';
  50897. document.body.appendChild(overlay);
  50898. var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  50899. svg.setAttribute('width', 38);
  50900. svg.setAttribute('height', 38);
  50901. svg.style.position = 'absolute';
  50902. svg.style.right = '20px';
  50903. svg.style.top = '20px';
  50904. svg.addEventListener('click', function () {
  50905. currentSession.end();
  50906. });
  50907. overlay.appendChild(svg);
  50908. var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  50909. path.setAttribute('d', 'M 12,12 L 28,28 M 28,12 12,28');
  50910. path.setAttribute('stroke', '#fff');
  50911. path.setAttribute('stroke-width', 2);
  50912. svg.appendChild(path);
  50913. if (sessionInit.optionalFeatures === undefined) {
  50914. sessionInit.optionalFeatures = [];
  50915. }
  50916. sessionInit.optionalFeatures.push('dom-overlay');
  50917. sessionInit.domOverlay = {
  50918. root: overlay
  50919. };
  50920. }
  50921. //
  50922. var currentSession = null;
  50923. function onSessionStarted(_x7) {
  50924. return _onSessionStarted2.apply(this, arguments);
  50925. }
  50926. function _onSessionStarted2() {
  50927. _onSessionStarted2 = _asyncToGenerator(function* (session) {
  50928. session.addEventListener('end', onSessionEnded);
  50929. renderer.xr.setReferenceSpaceType('local');
  50930. yield renderer.xr.setSession(session);
  50931. button.textContent = 'STOP AR';
  50932. sessionInit.domOverlay.root.style.display = '';
  50933. currentSession = session;
  50934. });
  50935. return _onSessionStarted2.apply(this, arguments);
  50936. }
  50937. function onSessionEnded( /* event */
  50938. ) {
  50939. currentSession.removeEventListener('end', onSessionEnded);
  50940. button.textContent = 'START AR';
  50941. sessionInit.domOverlay.root.style.display = 'none';
  50942. currentSession = null;
  50943. }
  50944. //
  50945. button.style.display = '';
  50946. button.style.cursor = 'pointer';
  50947. button.style.left = 'calc(50% - 50px)';
  50948. button.style.width = '100px';
  50949. button.textContent = 'START AR';
  50950. button.onmouseenter = function () {
  50951. button.style.opacity = '1.0';
  50952. };
  50953. button.onmouseleave = function () {
  50954. button.style.opacity = '0.5';
  50955. };
  50956. button.onclick = function () {
  50957. if (currentSession === null) {
  50958. navigator.xr.requestSession('immersive-ar', sessionInit).then(onSessionStarted);
  50959. } else {
  50960. currentSession.end();
  50961. if (navigator.xr.offerSession !== undefined) {
  50962. navigator.xr.offerSession('immersive-ar', sessionInit).then(onSessionStarted).catch(err => {
  50963. console.warn(err);
  50964. });
  50965. }
  50966. }
  50967. };
  50968. if (navigator.xr.offerSession !== undefined) {
  50969. navigator.xr.offerSession('immersive-ar', sessionInit).then(onSessionStarted).catch(err => {
  50970. console.warn(err);
  50971. });
  50972. }
  50973. }
  50974. function disableButton() {
  50975. button.style.display = '';
  50976. button.style.cursor = 'auto';
  50977. button.style.left = 'calc(50% - 75px)';
  50978. button.style.width = '150px';
  50979. button.onmouseenter = null;
  50980. button.onmouseleave = null;
  50981. button.onclick = null;
  50982. }
  50983. function showARNotSupported() {
  50984. disableButton();
  50985. button.textContent = 'AR NOT SUPPORTED';
  50986. }
  50987. function showARNotAllowed(exception) {
  50988. disableButton();
  50989. console.warn('Exception when trying to call xr.isSessionSupported', exception);
  50990. button.textContent = 'AR NOT ALLOWED';
  50991. }
  50992. function stylizeElement(element) {
  50993. element.style.position = 'absolute';
  50994. element.style.bottom = '20px';
  50995. element.style.padding = '12px 6px';
  50996. element.style.border = '1px solid #fff';
  50997. element.style.borderRadius = '4px';
  50998. element.style.background = 'rgba(0,0,0,0.1)';
  50999. element.style.color = '#fff';
  51000. element.style.font = 'normal 13px sans-serif';
  51001. element.style.textAlign = 'center';
  51002. element.style.opacity = '0.5';
  51003. element.style.outline = 'none';
  51004. element.style.zIndex = '999';
  51005. }
  51006. if ('xr' in navigator) {
  51007. button.id = 'ARButton';
  51008. button.style.display = 'none';
  51009. stylizeElement(button);
  51010. navigator.xr.isSessionSupported('immersive-ar').then(function (supported) {
  51011. supported ? showStartAR() : showARNotSupported();
  51012. }).catch(showARNotAllowed);
  51013. return button;
  51014. } else {
  51015. var message = document.createElement('a');
  51016. if (window.isSecureContext === false) {
  51017. message.href = document.location.href.replace(/^http:/, 'https:');
  51018. message.innerHTML = 'WEBXR NEEDS HTTPS'; // TODO Improve message
  51019. } else {
  51020. message.href = 'https://immersiveweb.dev/';
  51021. message.innerHTML = 'WEBXR NOT AVAILABLE';
  51022. }
  51023. message.style.left = 'calc(50% - 90px)';
  51024. message.style.width = '180px';
  51025. message.style.textDecoration = 'none';
  51026. stylizeElement(message);
  51027. return message;
  51028. }
  51029. }
  51030. }
  51031. var RenderMode = {
  51032. Always: 0,
  51033. OnChange: 1,
  51034. Never: 2
  51035. };
  51036. var THREE_CAMERA_FOV = 50;
  51037. var MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT = .75;
  51038. var MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER = 1500000;
  51039. var FOCUS_MARKER_FADE_IN_SPEED = 10.0;
  51040. var FOCUS_MARKER_FADE_OUT_SPEED = 2.5;
  51041. var CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION = 60;
  51042. /**
  51043. * Viewer: Manages the rendering of splat scenes. Manages an instance of SplatMesh as well as a web worker
  51044. * that performs the sort for its splats.
  51045. */
  51046. class Viewer {
  51047. constructor() {
  51048. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  51049. _defineProperty(this, "onKeyDown", function () {
  51050. var forward = new THREE$2.Vector3();
  51051. var tempMatrixLeft = new THREE$2.Matrix4();
  51052. var tempMatrixRight = new THREE$2.Matrix4();
  51053. return function (e) {
  51054. forward.set(0, 0, -1);
  51055. forward.transformDirection(this.camera.matrixWorld);
  51056. tempMatrixLeft.makeRotationAxis(forward, Math.PI / 128);
  51057. tempMatrixRight.makeRotationAxis(forward, -Math.PI / 128);
  51058. switch (e.code) {
  51059. case 'KeyG':
  51060. this.focalAdjustment += 0.02;
  51061. this.forceRenderNextFrame();
  51062. break;
  51063. case 'KeyF':
  51064. this.focalAdjustment -= 0.02;
  51065. this.forceRenderNextFrame();
  51066. break;
  51067. case 'ArrowLeft':
  51068. this.camera.up.transformDirection(tempMatrixLeft);
  51069. break;
  51070. case 'ArrowRight':
  51071. this.camera.up.transformDirection(tempMatrixRight);
  51072. break;
  51073. case 'KeyC':
  51074. this.showMeshCursor = !this.showMeshCursor;
  51075. break;
  51076. case 'KeyU':
  51077. this.showControlPlane = !this.showControlPlane;
  51078. break;
  51079. case 'KeyI':
  51080. this.showInfo = !this.showInfo;
  51081. if (this.showInfo) {
  51082. this.infoPanel.show();
  51083. } else {
  51084. this.infoPanel.hide();
  51085. }
  51086. break;
  51087. case 'KeyO':
  51088. if (!this.usingExternalCamera) {
  51089. this.setOrthographicMode(!this.camera.isOrthographicCamera);
  51090. }
  51091. break;
  51092. case 'KeyP':
  51093. if (!this.usingExternalCamera) {
  51094. this.splatMesh.setPointCloudModeEnabled(!this.splatMesh.getPointCloudModeEnabled());
  51095. }
  51096. break;
  51097. case 'Equal':
  51098. if (!this.usingExternalCamera) {
  51099. this.splatMesh.setSplatScale(this.splatMesh.getSplatScale() + 0.05);
  51100. }
  51101. break;
  51102. case 'Minus':
  51103. if (!this.usingExternalCamera) {
  51104. this.splatMesh.setSplatScale(Math.max(this.splatMesh.getSplatScale() - 0.05, 0.0));
  51105. }
  51106. break;
  51107. }
  51108. };
  51109. }());
  51110. _defineProperty(this, "onMouseUp", function () {
  51111. var clickOffset = new THREE$2.Vector2();
  51112. return function (mouse) {
  51113. clickOffset.copy(this.mousePosition).sub(this.mouseDownPosition);
  51114. var mouseUpTime = getCurrentTime();
  51115. var wasClick = mouseUpTime - this.mouseDownTime < 0.5 && clickOffset.length() < 2;
  51116. if (wasClick) {
  51117. this.onMouseClick(mouse);
  51118. }
  51119. };
  51120. }());
  51121. _defineProperty(this, "checkForFocalPointChange", function () {
  51122. var renderDimensions = new THREE$2.Vector2();
  51123. var toNewFocalPoint = new THREE$2.Vector3();
  51124. var outHits = [];
  51125. return function () {
  51126. if (!this.transitioningCameraTarget) {
  51127. this.getRenderDimensions(renderDimensions);
  51128. outHits.length = 0;
  51129. this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions);
  51130. this.raycaster.intersectSplatMesh(this.splatMesh, outHits);
  51131. if (outHits.length > 0) {
  51132. var hit = outHits[0];
  51133. var intersectionPoint = hit.origin;
  51134. toNewFocalPoint.copy(intersectionPoint).sub(this.camera.position);
  51135. if (toNewFocalPoint.length() > MINIMUM_DISTANCE_TO_NEW_FOCAL_POINT) {
  51136. this.previousCameraTarget.copy(this.controls.target);
  51137. this.nextCameraTarget.copy(intersectionPoint);
  51138. this.transitioningCameraTarget = true;
  51139. this.transitioningCameraTargetStartTime = getCurrentTime();
  51140. }
  51141. }
  51142. }
  51143. };
  51144. }());
  51145. _defineProperty(this, "updateSplatMesh", function () {
  51146. var renderDimensions = new THREE$2.Vector2();
  51147. return function () {
  51148. if (!this.splatMesh) return;
  51149. var splatCount = this.splatMesh.getSplatCount();
  51150. if (splatCount > 0) {
  51151. this.splatMesh.updateTransforms();
  51152. this.getRenderDimensions(renderDimensions);
  51153. var focalLengthX = this.camera.projectionMatrix.elements[0] * 0.5 * this.devicePixelRatio * renderDimensions.x;
  51154. var focalLengthY = this.camera.projectionMatrix.elements[5] * 0.5 * this.devicePixelRatio * renderDimensions.y;
  51155. //this.camera.projectionMatrix.elements[0] 等效于 (2 * n) / (r - l),其中n是焦距(到近裁剪面的距离)。当它乘以0.5,然后再乘以renderDimensions.x(即视口宽度)时,你得到的是 (n * 宽度) / (r - l)。由于r - l等于宽度,最终就只剩下了n,即焦距。对于cameraFocalLengthY的计算应该得出相同的结果,所以实际上我只需要向updateUniforms()函数传递一个单独的焦距值即可。(see:https://github.com/mkkellogg/GaussianSplats3D/issues/108)
  51156. var focalMultiplier = this.camera.isOrthographicCamera ? 1.0 / this.devicePixelRatio : 1.0;
  51157. var focalAdjustment = this.focalAdjustment * focalMultiplier;
  51158. var inverseFocalAdjustment = 1.0 / focalAdjustment;
  51159. this.adjustForWebXRStereo(renderDimensions);
  51160. this.splatMesh.updateUniforms(renderDimensions, focalLengthX * focalAdjustment, focalLengthY * focalAdjustment, this.camera.isOrthographicCamera, this.camera.zoom || 1.0, inverseFocalAdjustment);
  51161. }
  51162. };
  51163. }());
  51164. /**
  51165. * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer and set up the sorting web worker.
  51166. * This function will terminate the existing sort worker (if there is one).
  51167. */
  51168. _defineProperty(this, "addSplatBuffers", function () {
  51169. return function (splatBuffers) {
  51170. var splatBufferOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  51171. var finalBuild = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  51172. var showLoadingUI = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
  51173. var showLoadingUIForSplatTreeBuild = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  51174. if (this.isDisposingOrDisposed()) return Promise.resolve();
  51175. this.splatRenderReady = false;
  51176. var splatProcessingTaskId = null;
  51177. var finish = buildResults => {
  51178. if (this.isDisposingOrDisposed()) return;
  51179. if (splatProcessingTaskId !== null) {
  51180. this.loadingSpinner.removeTask(splatProcessingTaskId);
  51181. splatProcessingTaskId = null;
  51182. }
  51183. // If we aren't calculating the splat distances from the center on the GPU, the sorting worker needs splat centers and
  51184. // transform indexes so that it can calculate those distance values.
  51185. if (!this.gpuAcceleratedSort && this.sortWorker) {
  51186. this.sortWorker.postMessage({
  51187. 'centers': buildResults.centers.buffer,
  51188. 'transformIndexes': buildResults.sceneIndexes.buffer,
  51189. 'range': {
  51190. 'from': buildResults.from,
  51191. 'to': buildResults.to,
  51192. 'count': buildResults.count
  51193. }
  51194. });
  51195. }
  51196. this.splatRenderReady = true;
  51197. this.sortNeededForSceneChange = true;
  51198. };
  51199. return new Promise(resolve => {
  51200. if (showLoadingUI) {
  51201. splatProcessingTaskId = this.loadingSpinner.addTask('Processing splats...');
  51202. }
  51203. delayedExecute(() => {
  51204. if (this.isDisposingOrDisposed()) {
  51205. resolve();
  51206. } else {
  51207. var buildResults = this.addSplatBuffersToMesh(splatBuffers, splatBufferOptions, finalBuild, showLoadingUIForSplatTreeBuild);
  51208. var maxSplatCount = this.splatMesh.getMaxSplatCount();
  51209. if (this.sortWorker && this.sortWorker.maxSplatCount !== maxSplatCount) this.disposeSortWorker();
  51210. var sortWorkerSetupPromise = !this.sortWorker && maxSplatCount > 0 ? this.setupSortWorker(this.splatMesh) : Promise.resolve();
  51211. sortWorkerSetupPromise.then(() => {
  51212. finish(buildResults);
  51213. resolve();
  51214. });
  51215. }
  51216. }, true);
  51217. });
  51218. };
  51219. }());
  51220. _defineProperty(this, "shouldRender", function () {
  51221. var renderCount = 0;
  51222. var lastCameraPosition = new THREE$2.Vector3();
  51223. var lastCameraOrientation = new THREE$2.Quaternion();
  51224. var changeEpsilon = 0.0001;
  51225. return function () {
  51226. var shouldRender = false;
  51227. var cameraChanged = false;
  51228. if (this.camera) {
  51229. var cp = this.camera.position;
  51230. var co = this.camera.quaternion;
  51231. cameraChanged = Math.abs(cp.x - lastCameraPosition.x) > changeEpsilon || Math.abs(cp.y - lastCameraPosition.y) > changeEpsilon || Math.abs(cp.z - lastCameraPosition.z) > changeEpsilon || Math.abs(co.x - lastCameraOrientation.x) > changeEpsilon || Math.abs(co.y - lastCameraOrientation.y) > changeEpsilon || Math.abs(co.z - lastCameraOrientation.z) > changeEpsilon || Math.abs(co.w - lastCameraOrientation.w) > changeEpsilon;
  51232. }
  51233. shouldRender = this.renderMode !== RenderMode.Never && (renderCount === 0 || this.splatMesh.visibleRegionChanging || cameraChanged || this.renderMode === RenderMode.Always || this.dynamicMode === true || this.renderNextFrame);
  51234. if (this.camera) {
  51235. lastCameraPosition.copy(this.camera.position);
  51236. lastCameraOrientation.copy(this.camera.quaternion);
  51237. }
  51238. renderCount++;
  51239. return shouldRender;
  51240. };
  51241. }());
  51242. _defineProperty(this, "render", function () {
  51243. return function () {
  51244. if (!this.initialized || !this.splatRenderReady) return;
  51245. var hasRenderables = threeScene => {
  51246. for (var child of threeScene.children) {
  51247. if (child.visible) return true;
  51248. }
  51249. return false;
  51250. };
  51251. var oldLayer = this.camera.layers.mask;
  51252. this.camera.layers.set(0); //xzw add
  51253. var savedAuoClear = this.renderer.autoClear;
  51254. /* if (hasRenderables(this.threeScene)) {//xzw
  51255. this.renderer.render(this.threeScene, this.camera);
  51256. this.renderer.autoClear = false;
  51257. } */
  51258. this.renderer.render(this.splatMesh, this.camera);
  51259. this.renderer.autoClear = false;
  51260. if (this.sceneHelper.getFocusMarkerOpacity() > 0.0) this.renderer.render(this.sceneHelper.focusMarker, this.camera);
  51261. if (this.showControlPlane) this.renderer.render(this.sceneHelper.controlPlane, this.camera);
  51262. this.renderer.autoClear = savedAuoClear;
  51263. this.camera.layers.mask = oldLayer;
  51264. };
  51265. }());
  51266. _defineProperty(this, "updateFPS", function () {
  51267. var lastCalcTime = getCurrentTime();
  51268. var frameCount = 0;
  51269. return function () {
  51270. if (this.consecutiveRenderFrames > CONSECUTIVE_RENDERED_FRAMES_FOR_FPS_CALCULATION) {
  51271. var currentTime = getCurrentTime();
  51272. var calcDelta = currentTime - lastCalcTime;
  51273. if (calcDelta >= 1.0) {
  51274. this.currentFPS = frameCount;
  51275. frameCount = 0;
  51276. lastCalcTime = currentTime;
  51277. } else {
  51278. frameCount++;
  51279. }
  51280. } else {
  51281. this.currentFPS = null;
  51282. }
  51283. };
  51284. }());
  51285. _defineProperty(this, "updateForRendererSizeChanges", function () {
  51286. var lastRendererSize = new THREE$2.Vector2();
  51287. var currentRendererSize = new THREE$2.Vector2();
  51288. var lastCameraOrthographic;
  51289. return function () {
  51290. if (!this.usingExternalCamera) {
  51291. this.renderer.getSize(currentRendererSize);
  51292. if (lastCameraOrthographic === undefined || lastCameraOrthographic !== this.camera.isOrthographicCamera || currentRendererSize.x !== lastRendererSize.x || currentRendererSize.y !== lastRendererSize.y) {
  51293. if (this.camera.isOrthographicCamera) {
  51294. this.camera.left = -currentRendererSize.x / 2.0;
  51295. this.camera.right = currentRendererSize.x / 2.0;
  51296. this.camera.top = currentRendererSize.y / 2.0;
  51297. this.camera.bottom = -currentRendererSize.y / 2.0;
  51298. } else {
  51299. this.camera.aspect = currentRendererSize.x / currentRendererSize.y;
  51300. }
  51301. this.camera.updateProjectionMatrix();
  51302. lastRendererSize.copy(currentRendererSize);
  51303. lastCameraOrthographic = this.camera.isOrthographicCamera;
  51304. }
  51305. }
  51306. };
  51307. }());
  51308. _defineProperty(this, "timingSensitiveUpdates", function () {
  51309. var lastUpdateTime;
  51310. return function () {
  51311. var currentTime = getCurrentTime();
  51312. if (!lastUpdateTime) lastUpdateTime = currentTime;
  51313. var timeDelta = currentTime - lastUpdateTime;
  51314. this.updateCameraTransition(currentTime);
  51315. this.updateFocusMarker(timeDelta);
  51316. lastUpdateTime = currentTime;
  51317. };
  51318. }());
  51319. _defineProperty(this, "updateCameraTransition", function () {
  51320. var tempCameraTarget = new THREE$2.Vector3();
  51321. var toPreviousTarget = new THREE$2.Vector3();
  51322. var toNextTarget = new THREE$2.Vector3();
  51323. return function (currentTime) {
  51324. if (this.transitioningCameraTarget) {
  51325. toPreviousTarget.copy(this.previousCameraTarget).sub(this.camera.position).normalize();
  51326. toNextTarget.copy(this.nextCameraTarget).sub(this.camera.position).normalize();
  51327. var rotationAngle = Math.acos(toPreviousTarget.dot(toNextTarget));
  51328. var rotationSpeed = rotationAngle / (Math.PI / 3) * .65 + .3;
  51329. var t = rotationSpeed / rotationAngle * (currentTime - this.transitioningCameraTargetStartTime);
  51330. tempCameraTarget.copy(this.previousCameraTarget).lerp(this.nextCameraTarget, t);
  51331. this.camera.lookAt(tempCameraTarget);
  51332. this.controls.target.copy(tempCameraTarget);
  51333. if (t >= 1.0) {
  51334. this.transitioningCameraTarget = false;
  51335. }
  51336. }
  51337. };
  51338. }());
  51339. _defineProperty(this, "updateFocusMarker", function () {
  51340. var renderDimensions = new THREE$2.Vector2();
  51341. var wasTransitioning = false;
  51342. return function (timeDelta) {
  51343. this.getRenderDimensions(renderDimensions);
  51344. if (this.transitioningCameraTarget) {
  51345. this.sceneHelper.setFocusMarkerVisibility(true);
  51346. var currentFocusMarkerOpacity = Math.max(this.sceneHelper.getFocusMarkerOpacity(), 0.0);
  51347. var newFocusMarkerOpacity = Math.min(currentFocusMarkerOpacity + FOCUS_MARKER_FADE_IN_SPEED * timeDelta, 1.0);
  51348. this.sceneHelper.setFocusMarkerOpacity(newFocusMarkerOpacity);
  51349. this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions);
  51350. wasTransitioning = true;
  51351. this.forceRenderNextFrame();
  51352. } else {
  51353. var _currentFocusMarkerOpacity;
  51354. if (wasTransitioning) _currentFocusMarkerOpacity = 1.0;else _currentFocusMarkerOpacity = Math.min(this.sceneHelper.getFocusMarkerOpacity(), 1.0);
  51355. if (_currentFocusMarkerOpacity > 0) {
  51356. this.sceneHelper.updateFocusMarker(this.nextCameraTarget, this.camera, renderDimensions);
  51357. var _newFocusMarkerOpacity = Math.max(_currentFocusMarkerOpacity - FOCUS_MARKER_FADE_OUT_SPEED * timeDelta, 0.0);
  51358. this.sceneHelper.setFocusMarkerOpacity(_newFocusMarkerOpacity);
  51359. if (_newFocusMarkerOpacity === 0.0) this.sceneHelper.setFocusMarkerVisibility(false);
  51360. }
  51361. if (_currentFocusMarkerOpacity > 0.0) this.forceRenderNextFrame();
  51362. wasTransitioning = false;
  51363. }
  51364. };
  51365. }());
  51366. _defineProperty(this, "updateMeshCursor", function () {
  51367. var outHits = [];
  51368. var renderDimensions = new THREE$2.Vector2();
  51369. return function () {
  51370. if (this.showMeshCursor) {
  51371. this.forceRenderNextFrame();
  51372. this.getRenderDimensions(renderDimensions);
  51373. outHits.length = 0;
  51374. this.raycaster.setFromCameraAndScreenPosition(this.camera, this.mousePosition, renderDimensions);
  51375. this.raycaster.intersectSplatMesh(this.splatMesh, outHits);
  51376. if (outHits.length > 0) {
  51377. this.sceneHelper.setMeshCursorVisibility(true);
  51378. this.sceneHelper.positionAndOrientMeshCursor(outHits[0].origin, this.camera);
  51379. } else {
  51380. this.sceneHelper.setMeshCursorVisibility(false);
  51381. }
  51382. } else {
  51383. if (this.sceneHelper.getMeschCursorVisibility()) this.forceRenderNextFrame();
  51384. this.sceneHelper.setMeshCursorVisibility(false);
  51385. }
  51386. };
  51387. }());
  51388. _defineProperty(this, "updateInfoPanel", function () {
  51389. var renderDimensions = new THREE$2.Vector2();
  51390. return function () {
  51391. if (!this.showInfo) return;
  51392. var splatCount = this.splatMesh.getSplatCount();
  51393. this.getRenderDimensions(renderDimensions);
  51394. var cameraLookAtPosition = this.controls ? this.controls.target : null;
  51395. var meshCursorPosition = this.showMeshCursor ? this.sceneHelper.meshCursor.position : null;
  51396. var splatRenderCountPct = splatCount > 0 ? this.splatRenderCount / splatCount * 100 : 0;
  51397. this.infoPanel.update(renderDimensions, this.camera.position, cameraLookAtPosition, this.camera.up, this.camera.isOrthographicCamera, meshCursorPosition, this.currentFPS || 'N/A', splatCount, this.splatRenderCount, splatRenderCountPct, this.lastSortTime, this.focalAdjustment, this.splatMesh.getSplatScale(), this.splatMesh.getPointCloudModeEnabled());
  51398. };
  51399. }());
  51400. _defineProperty(this, "updateSplatSort", function () {
  51401. var mvpMatrix = new THREE$2.Matrix4();
  51402. var cameraPositionArray = [];
  51403. var lastSortViewDir = new THREE$2.Vector3(0, 0, -1);
  51404. var sortViewDir = new THREE$2.Vector3(0, 0, -1);
  51405. var lastSortViewPos = new THREE$2.Vector3();
  51406. var sortViewOffset = new THREE$2.Vector3();
  51407. var queuedSorts = [];
  51408. var partialSorts = [{
  51409. 'angleThreshold': 0.55,
  51410. 'sortFractions': [0.125, 0.33333, 0.75]
  51411. }, {
  51412. 'angleThreshold': 0.65,
  51413. 'sortFractions': [0.33333, 0.66667]
  51414. }, {
  51415. 'angleThreshold': 0.8,
  51416. 'sortFractions': [0.5]
  51417. }];
  51418. return /*#__PURE__*/_asyncToGenerator(function* () {
  51419. var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  51420. if (this.sortRunning) return;
  51421. if (this.splatMesh.getSplatCount() <= 0) return;
  51422. var angleDiff = 0;
  51423. var positionDiff = 0;
  51424. var needsRefreshForRotation = false;
  51425. var needsRefreshForPosition = false;
  51426. sortViewDir.set(0, 0, -1).applyQuaternion(this.camera.quaternion);
  51427. angleDiff = sortViewDir.dot(lastSortViewDir);
  51428. positionDiff = sortViewOffset.copy(this.camera.position).sub(lastSortViewPos).length();
  51429. if (!force) {
  51430. if (!this.sortNeededForSceneChange && !this.splatMesh.dynamicMode && queuedSorts.length === 0) {
  51431. if (angleDiff <= 0.99) needsRefreshForRotation = true;
  51432. if (positionDiff >= 1.0) needsRefreshForPosition = true;
  51433. if (!needsRefreshForRotation && !needsRefreshForPosition) return;
  51434. }
  51435. }
  51436. this.sortRunning = true;
  51437. var {
  51438. splatRenderCount,
  51439. shouldSortAll
  51440. } = this.gatherSceneNodesForSort();
  51441. this.splatRenderCount = splatRenderCount;
  51442. mvpMatrix.copy(this.camera.matrixWorld).invert();
  51443. var mvpCamera = this.perspectiveCamera || this.camera;
  51444. mvpMatrix.premultiply(mvpCamera.projectionMatrix);
  51445. mvpMatrix.multiply(this.splatMesh.matrixWorld);
  51446. if (this.gpuAcceleratedSort && (queuedSorts.length <= 1 || queuedSorts.length % 2 === 0)) {
  51447. yield this.splatMesh.computeDistancesOnGPU(mvpMatrix, this.sortWorkerPrecomputedDistances);
  51448. }
  51449. if (this.splatMesh.dynamicMode || shouldSortAll) {
  51450. queuedSorts.push(this.splatRenderCount);
  51451. } else {
  51452. if (queuedSorts.length === 0) {
  51453. for (var partialSort of partialSorts) {
  51454. if (angleDiff < partialSort.angleThreshold) {
  51455. for (var sortFraction of partialSort.sortFractions) {
  51456. queuedSorts.push(Math.floor(this.splatRenderCount * sortFraction));
  51457. }
  51458. break;
  51459. }
  51460. }
  51461. queuedSorts.push(this.splatRenderCount);
  51462. }
  51463. }
  51464. var sortCount = Math.min(queuedSorts.shift(), this.splatRenderCount);
  51465. cameraPositionArray[0] = this.camera.position.x;
  51466. cameraPositionArray[1] = this.camera.position.y;
  51467. cameraPositionArray[2] = this.camera.position.z;
  51468. var sortMessage = {
  51469. 'modelViewProj': mvpMatrix.elements,
  51470. 'cameraPosition': cameraPositionArray,
  51471. 'splatRenderCount': this.splatRenderCount,
  51472. 'splatSortCount': sortCount,
  51473. 'usePrecomputedDistances': this.gpuAcceleratedSort
  51474. };
  51475. if (this.splatMesh.dynamicMode) {
  51476. this.splatMesh.fillTransformsArray(this.sortWorkerTransforms);
  51477. }
  51478. if (!this.sharedMemoryForWorkers) {
  51479. sortMessage.indexesToSort = this.sortWorkerIndexesToSort;
  51480. sortMessage.transforms = this.sortWorkerTransforms;
  51481. if (this.gpuAcceleratedSort) {
  51482. sortMessage.precomputedDistances = this.sortWorkerPrecomputedDistances;
  51483. }
  51484. }
  51485. this.sortPromise = new Promise(resolve => {
  51486. this.sortPromiseResolver = resolve;
  51487. });
  51488. this.sortWorker.postMessage({
  51489. 'sort': sortMessage
  51490. });
  51491. if (queuedSorts.length === 0) {
  51492. lastSortViewPos.copy(this.camera.position);
  51493. lastSortViewDir.copy(sortViewDir);
  51494. }
  51495. this.sortNeededForSceneChange = false;
  51496. });
  51497. }());
  51498. /**
  51499. * Determine which splats to render by checking which are inside or close to the view frustum
  51500. */
  51501. _defineProperty(this, "gatherSceneNodesForSort", function () {
  51502. var nodeRenderList = [];
  51503. var allSplatsSortBuffer = null;
  51504. var tempVectorYZ = new THREE$2.Vector3();
  51505. var tempVectorXZ = new THREE$2.Vector3();
  51506. var tempVector = new THREE$2.Vector3();
  51507. var modelView = new THREE$2.Matrix4();
  51508. var baseModelView = new THREE$2.Matrix4();
  51509. var sceneTransform = new THREE$2.Matrix4();
  51510. var renderDimensions = new THREE$2.Vector3();
  51511. var forward = new THREE$2.Vector3(0, 0, -1);
  51512. var tempMax = new THREE$2.Vector3();
  51513. var nodeSize = node => {
  51514. return tempMax.copy(node.max).sub(node.min).length();
  51515. };
  51516. return function () {
  51517. var gatherAllNodes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
  51518. this.getRenderDimensions(renderDimensions);
  51519. var cameraFocalLength = renderDimensions.y / 2.0 / Math.tan(this.camera.fov / 2.0 * THREE$2.MathUtils.DEG2RAD);
  51520. var fovXOver2 = Math.atan(renderDimensions.x / 2.0 / cameraFocalLength);
  51521. var fovYOver2 = Math.atan(renderDimensions.y / 2.0 / cameraFocalLength);
  51522. var cosFovXOver2 = Math.cos(fovXOver2);
  51523. var cosFovYOver2 = Math.cos(fovYOver2);
  51524. var splatTree = this.splatMesh.getSplatTree();
  51525. if (splatTree) {
  51526. baseModelView.copy(this.camera.matrixWorld).invert();
  51527. baseModelView.multiply(this.splatMesh.matrixWorld);
  51528. var nodeRenderCount = 0;
  51529. var splatRenderCount = 0;
  51530. for (var s = 0; s < splatTree.subTrees.length; s++) {
  51531. var subTree = splatTree.subTrees[s];
  51532. modelView.copy(baseModelView);
  51533. if (this.splatMesh.dynamicMode) {
  51534. this.splatMesh.getSceneTransform(s, sceneTransform);
  51535. modelView.multiply(sceneTransform);
  51536. }
  51537. var nodeCount = subTree.nodesWithIndexes.length;
  51538. for (var i = 0; i < nodeCount; i++) {
  51539. var node = subTree.nodesWithIndexes[i];
  51540. if (!node.data || !node.data.indexes || node.data.indexes.length === 0) continue;
  51541. tempVector.copy(node.center).applyMatrix4(modelView);
  51542. var distanceToNode = tempVector.length();
  51543. tempVector.normalize();
  51544. tempVectorYZ.copy(tempVector).setX(0).normalize();
  51545. tempVectorXZ.copy(tempVector).setY(0).normalize();
  51546. var cameraAngleXZDot = forward.dot(tempVectorXZ);
  51547. var cameraAngleYZDot = forward.dot(tempVectorYZ);
  51548. var ns = nodeSize(node);
  51549. var outOfFovY = cameraAngleYZDot < cosFovYOver2 - .6; //角度超出
  51550. var outOfFovX = cameraAngleXZDot < cosFovXOver2 - .6;
  51551. if (!gatherAllNodes && (outOfFovX || outOfFovY) && distanceToNode > ns) {
  51552. continue;
  51553. }
  51554. splatRenderCount += node.data.indexes.length;
  51555. nodeRenderList[nodeRenderCount] = node;
  51556. node.data.distanceToNode = distanceToNode;
  51557. nodeRenderCount++;
  51558. }
  51559. }
  51560. nodeRenderList.length = nodeRenderCount;
  51561. nodeRenderList.sort((a, b) => {
  51562. //从近到远排序。去掉后也不影响,毕竟之后还要sort index
  51563. if (a.data.distanceToNode < b.data.distanceToNode) return -1;else return 1;
  51564. });
  51565. //将要渲染的点的index写入sortWorkerIndexesToSort的buffer
  51566. var currentByteOffset = splatRenderCount * Constants.BytesPerInt;
  51567. for (var _i16 = 0; _i16 < nodeRenderCount; _i16++) {
  51568. var _node = nodeRenderList[_i16];
  51569. var windowSizeInts = _node.data.indexes.length;
  51570. var windowSizeBytes = windowSizeInts * Constants.BytesPerInt;
  51571. var destView = new Uint32Array(this.sortWorkerIndexesToSort.buffer,
  51572. //写入sortWorkerIndexesToSort
  51573. currentByteOffset - windowSizeBytes, windowSizeInts);
  51574. destView.set(_node.data.indexes);
  51575. currentByteOffset -= windowSizeBytes;
  51576. }
  51577. return {
  51578. 'splatRenderCount': splatRenderCount,
  51579. 'shouldSortAll': false
  51580. };
  51581. } else {
  51582. var totalSplatCount = this.splatMesh.getSplatCount();
  51583. if (!allSplatsSortBuffer || allSplatsSortBuffer.length !== totalSplatCount) {
  51584. allSplatsSortBuffer = new Uint32Array(totalSplatCount);
  51585. for (var _i17 = 0; _i17 < totalSplatCount; _i17++) {
  51586. allSplatsSortBuffer[_i17] = _i17;
  51587. }
  51588. }
  51589. this.sortWorkerIndexesToSort.set(allSplatsSortBuffer);
  51590. return {
  51591. 'splatRenderCount': totalSplatCount,
  51592. 'shouldSortAll': true
  51593. };
  51594. }
  51595. };
  51596. }());
  51597. // The natural 'up' vector for viewing the scene (only has an effect when used with orbit controls and
  51598. // when the viewer uses its own camera).
  51599. if (!options.cameraUp) options.cameraUp = [0, 1, 0];
  51600. this.cameraUp = new THREE$2.Vector3().fromArray(options.cameraUp);
  51601. // The camera's initial position (only used when the viewer uses its own camera).
  51602. if (!options.initialCameraPosition) options.initialCameraPosition = [0, 10, 15];
  51603. this.initialCameraPosition = new THREE$2.Vector3().fromArray(options.initialCameraPosition);
  51604. // The initial focal point of the camera and center of the camera's orbit (only used when the viewer uses its own camera).
  51605. if (!options.initialCameraLookAt) options.initialCameraLookAt = [0, 0, 0];
  51606. this.initialCameraLookAt = new THREE$2.Vector3().fromArray(options.initialCameraLookAt);
  51607. // 'dropInMode' is a flag that is used internally to support the usage of the viewer as a Three.js scene object
  51608. this.dropInMode = options.dropInMode || false;
  51609. // If 'selfDrivenMode' is true, the viewer manages its own update/animation loop via requestAnimationFrame()
  51610. if (options.selfDrivenMode === undefined || options.selfDrivenMode === null) options.selfDrivenMode = true;
  51611. this.selfDrivenMode = options.selfDrivenMode && !this.dropInMode;
  51612. this.selfDrivenUpdateFunc = this.selfDrivenUpdate.bind(this);
  51613. // If 'useBuiltInControls' is true, the viewer will create its own instance of OrbitControls and attach to the camera
  51614. if (options.useBuiltInControls === undefined) options.useBuiltInControls = true;
  51615. this.useBuiltInControls = options.useBuiltInControls;
  51616. // parent element of the Three.js renderer canvas
  51617. this.rootElement = options.rootElement;
  51618. // Tells the viewer to pretend the device pixel ratio is 1, which can boost performance on devices where it is larger,
  51619. // at a small cost to visual quality
  51620. this.ignoreDevicePixelRatio = options.ignoreDevicePixelRatio || false;
  51621. this.devicePixelRatio = this.ignoreDevicePixelRatio ? 1 : window.devicePixelRatio;
  51622. // Tells the viewer to use 16-bit floating point values when storing splat covariance data in textures, instead of 32-bit
  51623. this.halfPrecisionCovariancesOnGPU = options.halfPrecisionCovariancesOnGPU || false;
  51624. // If 'threeScene' is valid, it will be rendered by the viewer along with the splat mesh
  51625. this.threeScene = options.threeScene;
  51626. // Allows for usage of an external Three.js renderer
  51627. this.renderer = options.renderer;
  51628. // Allows for usage of an external Three.js camera
  51629. this.camera = options.camera;
  51630. // If 'gpuAcceleratedSort' is true, a partially GPU-accelerated approach to sorting splats will be used.
  51631. // Currently this means pre-computing splat distances from the camera on the GPU
  51632. this.gpuAcceleratedSort = options.gpuAcceleratedSort || false;
  51633. // if 'integerBasedSort' is true, the integer version of splat centers as well as other values used to calculate
  51634. // splat distances are used instead of the float version. This speeds up computation, but introduces the possibility of
  51635. // overflow in larger scenes.
  51636. if (options.integerBasedSort === undefined || options.integerBasedSort === null) {
  51637. options.integerBasedSort = true;
  51638. }
  51639. this.integerBasedSort = options.integerBasedSort;
  51640. // If 'sharedMemoryForWorkers' is true, a SharedArrayBuffer will be used to communicate with web workers. This method
  51641. // is faster than copying memory to or from web workers, but comes with security implications as outlined here:
  51642. // https://web.dev/articles/cross-origin-isolation-guide
  51643. // If enabled, it requires specific CORS headers to be present in the response from the server that is sent when
  51644. // loading the application. More information is available in the README.
  51645. if (options.sharedMemoryForWorkers === undefined || options.sharedMemoryForWorkers === null) options.sharedMemoryForWorkers = true;
  51646. this.sharedMemoryForWorkers = options.sharedMemoryForWorkers;
  51647. // if 'dynamicScene' is true, it tells the viewer to assume scene elements are not stationary or that the number of splats in the
  51648. // scene may change. This prevents optimizations that depend on a static scene from being made. Additionally, if 'dynamicScene' is
  51649. // true it tells the splat mesh to not apply scene tranforms to splat data that is returned by functions like
  51650. // SplatMesh.getSplatCenter() by default.
  51651. this.dynamicScene = !!options.dynamicScene;
  51652. // When true, will perform additional steps during rendering to address artifacts caused by the rendering of gaussians at a
  51653. // substantially different resolution than that at which they were rendered during training. This will only work correctly
  51654. // for models that were trained using a process that utilizes this compensation calculation. For more details:
  51655. // https://github.com/nerfstudio-project/gsplat/pull/117
  51656. // https://github.com/graphdeco-inria/gaussian-splatting/issues/294#issuecomment-1772688093
  51657. this.antialiased = options.antialiased || false;
  51658. this.webXRMode = options.webXRMode || WebXRMode.None;
  51659. if (this.webXRMode !== WebXRMode.None) {
  51660. this.gpuAcceleratedSort = false;
  51661. }
  51662. this.webXRActive = false;
  51663. // if 'renderMode' is RenderMode.Always, then the viewer will rrender the scene on every update. If it is RenderMode.OnChange,
  51664. // it will only render when something in the scene has changed.
  51665. this.renderMode = options.renderMode || RenderMode.Always;
  51666. // SceneRevealMode.Default results in a nice, slow fade-in effect for progressively loaded scenes,
  51667. // and a fast fade-in for non progressively loaded scenes.
  51668. // SceneRevealMode.Gradual will force a slow fade-in for all scenes.
  51669. // SceneRevealMode.Instant will force all loaded scene data to be immediately visible.
  51670. this.sceneRevealMode = options.sceneRevealMode || SceneRevealMode.Default;
  51671. // Hacky, experimental, non-scientific parameter for tweaking focal length related calculations. For scenes with very
  51672. // small gaussians, small details, and small dimensions -- increasing this value can help improve visual quality.
  51673. this.focalAdjustment = options.focalAdjustment || 1.0;
  51674. // Specify the maximum screen-space splat size, can help deal with large splats that get too unwieldy
  51675. this.maxScreenSpaceSplatSize = options.maxScreenSpaceSplatSize || 2048;
  51676. // The verbosity of console logging
  51677. this.logLevel = options.logLevel || LogLevel.None;
  51678. // Degree of spherical harmonics to utilize in rendering splats (assuming the data is present in the splat scene).
  51679. // Valid values are 0 - 3. Default value is 0.
  51680. this.sphericalHarmonicsDegree = options.sphericalHarmonicsDegree || 0;
  51681. this.createSplatMesh();
  51682. this.controls = null;
  51683. this.perspectiveControls = null;
  51684. this.orthographicControls = null;
  51685. this.orthographicCamera = null;
  51686. this.perspectiveCamera = null;
  51687. this.showMeshCursor = false;
  51688. this.showControlPlane = false;
  51689. this.showInfo = false;
  51690. this.sceneHelper = null;
  51691. this.sortWorker = null;
  51692. this.sortRunning = false;
  51693. this.splatRenderCount = 0;
  51694. this.sortWorkerIndexesToSort = null;
  51695. this.sortWorkerSortedIndexes = null;
  51696. this.sortWorkerPrecomputedDistances = null;
  51697. this.sortWorkerTransforms = null;
  51698. this.runAfterFirstSort = [];
  51699. this.selfDrivenModeRunning = false;
  51700. this.splatRenderReady = false;
  51701. this.raycaster = new Raycaster$1();
  51702. this.infoPanel = null;
  51703. this.startInOrthographicMode = false;
  51704. this.currentFPS = 0;
  51705. this.lastSortTime = 0;
  51706. this.consecutiveRenderFrames = 0;
  51707. this.previousCameraTarget = new THREE$2.Vector3();
  51708. this.nextCameraTarget = new THREE$2.Vector3();
  51709. this.mousePosition = new THREE$2.Vector2();
  51710. this.mouseDownPosition = new THREE$2.Vector2();
  51711. this.mouseDownTime = null;
  51712. this.resizeObserver = null;
  51713. this.mouseMoveListener = null;
  51714. this.mouseDownListener = null;
  51715. this.mouseUpListener = null;
  51716. this.keyDownListener = null;
  51717. this.sortPromise = null;
  51718. this.sortPromiseResolver = null;
  51719. this.splatSceneDownloadPromises = {};
  51720. this.splatSceneDownloadAndBuildPromise = null;
  51721. this.splatSceneRemovalPromise = null;
  51722. this.loadingSpinner = new LoadingSpinner(null, this.rootElement || document.body);
  51723. this.loadingSpinner.hide();
  51724. this.loadingProgressBar = new LoadingProgressBar(this.rootElement || document.body);
  51725. this.loadingProgressBar.hide();
  51726. this.infoPanel = new InfoPanel(this.rootElement || document.body);
  51727. this.infoPanel.hide();
  51728. this.usingExternalCamera = this.dropInMode || this.camera ? true : false;
  51729. this.usingExternalRenderer = this.dropInMode || this.renderer ? true : false;
  51730. this.initialized = false;
  51731. this.disposing = false;
  51732. this.disposed = false;
  51733. if (!this.dropInMode) this.init();
  51734. }
  51735. createSplatMesh() {
  51736. this.splatMesh = new SplatMesh(this.dynamicScene, this.halfPrecisionCovariancesOnGPU, this.devicePixelRatio, this.gpuAcceleratedSort, this.integerBasedSort, this.antialiased, this.maxScreenSpaceSplatSize, this.logLevel, this.sphericalHarmonicsDegree);
  51737. this.splatMesh.frustumCulled = false;
  51738. }
  51739. init() {
  51740. if (this.initialized) return;
  51741. if (!this.rootElement) {
  51742. if (!this.usingExternalRenderer) {
  51743. this.rootElement = document.createElement('div');
  51744. this.rootElement.style.width = '100%';
  51745. this.rootElement.style.height = '100%';
  51746. this.rootElement.style.position = 'absolute';
  51747. document.body.appendChild(this.rootElement);
  51748. } else {
  51749. this.rootElement = this.renderer.domElement.parentElement || document.body;
  51750. }
  51751. }
  51752. this.setupCamera();
  51753. this.setupRenderer();
  51754. this.setupWebXR();
  51755. this.setupControls();
  51756. this.setupEventHandlers();
  51757. this.threeScene = this.threeScene || new THREE$2.Scene();
  51758. this.sceneHelper = new SceneHelper(this.threeScene);
  51759. this.sceneHelper.setupMeshCursor();
  51760. this.sceneHelper.setupFocusMarker();
  51761. this.sceneHelper.setupControlPlane();
  51762. this.loadingProgressBar.setContainer(this.rootElement);
  51763. this.loadingSpinner.setContainer(this.rootElement);
  51764. this.infoPanel.setContainer(this.rootElement);
  51765. this.initialized = true;
  51766. }
  51767. setupCamera() {
  51768. if (!this.usingExternalCamera) {
  51769. var renderDimensions = new THREE$2.Vector2();
  51770. this.getRenderDimensions(renderDimensions);
  51771. this.perspectiveCamera = new THREE$2.PerspectiveCamera(THREE_CAMERA_FOV, renderDimensions.x / renderDimensions.y, 0.1, 1000);
  51772. this.orthographicCamera = new THREE$2.OrthographicCamera(renderDimensions.x / -2, renderDimensions.x / 2, renderDimensions.y / 2, renderDimensions.y / -2, 0.1, 1000);
  51773. this.camera = this.startInOrthographicMode ? this.orthographicCamera : this.perspectiveCamera;
  51774. this.camera.position.copy(this.initialCameraPosition);
  51775. this.camera.up.copy(this.cameraUp).normalize();
  51776. this.camera.lookAt(this.initialCameraLookAt);
  51777. }
  51778. }
  51779. setupRenderer() {
  51780. if (!this.usingExternalRenderer) {
  51781. var renderDimensions = new THREE$2.Vector2();
  51782. this.getRenderDimensions(renderDimensions);
  51783. this.renderer = new THREE$2.WebGLRenderer({
  51784. antialias: false,
  51785. precision: 'highp'
  51786. });
  51787. this.renderer.setPixelRatio(this.devicePixelRatio);
  51788. this.renderer.autoClear = true;
  51789. this.renderer.setClearColor(new THREE$2.Color(0x000000), 0.0);
  51790. this.renderer.setSize(renderDimensions.x, renderDimensions.y);
  51791. this.resizeObserver = new ResizeObserver(() => {
  51792. this.getRenderDimensions(renderDimensions);
  51793. this.renderer.setSize(renderDimensions.x, renderDimensions.y);
  51794. this.forceRenderNextFrame();
  51795. });
  51796. this.resizeObserver.observe(this.rootElement);
  51797. this.rootElement.appendChild(this.renderer.domElement);
  51798. }
  51799. }
  51800. setupWebXR() {
  51801. if (this.webXRMode) {
  51802. if (this.webXRMode === WebXRMode.VR) {
  51803. this.rootElement.appendChild(VRButton.createButton(this.renderer));
  51804. } else if (this.webXRMode === WebXRMode.AR) {
  51805. this.rootElement.appendChild(ARButton.createButton(this.renderer));
  51806. }
  51807. this.renderer.xr.addEventListener('sessionstart', e => {
  51808. this.webXRActive = true;
  51809. });
  51810. this.renderer.xr.addEventListener('sessionend', e => {
  51811. this.webXRActive = false;
  51812. });
  51813. this.renderer.xr.enabled = true;
  51814. this.camera.position.copy(this.initialCameraPosition);
  51815. this.camera.up.copy(this.cameraUp).normalize();
  51816. this.camera.lookAt(this.initialCameraLookAt);
  51817. }
  51818. }
  51819. setupControls() {
  51820. if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) {
  51821. if (!this.usingExternalCamera) {
  51822. this.perspectiveControls = new OrbitControls(this.perspectiveCamera, this.renderer.domElement);
  51823. this.orthographicControls = new OrbitControls(this.orthographicCamera, this.renderer.domElement);
  51824. } else {
  51825. if (this.camera.isOrthographicCamera) {
  51826. this.orthographicControls = new OrbitControls(this.camera, this.renderer.domElement);
  51827. } else {
  51828. this.perspectiveControls = new OrbitControls(this.camera, this.renderer.domElement);
  51829. }
  51830. }
  51831. for (var controls of [this.perspectiveControls, this.orthographicControls]) {
  51832. if (controls) {
  51833. controls.listenToKeyEvents(window);
  51834. controls.rotateSpeed = 0.5;
  51835. controls.maxPolarAngle = Math.PI * .75;
  51836. controls.minPolarAngle = 0.1;
  51837. controls.enableDamping = true;
  51838. controls.dampingFactor = 0.05;
  51839. controls.target.copy(this.initialCameraLookAt);
  51840. }
  51841. }
  51842. this.controls = this.camera.isOrthographicCamera ? this.orthographicControls : this.perspectiveControls;
  51843. }
  51844. }
  51845. setupEventHandlers() {
  51846. if (this.useBuiltInControls && this.webXRMode === WebXRMode.None) {
  51847. this.mouseMoveListener = this.onMouseMove.bind(this);
  51848. this.renderer.domElement.addEventListener('pointermove', this.mouseMoveListener, false);
  51849. this.mouseDownListener = this.onMouseDown.bind(this);
  51850. this.renderer.domElement.addEventListener('pointerdown', this.mouseDownListener, false);
  51851. this.mouseUpListener = this.onMouseUp.bind(this);
  51852. this.renderer.domElement.addEventListener('pointerup', this.mouseUpListener, false);
  51853. this.keyDownListener = this.onKeyDown.bind(this);
  51854. window.addEventListener('keydown', this.keyDownListener, false);
  51855. }
  51856. }
  51857. removeEventHandlers() {
  51858. if (this.useBuiltInControls) {
  51859. this.renderer.domElement.removeEventListener('pointermove', this.mouseMoveListener);
  51860. this.mouseMoveListener = null;
  51861. this.renderer.domElement.removeEventListener('pointerdown', this.mouseDownListener);
  51862. this.mouseDownListener = null;
  51863. this.renderer.domElement.removeEventListener('pointerup', this.mouseUpListener);
  51864. this.mouseUpListener = null;
  51865. window.removeEventListener('keydown', this.keyDownListener);
  51866. this.keyDownListener = null;
  51867. }
  51868. }
  51869. setRenderMode(renderMode) {
  51870. this.renderMode = renderMode;
  51871. }
  51872. onMouseMove(mouse) {
  51873. this.mousePosition.set(mouse.offsetX, mouse.offsetY);
  51874. }
  51875. onMouseDown() {
  51876. this.mouseDownPosition.copy(this.mousePosition);
  51877. this.mouseDownTime = getCurrentTime();
  51878. }
  51879. onMouseClick(mouse) {
  51880. this.mousePosition.set(mouse.offsetX, mouse.offsetY);
  51881. this.checkForFocalPointChange();
  51882. }
  51883. getRenderDimensions(outDimensions) {
  51884. if (this.rootElement) {
  51885. outDimensions.x = this.rootElement.offsetWidth;
  51886. outDimensions.y = this.rootElement.offsetHeight;
  51887. } else {
  51888. this.renderer.getSize(outDimensions);
  51889. }
  51890. }
  51891. setOrthographicMode(orthographicMode) {
  51892. if (orthographicMode === this.camera.isOrthographicCamera) return;
  51893. var fromCamera = this.camera;
  51894. var toCamera = orthographicMode ? this.orthographicCamera : this.perspectiveCamera;
  51895. toCamera.position.copy(fromCamera.position);
  51896. toCamera.up.copy(fromCamera.up);
  51897. toCamera.rotation.copy(fromCamera.rotation);
  51898. toCamera.quaternion.copy(fromCamera.quaternion);
  51899. toCamera.matrix.copy(fromCamera.matrix);
  51900. this.camera = toCamera;
  51901. if (this.controls) {
  51902. var resetControls = controls => {
  51903. controls.saveState();
  51904. controls.reset();
  51905. };
  51906. var fromControls = this.controls;
  51907. var toControls = orthographicMode ? this.orthographicControls : this.perspectiveControls;
  51908. resetControls(toControls);
  51909. resetControls(fromControls);
  51910. toControls.target.copy(fromControls.target);
  51911. if (orthographicMode) {
  51912. Viewer.setCameraZoomFromPosition(toCamera, fromCamera, fromControls);
  51913. } else {
  51914. Viewer.setCameraPositionFromZoom(toCamera, fromCamera, toControls);
  51915. }
  51916. this.controls = toControls;
  51917. this.camera.lookAt(this.controls.target);
  51918. }
  51919. }
  51920. adjustForWebXRStereo(renderDimensions) {
  51921. // TODO: Figure out a less hacky way to determine if stereo rendering is active
  51922. if (this.camera && this.webXRActive) {
  51923. var xrCamera = this.renderer.xr.getCamera();
  51924. var xrCameraProj00 = xrCamera.projectionMatrix.elements[0];
  51925. var cameraProj00 = this.camera.projectionMatrix.elements[0];
  51926. renderDimensions.x *= cameraProj00 / xrCameraProj00;
  51927. }
  51928. }
  51929. isLoadingOrUnloading() {
  51930. return Object.keys(this.splatSceneDownloadPromises).length > 0 || this.splatSceneDownloadAndBuildPromise !== null || this.splatSceneRemovalPromise !== null;
  51931. }
  51932. isDisposingOrDisposed() {
  51933. return this.disposing || this.disposed;
  51934. }
  51935. addSplatSceneDownloadPromise(promise) {
  51936. this.splatSceneDownloadPromises[promise.id] = promise;
  51937. }
  51938. removeSplatSceneDownloadPromise(promise) {
  51939. delete this.splatSceneDownloadPromises[promise.id];
  51940. }
  51941. setSplatSceneDownloadAndBuildPromise(promise) {
  51942. this.splatSceneDownloadAndBuildPromise = promise;
  51943. }
  51944. clearSplatSceneDownloadAndBuildPromise() {
  51945. this.splatSceneDownloadAndBuildPromise = null;
  51946. }
  51947. /**
  51948. * Add a splat scene to the viewer and display any loading UI if appropriate.
  51949. * @param {string} path Path to splat scene to be loaded
  51950. * @param {object} options {
  51951. *
  51952. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  51953. * value (valid range: 0 - 255), defaults to 1
  51954. *
  51955. * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true
  51956. *
  51957. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  51958. *
  51959. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  51960. *
  51961. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  51962. *
  51963. * onProgress: Function to be called as file data are received, or other processing occurs
  51964. *
  51965. * }
  51966. * @return {AbortablePromise}
  51967. */
  51968. addSplatScene(path) {
  51969. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  51970. if (this.isLoadingOrUnloading()) {
  51971. throw new Error('Cannot add splat scene while another load or unload is already in progress.');
  51972. }
  51973. if (this.isDisposingOrDisposed()) {
  51974. throw new Error('Cannot add splat scene after dispose() is called.');
  51975. }
  51976. var format = options.format !== undefined && options.format !== null ? options.format : sceneFormatFromPath(path);
  51977. var streamBuildSections = Viewer.isStreamable(format) && options.streamView;
  51978. var showLoadingUI = options.showLoadingUI !== undefined && options.showLoadingUI !== null ? options.showLoadingUI : true;
  51979. var loadingUITaskId = null;
  51980. if (showLoadingUI) {
  51981. this.loadingSpinner.removeAllTasks();
  51982. loadingUITaskId = this.loadingSpinner.addTask('Downloading...');
  51983. }
  51984. var hideLoadingUI = () => {
  51985. this.loadingProgressBar.hide();
  51986. this.loadingSpinner.removeAllTasks();
  51987. };
  51988. var onProgressUIUpdate = (percentComplete, percentCompleteLabel, loaderStatus) => {
  51989. if (showLoadingUI) {
  51990. if (loaderStatus === LoaderStatus.Downloading) {
  51991. if (percentComplete == 100) {
  51992. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Download complete!');
  51993. } else {
  51994. if (streamBuildSections) {
  51995. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Downloading splats...');
  51996. } else {
  51997. var suffix = percentCompleteLabel ? ": ".concat(percentCompleteLabel) : "...";
  51998. this.loadingSpinner.setMessageForTask(loadingUITaskId, "Downloading".concat(suffix));
  51999. }
  52000. }
  52001. } else if (loaderStatus === LoaderStatus.Processing) {
  52002. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Processing splats...');
  52003. } else {
  52004. this.loadingSpinner.setMessageForTask(loadingUITaskId, 'Ready!');
  52005. }
  52006. }
  52007. };
  52008. var downloadDone = false;
  52009. var downloadedPercentage = 0;
  52010. var splatBuffersAddedUIUpdate = (firstBuild, finalBuild) => {
  52011. if (showLoadingUI) {
  52012. if (firstBuild && streamBuildSections || finalBuild && !streamBuildSections) {
  52013. this.runAfterFirstSort.push(() => {
  52014. this.loadingSpinner.removeTask(loadingUITaskId);
  52015. if (!finalBuild && !downloadDone) this.loadingProgressBar.show();
  52016. });
  52017. }
  52018. if (streamBuildSections) {
  52019. if (finalBuild) {
  52020. downloadDone = true;
  52021. this.loadingProgressBar.hide();
  52022. } else {
  52023. this.loadingProgressBar.setProgress(downloadedPercentage);
  52024. }
  52025. }
  52026. }
  52027. };
  52028. var onProgress = (percentComplete, percentCompleteLabel, loaderStatus) => {
  52029. downloadedPercentage = percentComplete;
  52030. onProgressUIUpdate(percentComplete, percentCompleteLabel, loaderStatus);
  52031. if (options.onProgress) options.onProgress(percentComplete, percentCompleteLabel, loaderStatus);
  52032. };
  52033. var buildSection = (splatBuffer, firstBuild, finalBuild) => {
  52034. if (!streamBuildSections && options.onProgress) options.onProgress(0, '0%', LoaderStatus.Processing);
  52035. var addSplatBufferOptions = {
  52036. 'rotation': options.rotation || options.orientation,
  52037. 'position': options.position,
  52038. 'scale': options.scale,
  52039. 'splatAlphaRemovalThreshold': options.splatAlphaRemovalThreshold
  52040. };
  52041. return this.addSplatBuffers([splatBuffer], [addSplatBufferOptions], finalBuild, firstBuild && showLoadingUI, showLoadingUI).then(() => {
  52042. if (!streamBuildSections && options.onProgress) options.onProgress(100, '100%', LoaderStatus.Processing);
  52043. splatBuffersAddedUIUpdate(firstBuild, finalBuild);
  52044. });
  52045. };
  52046. var loadFunc = streamBuildSections ? this.downloadAndBuildSingleSplatSceneStreaming.bind(this) : this.downloadAndBuildSingleSplatSceneNonStreaming.bind(this);
  52047. return loadFunc(path, format, options.splatAlphaRemovalThreshold, buildSection.bind(this), onProgress, hideLoadingUI.bind(this));
  52048. }
  52049. /**
  52050. * Download a single non-streamed splat scene, convert to splat buffer and then rebuild the viewer's splat mesh
  52051. * by calling 'buildFunc'. Also sets/clears relevant instance synchronization objects, and calls appropriate functions
  52052. * on success or failure.
  52053. * @param {string} path Path to splat scene to be loaded
  52054. * @param {SceneFormat} format Format of the splat scene file
  52055. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255)
  52056. * @param {function} buildFunc Function to build the viewer's splat mesh with the downloaded splat buffer
  52057. * @param {function} onProgress Function to be called as file data are received, or other processing occurs
  52058. * @param {function} onException Function to be called when exception occurs
  52059. * @return {AbortablePromise}
  52060. */
  52061. downloadAndBuildSingleSplatSceneNonStreaming(path, format, splatAlphaRemovalThreshold, buildFunc, onProgress, onException) {
  52062. var downloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold, onProgress, false, undefined, format).then(splatBuffer => {
  52063. this.removeSplatSceneDownloadPromise(downloadPromise);
  52064. return buildFunc(splatBuffer, true, true).then(() => {
  52065. this.clearSplatSceneDownloadAndBuildPromise();
  52066. });
  52067. }).catch(e => {
  52068. if (onException) onException();
  52069. this.clearSplatSceneDownloadAndBuildPromise();
  52070. this.removeSplatSceneDownloadPromise(downloadPromise);
  52071. if (!(e instanceof AbortedPromiseError)) {
  52072. throw new Error("Viewer::addSplatScene -> Could not load file ".concat(path));
  52073. }
  52074. });
  52075. this.addSplatSceneDownloadPromise(downloadPromise);
  52076. this.setSplatSceneDownloadAndBuildPromise(downloadPromise);
  52077. return downloadPromise;
  52078. }
  52079. /**
  52080. * Download a single splat scene and convert to splat buffer in a streamed manner, allowing rendering as the file downloads.
  52081. * As each section is downloaded, the viewer's splat mesh is rebuilt by calling 'buildFunc'
  52082. * Also sets/clears relevant instance synchronization objects, and calls appropriate functions on success or failure.
  52083. * @param {string} path Path to splat scene to be loaded
  52084. * @param {SceneFormat} format Format of the splat scene file
  52085. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified value (valid range: 0 - 255)
  52086. * @param {function} buildFunc Function to rebuild the viewer's splat mesh after a new splat buffer section is downloaded
  52087. * @param {function} onDownloadProgress Function to be called as file data are received
  52088. * @param {function} onDownloadException Function to be called when exception occurs at any point during the full download
  52089. * @return {AbortablePromise}
  52090. */
  52091. downloadAndBuildSingleSplatSceneStreaming(path, format, splatAlphaRemovalThreshold, buildFunc, onDownloadProgress, onDownloadException) {
  52092. var firstStreamedSectionDownloadAndBuildResolver;
  52093. var firstStreamedSectionDownloadAndBuildRejecter;
  52094. var splatSceneDownloadAndBuildResolver;
  52095. var splatSceneDownloadAndBuildRejecter;
  52096. var steamedSectionBuildCount = 0;
  52097. var streamedSectionBuilding = false;
  52098. var queuedStreamedSectionBuilds = [];
  52099. var checkAndBuildStreamedSections = () => {
  52100. if (queuedStreamedSectionBuilds.length > 0 && !streamedSectionBuilding && !this.isDisposingOrDisposed()) {
  52101. streamedSectionBuilding = true;
  52102. var queuedBuild = queuedStreamedSectionBuilds.shift();
  52103. buildFunc(queuedBuild.splatBuffer, queuedBuild.firstBuild, queuedBuild.finalBuild).then(() => {
  52104. streamedSectionBuilding = false;
  52105. if (queuedBuild.firstBuild) {
  52106. firstStreamedSectionDownloadAndBuildRejecter = null;
  52107. firstStreamedSectionDownloadAndBuildResolver();
  52108. } else if (queuedBuild.finalBuild) {
  52109. splatSceneDownloadAndBuildResolver();
  52110. this.clearSplatSceneDownloadAndBuildPromise();
  52111. }
  52112. if (queuedStreamedSectionBuilds.length > 0) delayedExecute(() => checkAndBuildStreamedSections());
  52113. });
  52114. }
  52115. };
  52116. var onStreamedSectionProgress = (splatBuffer, finalBuild) => {
  52117. if (!this.isDisposingOrDisposed()) {
  52118. if (finalBuild || queuedStreamedSectionBuilds.length === 0 || splatBuffer.getSplatCount() > queuedStreamedSectionBuilds[0].splatBuffer.getSplatCount()) {
  52119. queuedStreamedSectionBuilds.push({
  52120. splatBuffer,
  52121. firstBuild: steamedSectionBuildCount === 0,
  52122. finalBuild
  52123. });
  52124. steamedSectionBuildCount++;
  52125. checkAndBuildStreamedSections();
  52126. }
  52127. }
  52128. };
  52129. var splatSceneDownloadPromise = this.downloadSplatSceneToSplatBuffer(path, splatAlphaRemovalThreshold, onDownloadProgress, true, onStreamedSectionProgress, format);
  52130. var firstStreamedSectionBuildPromise = new AbortablePromise((resolver, rejecter) => {
  52131. firstStreamedSectionDownloadAndBuildResolver = resolver;
  52132. firstStreamedSectionDownloadAndBuildRejecter = rejecter;
  52133. }, splatSceneDownloadPromise.abortHandler);
  52134. var splatSceneDownloadAndBuildPromise = new AbortablePromise((resolver, rejecter) => {
  52135. splatSceneDownloadAndBuildResolver = resolver;
  52136. splatSceneDownloadAndBuildRejecter = rejecter;
  52137. });
  52138. this.addSplatSceneDownloadPromise(splatSceneDownloadPromise);
  52139. this.setSplatSceneDownloadAndBuildPromise(splatSceneDownloadAndBuildPromise);
  52140. splatSceneDownloadPromise.then(() => {
  52141. this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise);
  52142. }).catch(e => {
  52143. this.clearSplatSceneDownloadAndBuildPromise();
  52144. this.removeSplatSceneDownloadPromise(splatSceneDownloadPromise);
  52145. if (!(e instanceof AbortedPromiseError)) {
  52146. splatSceneDownloadAndBuildRejecter(e);
  52147. if (firstStreamedSectionDownloadAndBuildRejecter) firstStreamedSectionDownloadAndBuildRejecter(e);
  52148. if (onDownloadException) onDownloadException(e);
  52149. }
  52150. });
  52151. return firstStreamedSectionBuildPromise;
  52152. }
  52153. /**
  52154. * Add multiple splat scenes to the viewer and display any loading UI if appropriate.
  52155. * @param {Array<object>} sceneOptions Array of per-scene options: {
  52156. *
  52157. * path: Path to splat scene to be loaded
  52158. *
  52159. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  52160. * value (valid range: 0 - 255), defaults to 1
  52161. *
  52162. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  52163. *
  52164. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  52165. *
  52166. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  52167. * }
  52168. * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true
  52169. * @param {function} onProgress Function to be called as file data are received
  52170. * @return {AbortablePromise}
  52171. */
  52172. addSplatScenes(sceneOptions) {
  52173. var showLoadingUI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  52174. var onProgress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  52175. if (this.isLoadingOrUnloading()) {
  52176. throw new Error('Cannot add splat scene while another load or unload is already in progress.');
  52177. }
  52178. if (this.isDisposingOrDisposed()) {
  52179. throw new Error('Cannot add splat scene after dispose() is called.');
  52180. }
  52181. var fileCount = sceneOptions.length;
  52182. var percentComplete = [];
  52183. if (showLoadingUI) {
  52184. this.loadingSpinner.removeAllTasks();
  52185. this.loadingSpinner.show();
  52186. }
  52187. var onLoadProgress = (fileIndex, percent, percentLabel) => {
  52188. percentComplete[fileIndex] = percent;
  52189. var totalPercent = 0;
  52190. for (var i = 0; i < fileCount; i++) totalPercent += percentComplete[i] || 0;
  52191. totalPercent = totalPercent / fileCount;
  52192. percentLabel = "".concat(totalPercent.toFixed(2), "%");
  52193. if (showLoadingUI) {
  52194. this.loadingSpinner.setMessage(totalPercent == 100 ? "Download complete!" : "Downloading: ".concat(percentLabel));
  52195. }
  52196. if (onProgress) onProgress(totalPercent, percentLabel, LoaderStatus.Downloading);
  52197. };
  52198. var downloadPromises = [];
  52199. var nativeLoadPromises = [];
  52200. var abortHandlers = [];
  52201. for (var i = 0; i < sceneOptions.length; i++) {
  52202. var _options2 = sceneOptions[i];
  52203. var format = _options2.format !== undefined && _options2.format !== null ? _options2.format : sceneFormatFromPath(_options2.path);
  52204. var _downloadPromise = this.downloadSplatSceneToSplatBuffer(_options2.path, _options2.splatAlphaRemovalThreshold, onLoadProgress.bind(this, i), false, undefined, format);
  52205. abortHandlers.push(_downloadPromise.abortHandler);
  52206. downloadPromises.push(_downloadPromise);
  52207. nativeLoadPromises.push(_downloadPromise.promise);
  52208. this.addSplatSceneDownloadPromise(_downloadPromise);
  52209. }
  52210. var downloadPromise = new AbortablePromise((resolve, reject) => {
  52211. Promise.all(nativeLoadPromises).then(splatBuffers => {
  52212. if (showLoadingUI) this.loadingSpinner.hide();
  52213. if (onProgress) options.onProgress(0, '0%', LoaderStatus.Processing);
  52214. this.addSplatBuffers(splatBuffers, sceneOptions, true, showLoadingUI, showLoadingUI).then(() => {
  52215. if (onProgress) onProgress(100, '100%', LoaderStatus.Processing);
  52216. this.clearSplatSceneDownloadAndBuildPromise();
  52217. resolve();
  52218. });
  52219. }).catch(e => {
  52220. if (showLoadingUI) this.loadingSpinner.hide();
  52221. this.clearSplatSceneDownloadAndBuildPromise();
  52222. if (!(e instanceof AbortedPromiseError)) {
  52223. reject(new Error("Viewer::addSplatScenes -> Could not load one or more splat scenes."));
  52224. } else {
  52225. resolve();
  52226. }
  52227. }).finally(() => {
  52228. for (var _downloadPromise2 of downloadPromises) {
  52229. this.removeSplatSceneDownloadPromise(_downloadPromise2);
  52230. }
  52231. });
  52232. }, () => {
  52233. for (var abortHandler of abortHandlers) abortHandler();
  52234. });
  52235. this.setSplatSceneDownloadAndBuildPromise(downloadPromise);
  52236. return downloadPromise;
  52237. }
  52238. /**
  52239. * Download a splat scene and convert to SplatBuffer instance.
  52240. * @param {string} path Path to splat scene to be loaded
  52241. * @param {number} splatAlphaRemovalThreshold Ignore any splats with an alpha less than the specified
  52242. * value (valid range: 0 - 255), defaults to 1
  52243. *
  52244. * @param {function} onProgress Function to be called as file data are received
  52245. * @param {boolean} streamBuiltSections Construct file sections into splat buffers as they are downloaded
  52246. * @param {function} onSectionBuilt Function to be called when new section is added to the file
  52247. * @param {string} format File format of the scene
  52248. * @return {AbortablePromise}
  52249. */
  52250. downloadSplatSceneToSplatBuffer(path) {
  52251. var splatAlphaRemovalThreshold = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  52252. var onProgress = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
  52253. var streamBuiltSections = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  52254. var onSectionBuilt = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
  52255. var format = arguments.length > 5 ? arguments[5] : undefined;
  52256. if (format === SceneFormat.Splat) {
  52257. return SplatLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt, splatAlphaRemovalThreshold, 0, false);
  52258. } else if (format === SceneFormat.KSplat) {
  52259. return KSplatLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt);
  52260. } else if (format === SceneFormat.Ply) {
  52261. return PlyLoader.loadFromURL(path, onProgress, streamBuiltSections, onSectionBuilt, splatAlphaRemovalThreshold, 0, this.sphericalHarmonicsDegree);
  52262. }
  52263. return AbortablePromise.reject(new Error("Viewer::downloadSplatSceneToSplatBuffer -> File format not supported: ".concat(path)));
  52264. }
  52265. static isStreamable(format) {
  52266. return format === SceneFormat.Splat || format === SceneFormat.KSplat || format === SceneFormat.Ply;
  52267. }
  52268. /**
  52269. * Add one or more instances of SplatBuffer to the SplatMesh instance managed by the viewer. This function is additive; all splat
  52270. * buffers contained by the viewer's splat mesh before calling this function will be preserved.
  52271. * @param {Array<SplatBuffer>} splatBuffers SplatBuffer instances
  52272. * @param {Array<object>} splatBufferOptions Array of options objects: {
  52273. *
  52274. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  52275. * value (valid range: 0 - 255), defaults to 1
  52276. *
  52277. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  52278. *
  52279. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  52280. *
  52281. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  52282. * }
  52283. * @param {boolean} finalBuild Will the splat mesh be in its final state after this build?
  52284. * @param {boolean} showLoadingUIForSplatTreeBuild Whether or not to show the loading spinner during construction of the splat tree.
  52285. * @return {object} Object containing info about the splats that are updated
  52286. */
  52287. addSplatBuffersToMesh(splatBuffers, splatBufferOptions) {
  52288. var finalBuild = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  52289. var showLoadingUIForSplatTreeBuild = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
  52290. if (this.isDisposingOrDisposed()) return;
  52291. var allSplatBuffers = this.splatMesh.splatBuffers || [];
  52292. var allSplatBufferOptions = this.splatMesh.splatBufferOptions || [];
  52293. allSplatBuffers.push(...splatBuffers);
  52294. allSplatBufferOptions.push(...splatBufferOptions);
  52295. if (this.renderer) this.splatMesh.setRenderer(this.renderer);
  52296. var splatOptimizingTaskId;
  52297. var onSplatTreeIndexesUpload = finished => {
  52298. if (this.isDisposingOrDisposed()) return;
  52299. var splatCount = this.splatMesh.getSplatCount();
  52300. if (showLoadingUIForSplatTreeBuild && splatCount >= MIN_SPLAT_COUNT_TO_SHOW_SPLAT_TREE_LOADING_SPINNER) {
  52301. if (!finished && !splatOptimizingTaskId) {
  52302. this.loadingSpinner.setMinimized(true, true);
  52303. splatOptimizingTaskId = this.loadingSpinner.addTask('Optimizing splats...');
  52304. }
  52305. }
  52306. };
  52307. var onSplatTreeReady = finished => {
  52308. if (this.isDisposingOrDisposed()) return;
  52309. if (finished && splatOptimizingTaskId) {
  52310. this.loadingSpinner.removeTask(splatOptimizingTaskId);
  52311. }
  52312. };
  52313. return this.splatMesh.build(allSplatBuffers, allSplatBufferOptions, true, finalBuild, onSplatTreeIndexesUpload, onSplatTreeReady);
  52314. }
  52315. /**
  52316. * Set up the splat sorting web worker.
  52317. * @param {SplatMesh} splatMesh SplatMesh instance that contains the splats to be sorted
  52318. * @return {Promise}
  52319. */
  52320. setupSortWorker(splatMesh) {
  52321. if (this.isDisposingOrDisposed()) return;
  52322. return new Promise(resolve => {
  52323. var DistancesArrayType = this.integerBasedSort ? Int32Array : Float32Array;
  52324. var splatCount = splatMesh.getSplatCount();
  52325. var maxSplatCount = splatMesh.getMaxSplatCount();
  52326. this.sortWorker = createSortWorker(maxSplatCount, this.sharedMemoryForWorkers, this.integerBasedSort, this.splatMesh.dynamicMode);
  52327. var sortCount = 0;
  52328. this.sortWorker.onmessage = e => {
  52329. if (e.data.sortDone) {
  52330. this.sortRunning = false;
  52331. if (this.sharedMemoryForWorkers) {
  52332. this.splatMesh.updateRenderIndexes(this.sortWorkerSortedIndexes, e.data.splatRenderCount);
  52333. } else {
  52334. var sortedIndexes = new Uint32Array(e.data.sortedIndexes.buffer, 0, e.data.splatRenderCount);
  52335. this.splatMesh.updateRenderIndexes(sortedIndexes, e.data.splatRenderCount);
  52336. }
  52337. this.lastSortTime = e.data.sortTime;
  52338. this.sortPromiseResolver();
  52339. this.sortPromiseResolver = null;
  52340. this.forceRenderNextFrame();
  52341. if (sortCount === 0) {
  52342. this.runAfterFirstSort.forEach(func => {
  52343. func();
  52344. });
  52345. this.runAfterFirstSort.length = 0;
  52346. }
  52347. sortCount++;
  52348. } else if (e.data.sortCanceled) {
  52349. this.sortRunning = false;
  52350. } else if (e.data.sortSetupPhase1Complete) {
  52351. //划分好共享数据
  52352. if (this.logLevel >= LogLevel.Info) console.log('Sorting web worker WASM setup complete.');
  52353. if (this.sharedMemoryForWorkers) {
  52354. this.sortWorkerSortedIndexes = new Uint32Array(e.data.sortedIndexesBuffer,
  52355. //这是以后就是每次要渲染的indexes
  52356. e.data.sortedIndexesOffset, maxSplatCount);
  52357. this.sortWorkerIndexesToSort = new Uint32Array(e.data.indexesToSortBuffer,
  52358. //准备sort的点,每次镜头改变时先选出要渲染的点,再排序
  52359. e.data.indexesToSortOffset, maxSplatCount);
  52360. this.sortWorkerPrecomputedDistances = new DistancesArrayType(e.data.precomputedDistancesBuffer, e.data.precomputedDistancesOffset, maxSplatCount);
  52361. this.sortWorkerTransforms = new Float32Array(e.data.transformsBuffer, e.data.transformsOffset, Constants.MaxScenes * 16);
  52362. } else {
  52363. this.sortWorkerIndexesToSort = new Uint32Array(maxSplatCount);
  52364. this.sortWorkerPrecomputedDistances = new DistancesArrayType(maxSplatCount);
  52365. this.sortWorkerTransforms = new Float32Array(Constants.MaxScenes * 16);
  52366. }
  52367. for (var i = 0; i < splatCount; i++) this.sortWorkerIndexesToSort[i] = i; //初始化待sort的所有index,按顺序赋值就行
  52368. this.sortWorker.maxSplatCount = maxSplatCount; //总点数
  52369. if (this.logLevel >= LogLevel.Info) {
  52370. console.log('Sorting web worker ready.');
  52371. var splatDataTextures = this.splatMesh.getSplatDataTextures();
  52372. var covariancesTextureSize = splatDataTextures.covariances.size;
  52373. var centersColorsTextureSize = splatDataTextures.centerColors.size;
  52374. console.log('Covariances texture size: ' + covariancesTextureSize.x + ' x ' + covariancesTextureSize.y);
  52375. console.log('Centers/colors texture size: ' + centersColorsTextureSize.x + ' x ' + centersColorsTextureSize.y);
  52376. }
  52377. resolve();
  52378. }
  52379. };
  52380. });
  52381. }
  52382. disposeSortWorker() {
  52383. if (this.sortWorker) this.sortWorker.terminate();
  52384. this.sortWorker = null;
  52385. this.sortPromise = null;
  52386. if (this.sortPromiseResolver) {
  52387. this.sortPromiseResolver();
  52388. this.sortPromiseResolver = null;
  52389. }
  52390. this.sortRunning = false;
  52391. }
  52392. removeSplatScene(index) {
  52393. var showLoadingUI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  52394. if (this.isLoadingOrUnloading()) {
  52395. throw new Error('Cannot remove splat scene while another load or unload is already in progress.');
  52396. }
  52397. if (this.isDisposingOrDisposed()) {
  52398. throw new Error('Cannot remove splat scene after dispose() is called.');
  52399. }
  52400. var sortPromise;
  52401. this.splatSceneRemovalPromise = new Promise((resolve, reject) => {
  52402. var revmovalTaskId;
  52403. if (showLoadingUI) {
  52404. this.loadingSpinner.removeAllTasks();
  52405. this.loadingSpinner.show();
  52406. revmovalTaskId = this.loadingSpinner.addTask('Removing splat scene...');
  52407. }
  52408. var checkAndHideLoadingUI = () => {
  52409. if (showLoadingUI) {
  52410. this.loadingSpinner.hide();
  52411. this.loadingSpinner.removeTask(revmovalTaskId);
  52412. }
  52413. };
  52414. var onDone = error => {
  52415. checkAndHideLoadingUI();
  52416. this.splatSceneRemovalPromise = null;
  52417. if (!error) resolve();else reject(error);
  52418. };
  52419. var checkForEarlyExit = () => {
  52420. if (this.isDisposingOrDisposed()) {
  52421. onDone();
  52422. return true;
  52423. }
  52424. return false;
  52425. };
  52426. sortPromise = this.sortPromise || Promise.resolve();
  52427. sortPromise.then(() => {
  52428. if (checkForEarlyExit()) return;
  52429. var savedSplatBuffers = [];
  52430. var savedSceneOptions = [];
  52431. var savedSceneTransformComponents = [];
  52432. var savedVisibleRegionFadeStartRadius = this.splatMesh.visibleRegionFadeStartRadius;
  52433. for (var i = 0; i < this.splatMesh.scenes.length; i++) {
  52434. if (i !== index) {
  52435. var scene = this.splatMesh.scenes[i];
  52436. savedSplatBuffers.push(scene.splatBuffer);
  52437. savedSceneOptions.push(this.splatMesh.sceneOptions[i]);
  52438. savedSceneTransformComponents.push({
  52439. 'position': scene.position.clone(),
  52440. 'quaternion': scene.quaternion.clone(),
  52441. 'scale': scene.scale.clone()
  52442. });
  52443. }
  52444. }
  52445. this.disposeSortWorker();
  52446. this.splatMesh.dispose();
  52447. this.createSplatMesh();
  52448. this.addSplatBuffers(savedSplatBuffers, savedSceneOptions, true, false, true).then(() => {
  52449. if (checkForEarlyExit()) return;
  52450. checkAndHideLoadingUI();
  52451. this.splatMesh.visibleRegionFadeStartRadius = savedVisibleRegionFadeStartRadius;
  52452. this.splatMesh.scenes.forEach((scene, index) => {
  52453. scene.position.copy(savedSceneTransformComponents[index].position);
  52454. scene.quaternion.copy(savedSceneTransformComponents[index].quaternion);
  52455. scene.scale.copy(savedSceneTransformComponents[index].scale);
  52456. });
  52457. this.splatMesh.updateTransforms();
  52458. this.splatRenderReady = false;
  52459. this.updateSplatSort(true).then(() => {
  52460. if (checkForEarlyExit()) {
  52461. this.splatRenderReady = true;
  52462. return;
  52463. }
  52464. sortPromise = this.sortPromise || Promise.resolve();
  52465. sortPromise.then(() => {
  52466. this.splatRenderReady = true;
  52467. onDone();
  52468. });
  52469. });
  52470. }).catch(e => {
  52471. onDone(e);
  52472. });
  52473. });
  52474. });
  52475. return this.splatSceneRemovalPromise;
  52476. }
  52477. /**
  52478. * Start self-driven mode
  52479. */
  52480. start() {
  52481. if (this.selfDrivenMode) {
  52482. if (this.webXRMode) {
  52483. this.renderer.setAnimationLoop(this.selfDrivenUpdateFunc);
  52484. } else {
  52485. this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc);
  52486. }
  52487. this.selfDrivenModeRunning = true;
  52488. } else {
  52489. throw new Error('Cannot start viewer unless it is in self driven mode.');
  52490. }
  52491. }
  52492. /**
  52493. * Stop self-driven mode
  52494. */
  52495. stop() {
  52496. if (this.selfDrivenMode && this.selfDrivenModeRunning) {
  52497. if (!this.webXRMode) {
  52498. cancelAnimationFrame(this.requestFrameId);
  52499. }
  52500. this.selfDrivenModeRunning = false;
  52501. }
  52502. }
  52503. /**
  52504. * Dispose of all resources held directly and indirectly by this viewer.
  52505. */
  52506. dispose() {
  52507. var _this = this;
  52508. return _asyncToGenerator(function* () {
  52509. _this.disposing = true;
  52510. var waitPromises = [];
  52511. var promisesToAbort = [];
  52512. for (var promiseKey in _this.splatSceneDownloadPromises) {
  52513. if (_this.splatSceneDownloadPromises.hasOwnProperty(promiseKey)) {
  52514. var downloadPromiseToAbort = _this.splatSceneDownloadPromises[promiseKey];
  52515. promisesToAbort.push(downloadPromiseToAbort);
  52516. waitPromises.push(downloadPromiseToAbort.promise);
  52517. }
  52518. }
  52519. if (_this.sortPromise) {
  52520. waitPromises.push(_this.sortPromise);
  52521. }
  52522. var disposePromise = Promise.all(waitPromises).finally(() => {
  52523. _this.stop();
  52524. if (_this.controls) {
  52525. _this.controls.dispose();
  52526. _this.controls = null;
  52527. }
  52528. if (_this.splatMesh) {
  52529. _this.splatMesh.dispose();
  52530. _this.splatMesh = null;
  52531. }
  52532. if (_this.sceneHelper) {
  52533. _this.sceneHelper.dispose();
  52534. _this.sceneHelper = null;
  52535. }
  52536. if (_this.resizeObserver) {
  52537. _this.resizeObserver.unobserve(_this.rootElement);
  52538. _this.resizeObserver = null;
  52539. }
  52540. _this.disposeSortWorker();
  52541. _this.removeEventHandlers();
  52542. _this.loadingSpinner.removeAllTasks();
  52543. _this.loadingSpinner.setContainer(null);
  52544. _this.loadingProgressBar.hide();
  52545. _this.loadingProgressBar.setContainer(null);
  52546. _this.infoPanel.setContainer(null);
  52547. _this.camera = null;
  52548. _this.threeScene = null;
  52549. _this.splatRenderReady = false;
  52550. _this.initialized = false;
  52551. if (_this.renderer) {
  52552. if (!_this.usingExternalRenderer) {
  52553. _this.rootElement.removeChild(_this.renderer.domElement);
  52554. _this.renderer.dispose();
  52555. }
  52556. _this.renderer = null;
  52557. }
  52558. if (!_this.usingExternalRenderer) {
  52559. document.body.removeChild(_this.rootElement);
  52560. }
  52561. _this.sortWorkerSortedIndexes = null;
  52562. _this.sortWorkerIndexesToSort = null;
  52563. _this.sortWorkerPrecomputedDistances = null;
  52564. _this.sortWorkerTransforms = null;
  52565. _this.disposed = true;
  52566. _this.disposing = false;
  52567. });
  52568. promisesToAbort.forEach(toAbort => {
  52569. toAbort.abort();
  52570. });
  52571. return disposePromise;
  52572. })();
  52573. }
  52574. selfDrivenUpdate() {
  52575. /* if (this.selfDrivenMode && !this.webXRMode) { //xzw delete
  52576. this.requestFrameId = requestAnimationFrame(this.selfDrivenUpdateFunc);
  52577. } */
  52578. this.update();
  52579. if (this.shouldRender()) {
  52580. this.render();
  52581. this.consecutiveRenderFrames++;
  52582. } else {
  52583. this.consecutiveRenderFrames = 0;
  52584. }
  52585. this.renderNextFrame = false;
  52586. }
  52587. forceRenderNextFrame() {
  52588. this.renderNextFrame = true;
  52589. }
  52590. update(renderer, camera) {
  52591. if (this.dropInMode) this.updateForDropInMode(renderer, camera);
  52592. if (!this.initialized || !this.splatRenderReady) return;
  52593. if (this.controls) {
  52594. this.controls.update();
  52595. if (this.camera.isOrthographicCamera && !this.usingExternalCamera) {
  52596. Viewer.setCameraPositionFromZoom(this.camera, this.camera, this.controls);
  52597. }
  52598. }
  52599. this.splatMesh.updateVisibleRegionFadeDistance(this.sceneRevealMode);
  52600. this.updateSplatSort();
  52601. this.updateForRendererSizeChanges();
  52602. this.updateSplatMesh();
  52603. this.updateMeshCursor();
  52604. this.updateFPS();
  52605. this.timingSensitiveUpdates();
  52606. this.updateInfoPanel();
  52607. this.updateControlPlane();
  52608. }
  52609. updateForDropInMode(renderer, camera) {
  52610. this.renderer = renderer;
  52611. if (this.splatMesh) this.splatMesh.setRenderer(this.renderer);
  52612. this.camera = camera;
  52613. if (this.controls) this.controls.object = camera;
  52614. this.init();
  52615. }
  52616. updateControlPlane() {
  52617. if (this.showControlPlane) {
  52618. this.sceneHelper.setControlPlaneVisibility(true);
  52619. this.sceneHelper.positionAndOrientControlPlane(this.controls.target, this.camera.up);
  52620. } else {
  52621. this.sceneHelper.setControlPlaneVisibility(false);
  52622. }
  52623. }
  52624. getSplatMesh() {
  52625. return this.splatMesh;
  52626. }
  52627. /**
  52628. * Get a reference to a splat scene.
  52629. * @param {number} sceneIndex The index of the scene to which the reference will be returned
  52630. * @return {SplatScene}
  52631. */
  52632. getSplatScene(sceneIndex) {
  52633. return this.splatMesh.getScene(sceneIndex);
  52634. }
  52635. isMobile() {
  52636. return navigator.userAgent.includes('Mobi');
  52637. }
  52638. }
  52639. /**
  52640. * DropInViewer: Wrapper for a Viewer instance that enables it to be added to a Three.js scene like
  52641. * any other Three.js scene object (Mesh, Object3D, etc.)
  52642. */
  52643. _defineProperty(Viewer, "setCameraPositionFromZoom", function () {
  52644. var tempVector = new THREE$2.Vector3();
  52645. return function (positionCamera, zoomedCamera, controls) {
  52646. var toLookAtDistance = 1 / (zoomedCamera.zoom * 0.001);
  52647. tempVector.copy(controls.target).sub(positionCamera.position).normalize().multiplyScalar(toLookAtDistance).negate();
  52648. positionCamera.position.copy(controls.target).add(tempVector);
  52649. };
  52650. }());
  52651. _defineProperty(Viewer, "setCameraZoomFromPosition", function () {
  52652. var tempVector = new THREE$2.Vector3();
  52653. return function (zoomCamera, positionZamera, controls) {
  52654. var toLookAtDistance = tempVector.copy(controls.target).sub(positionZamera.position).length();
  52655. zoomCamera.zoom = 1 / (toLookAtDistance * .001);
  52656. };
  52657. }());
  52658. class DropInViewer extends THREE$2.Group {
  52659. constructor() {
  52660. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  52661. super();
  52662. options.selfDrivenMode = false;
  52663. options.useBuiltInControls = false;
  52664. options.rootElement = null;
  52665. options.ignoreDevicePixelRatio = false;
  52666. options.dropInMode = true;
  52667. options.camera = undefined;
  52668. options.renderer = undefined;
  52669. this.viewer = new Viewer(options);
  52670. this.splatMesh = null;
  52671. this.callbackMesh = DropInViewer.createCallbackMesh();
  52672. this.add(this.callbackMesh);
  52673. this.callbackMesh.onBeforeRender = DropInViewer.onBeforeRender.bind(this, this.viewer);
  52674. }
  52675. /**
  52676. * Add a single splat scene to the viewer.
  52677. * @param {string} path Path to splat scene to be loaded
  52678. * @param {object} options {
  52679. *
  52680. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  52681. * value (valid range: 0 - 255), defaults to 1
  52682. *
  52683. * showLoadingUI: Display a loading spinner while the scene is loading, defaults to true
  52684. *
  52685. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  52686. *
  52687. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  52688. *
  52689. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  52690. *
  52691. * onProgress: Function to be called as file data are received
  52692. *
  52693. * }
  52694. * @return {AbortablePromise}
  52695. */
  52696. addSplatScene(path) {
  52697. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  52698. if (options.showLoadingUI !== false) options.showLoadingUI = true;
  52699. return this.viewer.addSplatScene(path, options);
  52700. }
  52701. /**
  52702. * Add multiple splat scenes to the viewer.
  52703. * @param {Array<object>} sceneOptions Array of per-scene options: {
  52704. *
  52705. * path: Path to splat scene to be loaded
  52706. *
  52707. * splatAlphaRemovalThreshold: Ignore any splats with an alpha less than the specified
  52708. * value (valid range: 0 - 255), defaults to 1
  52709. *
  52710. * position (Array<number>): Position of the scene, acts as an offset from its default position, defaults to [0, 0, 0]
  52711. *
  52712. * rotation (Array<number>): Rotation of the scene represented as a quaternion, defaults to [0, 0, 0, 1]
  52713. *
  52714. * scale (Array<number>): Scene's scale, defaults to [1, 1, 1]
  52715. * }
  52716. * @param {boolean} showLoadingUI Display a loading spinner while the scene is loading, defaults to true
  52717. * @return {AbortablePromise}
  52718. */
  52719. addSplatScenes(sceneOptions, showLoadingUI) {
  52720. if (showLoadingUI !== false) showLoadingUI = true;
  52721. return this.viewer.addSplatScenes(sceneOptions, showLoadingUI);
  52722. }
  52723. /**
  52724. * Get a reference to a splat scene.
  52725. * @param {number} sceneIndex The index of the scene to which the reference will be returned
  52726. * @return {SplatScene}
  52727. */
  52728. getSplatScene(sceneIndex) {
  52729. return this.viewer.getSplatScene(sceneIndex);
  52730. }
  52731. removeSplatScene(index) {
  52732. return this.viewer.removeSplatScene(index);
  52733. }
  52734. dispose() {
  52735. return this.viewer.dispose();
  52736. }
  52737. static onBeforeRender(viewer, renderer, threeScene, camera) {
  52738. if (this.splatMesh !== this.viewer.splatMesh) {
  52739. if (this.splatMesh) {
  52740. this.remove(this.splatMesh);
  52741. }
  52742. this.splatMesh = this.viewer.splatMesh;
  52743. this.add(this.viewer.splatMesh);
  52744. }
  52745. viewer.update(renderer, camera);
  52746. }
  52747. static createCallbackMesh() {
  52748. var geometry = new THREE$2.SphereGeometry(1, 8, 8);
  52749. var material = new THREE$2.MeshBasicMaterial();
  52750. material.colorWrite = false;
  52751. material.depthWrite = false;
  52752. var mesh = new THREE$2.Mesh(geometry, material);
  52753. mesh.frustumCulled = false;
  52754. return mesh;
  52755. }
  52756. }
  52757. var GAS = /*#__PURE__*/Object.freeze({
  52758. __proto__: null,
  52759. AbortablePromise: AbortablePromise,
  52760. CompressedPlyParser: CompressedPlyParser,
  52761. DropInViewer: DropInViewer,
  52762. KSplatLoader: KSplatLoader,
  52763. LoaderUtils: Utils$1,
  52764. LogLevel: LogLevel,
  52765. OrbitControls: OrbitControls,
  52766. PlyLoader: PlyLoader,
  52767. PlyParser: PlyParser,
  52768. RenderMode: RenderMode,
  52769. SceneFormat: SceneFormat,
  52770. SceneRevealMode: SceneRevealMode,
  52771. SplatBuffer: SplatBuffer,
  52772. SplatBufferGenerator: SplatBufferGenerator,
  52773. SplatLoader: SplatLoader,
  52774. SplatParser: SplatParser,
  52775. SplatPartitioner: SplatPartitioner,
  52776. Viewer: Viewer,
  52777. WebXRMode: WebXRMode
  52778. });
  52779. var renderOrders = {
  52780. line: 0,
  52781. spot: 15 //高过模型
  52782. };
  52783. var planeGeo$2 = new PlaneGeometry(1, 1);
  52784. var texLoader$7 = new TextureLoader();
  52785. var lineMat = new LineBasicMaterial({
  52786. color: '#ffffff'
  52787. });
  52788. var spotMat;
  52789. var defaultLineLength = 0.6;
  52790. var defaultSpotScale = 0.4;
  52791. class Tag extends Object3D {
  52792. constructor(o) {
  52793. super();
  52794. this.lineLength = o.lineLength != void 0 ? o.lineLength : defaultLineLength;
  52795. this.position.copy(o.position);
  52796. this.normal = o.normal != void 0 ? o.normal : new Vector3(0, 0, -1);
  52797. this.root = o.root;
  52798. //this.matrixAutoUpdate = false
  52799. this.build();
  52800. /* this.spot.addEventListener('mouseover',()=>{
  52801. }) */
  52802. }
  52803. build() {
  52804. if (!spotMat) {
  52805. spotMat = new MeshBasicMaterial({
  52806. transparent: true,
  52807. map: texLoader$7.load(Potree.resourcePath + '/textures/spot_default.png')
  52808. });
  52809. }
  52810. var endPos = this.normal.clone().multiplyScalar(this.lineLength);
  52811. this.line = LineDraw.createLine([new Vector3(0, 0, 0), endPos], {
  52812. mat: lineMat
  52813. });
  52814. var group = new Object3D();
  52815. this.spot = new Mesh(planeGeo$2, spotMat);
  52816. this.spot.scale.set(defaultSpotScale, defaultSpotScale, defaultSpotScale);
  52817. this.titleLabel = new TextSprite$2({
  52818. root: group,
  52819. text: '1',
  52820. sizeInfo: {
  52821. width2d: 200
  52822. },
  52823. textColor: {
  52824. r: 255,
  52825. g: 255,
  52826. b: 255,
  52827. a: 1.0
  52828. },
  52829. backgroundColor: {
  52830. r: 0,
  52831. g: 0,
  52832. b: 0,
  52833. a: 0.8
  52834. },
  52835. borderRadius: 6,
  52836. fontsize: 13,
  52837. fontWeight: '',
  52838. //thick
  52839. renderOrder: renderOrders.spot,
  52840. pickOrder: renderOrders.spot
  52841. }); //更新sprite时,实际更新的是root: spot的矩阵
  52842. this.spot.renderOrder = renderOrders.spot;
  52843. /* const mainLabelProp = {
  52844. backgroundColor: {r: defaultColor.r*255, g: defaultColor.g*255, b: defaultColor.b*255, a:config.measure.default.opacity},
  52845. textColor: {r: textColor.r*255, g: textColor.g*255, b: textColor.b*255, a: 1.0},
  52846. fontsize:16,
  52847. useDepth : true ,
  52848. renderOrder : 5, pickOrder:5,
  52849. } */
  52850. this.titleLabel.position.set(0, 0.4, 0);
  52851. this.titleLabel.sprite.material.depthTest = this.titleLabel.sprite.material.depthWrite = true;
  52852. group.position.copy(endPos);
  52853. group.add(this.spot);
  52854. group.add(this.titleLabel);
  52855. this.add(group);
  52856. this.add(this.line);
  52857. viewer.scene.tags.add(this);
  52858. }
  52859. changeTitle(title) {
  52860. this.titleLabel.changeText(title);
  52861. }
  52862. updateMatrixWorld(force) {
  52863. //重写,只为了将root当做parent
  52864. this.updateMatrix();
  52865. this.matrixWorld.multiplyMatrices(this.root.matrixWorld, this.matrix);
  52866. var children = this.children;
  52867. for (var i = 0, l = children.length; i < l; i++) {
  52868. children[i].updateMatrixWorld(force);
  52869. }
  52870. }
  52871. updateWorldMatrix(updateParents, updateChildren) {
  52872. //重写,只为了将root当做parent
  52873. if (updateParents === true && this.root !== null) {
  52874. this.root.updateWorldMatrix(true, false);
  52875. }
  52876. if (this.matrixAutoUpdate) this.updateMatrix();
  52877. this.matrixWorld.multiplyMatrices(this.root.matrixWorld, this.matrix);
  52878. if (updateChildren === true) {
  52879. var children = this.children;
  52880. for (var i = 0, l = children.length; i < l; i++) {
  52881. children[i].updateWorldMatrix(false, true);
  52882. }
  52883. }
  52884. }
  52885. dispose() {
  52886. this.parent.remove(this);
  52887. this.titleLabel.dispose();
  52888. }
  52889. }
  52890. class TagTool extends EventDispatcher {
  52891. constructor(viewer) {
  52892. super();
  52893. this.viewer = viewer;
  52894. this.viewer.addEventListener('start_inserting_tag', e => {
  52895. this.viewer.dispatchEvent({
  52896. type: 'cancel_insertions'
  52897. });
  52898. });
  52899. }
  52900. createTagFromData(data) {
  52901. var tag = new Tag({
  52902. title: data.title,
  52903. position: data.position,
  52904. normal: data.normal,
  52905. root: data.root //e.intersect.pointcloud || e.intersect.object
  52906. });
  52907. return tag;
  52908. }
  52909. startInsertion() {
  52910. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  52911. var callback = arguments.length > 1 ? arguments[1] : undefined;
  52912. var cancelFun = arguments.length > 2 ? arguments[2] : undefined;
  52913. var deferred = $.Deferred();
  52914. this.viewer.dispatchEvent({
  52915. type: 'start_inserting_tag'
  52916. });
  52917. this.adding = true;
  52918. var cancel = () => {
  52919. end();
  52920. };
  52921. var end = () => {
  52922. this.adding = false;
  52923. viewer.dispatchEvent({
  52924. type: "endTagMove"
  52925. });
  52926. this.viewer.removeEventListener('global_click', click);
  52927. };
  52928. var click = e => {
  52929. var worldPos = e.intersect && ( /* e.intersect.orthoIntersect || */e.intersect.location);
  52930. if (!worldPos) {
  52931. return;
  52932. }
  52933. var localPos = Potree.Utils.datasetPosTransform({
  52934. toDataset: true,
  52935. pointcloud: e.intersect.pointcloud,
  52936. object: e.intersect.object,
  52937. position: worldPos
  52938. });
  52939. var tag = new Tag({
  52940. title: '1',
  52941. position: localPos,
  52942. normal: e.intersect.normal,
  52943. root: e.intersect.pointcloud || e.intersect.object
  52944. });
  52945. //pointcloud里加一个normal 的非float32
  52946. end();
  52947. e.consume && e.consume();
  52948. deferred.resolve(tag);
  52949. return {
  52950. stopContinue: true
  52951. };
  52952. };
  52953. this.viewer.addEventListener('global_click', click, {
  52954. importance: 10
  52955. });
  52956. return deferred.promise();
  52957. }
  52958. }
  52959. var initDir = new Vector3(0, 1, 0); //指南针模型的北方向 向屏幕里
  52960. class Compass extends EventDispatcher {
  52961. constructor(dom, viewport) {
  52962. super();
  52963. this.angle = 0;
  52964. this.show = false;
  52965. if (dom) {
  52966. this.dom = $(dom);
  52967. }
  52968. this.viewport = viewport;
  52969. this.init();
  52970. }
  52971. init() {
  52972. var width = 100,
  52973. height = 100;
  52974. if (!this.dom) {
  52975. this.dom = $('<div name="compass"></div>');
  52976. $(viewer.renderArea).append(this.dom);
  52977. }
  52978. this.dom.css({
  52979. display: "none",
  52980. position: "absolute",
  52981. right: "1%",
  52982. top: "60px",
  52983. width: width + "px",
  52984. height: height + "px",
  52985. "z-index": 100,
  52986. "pointer-events": "none"
  52987. });
  52988. var child = $("<div class='dirText north'><span>" + /* (config.lang=='zh'? */'北' /* :'N') */ + "</span></div><div class='center'></div>");
  52989. this.dom.append(child);
  52990. this.dom.find(".dirText").css({
  52991. textAlign: "center",
  52992. "font-size": "10px",
  52993. "position": "absolute",
  52994. width: "100%",
  52995. height: "25px",
  52996. "line-height": "25px"
  52997. });
  52998. this.dom.find(".north").css({
  52999. "color": "#02a0e9",
  53000. "top": "0"
  53001. });
  53002. this.dom.find(".south").css({
  53003. "color": "#ff1414",
  53004. "bottom": "0"
  53005. });
  53006. this.dom.find(".center").css({
  53007. //"background":`url(${config.getStaticResource('img')}/dire.png)`,
  53008. width: width / 2 + "px",
  53009. height: height / 2 + "px",
  53010. "background-size": "contain",
  53011. "background-position": "center",
  53012. left: "50%",
  53013. top: "50%",
  53014. transform: "translate(-50%,-50%)",
  53015. position: "absolute"
  53016. });
  53017. this.dom.find(".dirText").css({
  53018. "text-align": "center",
  53019. "font-size": "10px",
  53020. "color": "rgb(255, 255, 255)",
  53021. "position": "absolute",
  53022. "top": "50%",
  53023. "left": "50%",
  53024. "width": "45%",
  53025. "height": "0px",
  53026. "transform-origin": "left center"
  53027. });
  53028. this.dom.find(".dirText span").css({
  53029. display: "block",
  53030. position: "absolute",
  53031. right: "5px",
  53032. top: "0",
  53033. width: "20px",
  53034. height: "20px",
  53035. "line-height": "20px",
  53036. // "font-size": ".75rem ",
  53037. "margin-top": "-10px"
  53038. });
  53039. try {
  53040. this.renderer = new WebGLRenderer({
  53041. antialias: true,
  53042. alpha: true
  53043. }); //许钟文 添加个抗锯齿,否则添加的线条锯齿严重,
  53044. this.renderer.autoClear = !0;
  53045. this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  53046. this.renderer.domElement.setAttribute('name', 'compass');
  53047. this.renderer.setClearAlpha(0.0);
  53048. //xst修改
  53049. //this.renderer.setSize(width/2, height/2, false, window.devicePixelRatio ? window.devicePixelRatio : 1);
  53050. //xst修改
  53051. //this.renderer.setPixelRatio(window.devicePixelRatio ? window.devicePixelRatio : 1);
  53052. //this.renderer.setSize(width/2, height/2);
  53053. //xst修改
  53054. this.renderer.setDrawingBufferSize(width / 2, height / 2, window.devicePixelRatio ? window.devicePixelRatio : 1);
  53055. //this.emit(SceneRendererEvents.ContextCreated)
  53056. } catch (e) {
  53057. viewer.dispatchEvent('webglError', {
  53058. msg: e
  53059. });
  53060. }
  53061. this.dom.find(".center")[0].appendChild(this.renderer.domElement);
  53062. this.renderer.domElement.style.width = this.renderer.domElement.style.height = '100%';
  53063. this.camera = new PerspectiveCamera();
  53064. this.camera.fov = 50;
  53065. this.camera.updateProjectionMatrix();
  53066. this.scene = new Scene(), this.scene.add(this.camera);
  53067. this.createCompass();
  53068. viewer.addEventListener('camera_changed', e => {
  53069. if (e.viewport == this.viewport && e.changeInfo.quaternionChanged /* || e.changeInfo.quaternionChanged */) {
  53070. this.update();
  53071. }
  53072. });
  53073. this.setDomPos();
  53074. if (this.viewport) this.setDisplay(true);
  53075. }
  53076. createCompass() {
  53077. //ConeBufferGeometry(radius : Float, height : Float, radialSegments : Integer, heightSegments : Integer, openEnded : Boolean, thetaStart : Float, thetaLength : Float)
  53078. var height = 2;
  53079. var geometry1 = new ConeBufferGeometry(0.7, height, 4, true);
  53080. var geometry2 = new ConeBufferGeometry(0.7, height, 4, true);
  53081. var material = new MeshBasicMaterial({
  53082. vertexColors: true
  53083. });
  53084. //指南针由两个四棱锥拼成,为了渐变颜色,采用指定vertexColor的方式。
  53085. var setColor = function setColor(geometry, color1, color2) {
  53086. var colors = [];
  53087. for (var i = 0, n = geometry.attributes.position.count; i < n; ++i) {
  53088. colors.push(1, 1, 1);
  53089. }
  53090. var set = function set(index, color) {
  53091. //设置第index个点的颜色
  53092. colors[index * 3 + 0] = color[0];
  53093. colors[index * 3 + 1] = color[1];
  53094. colors[index * 3 + 2] = color[2];
  53095. };
  53096. var mid = [(color1[0] + color2[0]) / 2, (color1[1] + color2[1]) / 2, (color1[2] + color2[2]) / 2];
  53097. set(1, color1);
  53098. set(5, color1);
  53099. set(6, color1);
  53100. set(2, mid);
  53101. set(3, mid);
  53102. set(7, mid);
  53103. set(4, color2);
  53104. set(8, color2);
  53105. set(9, color2);
  53106. geometry.setAttribute("color", new BufferAttribute(new Float32Array(colors), 3));
  53107. };
  53108. var blue1 = [1 / 255, 238 / 255, 245 / 255]; //逐渐变深
  53109. var blue2 = [20 / 255, 146 / 255, 170 / 255];
  53110. var blue3 = [40 / 255, 60 / 255, 103 / 255];
  53111. setColor(geometry1, blue1, blue2);
  53112. setColor(geometry2, blue2, blue3);
  53113. /* 朝箭头方向看点构成如下 虽然geometry.attributes.position.count = 19 只有1-9设置的颜色是有效的 另外为什么7决定了上下两边的颜色呢…… 5、9可将其分成上下两个颜色
  53114. 6
  53115. /|\
  53116. / | \
  53117. 7 /_2|1_\ 5
  53118. \ 3|4 / 9
  53119. \ | /
  53120. \|/
  53121. 8
  53122. */
  53123. var cone = new Mesh(geometry1, material);
  53124. cone.position.setY(height / 2);
  53125. geometry1.computeVertexNormals(); //computeFaceNormals
  53126. geometry2.computeVertexNormals();
  53127. var cones = new Object3D();
  53128. cones.add(cone);
  53129. var cone2 = new Mesh(geometry2, material);
  53130. cone2.rotation.x = Math.PI;
  53131. cone2.position.setY(-height / 2);
  53132. cones.add(cone2);
  53133. //cones.rotation.x = Math.PI / 2;//转向initDir的方向
  53134. //cones.rotation.z = Math.PI / 2;
  53135. cones.rotation.z = Math.PI; //转向initDir的方向
  53136. cones.scale.set(0.7, 0.7, 0.7);
  53137. this.scene.add(cones);
  53138. this.cones = cones;
  53139. }
  53140. setNorth() {
  53141. //设置北方向,这决定了指南针自身的朝向。
  53142. var floors = store.getters['scene/houstFloor'].floors;
  53143. if (!floors || !floors.length) {
  53144. return;
  53145. }
  53146. var floor = floors[0];
  53147. var metadata = app.store.getters['scene/metadata'] || {};
  53148. this.angle = (floor && floor.dire || 0) + MathUtils.radToDeg(parseFloat(metadata.floorPlanAngle || 0)); //基础朝向
  53149. this.cones.rotation.y = Math.PI / 2 - MathUtils.degToRad(this.angle);
  53150. //console.log("dir:"+floor.dire+", floorPlanAngle:"+metadata.floorPlanAngle)
  53151. this.update();
  53152. }
  53153. update(quaternion) {
  53154. if (!this.show) return;
  53155. if (!quaternion) quaternion = this.viewport.camera.quaternion.clone();
  53156. this.updateCamera(quaternion);
  53157. this.updateLabel(quaternion);
  53158. this.render();
  53159. }
  53160. /*updateLabel(quaternion){//更新北标签
  53161. var dir = viewer.mainViewport.view.direction;
  53162. var oriDir = initDir.clone() //指南针最初始时的北方向
  53163. var extraQua
  53164. if(objects.player.mode == "transitioning"){//当transitioning时,相机的quaternion不是用control的lookAt算出来,而是直接由一个quaternion过渡到另一个,这样相机将会是歪的,投影面也就不会是原先的水平面。
  53165. var tempCamera = new THREE.Camera(); //借用camera的lookAt算出如果正视同样的target, quaternion会是什么值。 将它乘以当前相机quaternion,得到的就是相机歪的旋转值。
  53166. tempCamera.position.copy(this.camera.position);
  53167. tempCamera.lookAt(tempCamera.position.clone().add(dir))
  53168. var q = tempCamera.quaternion.inverse()
  53169. extraQua = q.premultiply(quaternion) //歪掉的额外旋转值
  53170. }
  53171. //北标签的方向为指南针轮盘方向,也就是要将camera的方向投影到水平面上。 但是如果相机歪了,看到的世界都会歪一定角度,投影面也要歪一定角度。
  53172. var up = new THREE.Vector3(0,0,1) //投影水平面的法线,也是相机的摆正的up方向
  53173. extraQua && up.applyQuaternion(extraQua)
  53174. dir.projectOnPlane(up) //将方向投影到水平面上; 如果相机不是正视(extraQua不为0001),就要将水平面也转动
  53175. oriDir.projectOnPlane(up)//为什么initDir投影了和没有投影angle结果一样
  53176. var angle = dir.angleTo(oriDir)
  53177. if(dir.cross(oriDir).y > 0)angle = -angle
  53178. var deg = this.angle - 90 + THREE.Math.radToDeg(angle) //因为css写的样式初始是指向右方,和initDir差了90°,所以减去。
  53179. this.dom.find(".dirText").css( "transform","rotate("+deg+"deg)" )
  53180. this.dom.find(".dirText span").css("transform","rotate("+(-deg)+"deg)")
  53181. } */
  53182. updateLabel(quaternion) {
  53183. //更新北标签
  53184. var deg = MathUtils.radToDeg(this.viewport.view.yaw) - 90;
  53185. this.dom.find(".dirText").css("transform", "rotate(" + deg + "deg)");
  53186. this.dom.find(".dirText span").css("transform", "rotate(" + -deg + "deg)");
  53187. }
  53188. updateCamera(quaternion) {
  53189. //更新canvas中的指南针表现,也就是更新相机,和场景中的相机朝向一致。
  53190. var radius = 5; //相机距离
  53191. this.camera.quaternion.copy(quaternion);
  53192. var dir = this.viewport.view.direction; //相机朝向
  53193. this.camera.position.copy(dir.multiplyScalar(radius).negate()); //相机绕着指南针中心(000)转动
  53194. }
  53195. changeViewport(viewport) {
  53196. this.viewport = viewport;
  53197. this.update(); //因相机更新了
  53198. }
  53199. render() {
  53200. this.renderer.render(this.scene, this.camera);
  53201. }
  53202. setDisplay(state) {
  53203. this.show = !!state;
  53204. if (this.show) {
  53205. this.update();
  53206. this.dom.fadeIn(100);
  53207. } else {
  53208. this.dom.fadeOut(100);
  53209. }
  53210. }
  53211. setAutoDisplay(state) {
  53212. //被直接改变了dom的显示
  53213. this.autoJudgeShow = state;
  53214. if (state) {
  53215. this._autoDisplayEvent = () => {
  53216. var oldShow = this.show;
  53217. this.show = !!this.renderer.domElement.clientHeight;
  53218. if (oldShow != this.show) {
  53219. this.update();
  53220. }
  53221. };
  53222. viewer.addEventListener('update_start', this._autoDisplayEvent);
  53223. } else {
  53224. viewer.removeEventListener('update_start', this._autoDisplayEvent);
  53225. }
  53226. }
  53227. setDomPos() {
  53228. if (!this.viewport) return;
  53229. var right = this.viewport.left + this.viewport.width;
  53230. this.dom.css({
  53231. 'right': (1 - right) * 100 + 1 + '%'
  53232. });
  53233. }
  53234. }
  53235. class AxisViewer extends ViewerBase {
  53236. constructor(listenViewport, parentArea) {
  53237. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  53238. var domElement = $("<div name=\"Axisdom\" viewport=".concat(listenViewport.name, "></div>"));
  53239. $(parentArea).append(domElement);
  53240. var posInfo = Object.assign({
  53241. //default:
  53242. right: 0,
  53243. top: 0,
  53244. width: '100px',
  53245. height: '100px'
  53246. }, options.domStyle, {
  53247. position: 'absolute'
  53248. });
  53249. if (options.domStyle) {
  53250. if (options.domStyle.bottom != void 0) {
  53251. delete posInfo.top;
  53252. }
  53253. if (options.domStyle.left != void 0) {
  53254. delete posInfo.right;
  53255. }
  53256. }
  53257. domElement.css(posInfo);
  53258. super(domElement[0], {
  53259. name: 'axis',
  53260. antialias: true
  53261. });
  53262. this.listenViewport = listenViewport;
  53263. Object.defineProperty(listenViewport, 'axis', {
  53264. value: this,
  53265. writable: true,
  53266. // 可写(可选)
  53267. enumerable: false,
  53268. // 不可枚举
  53269. configurable: true // 可配置(可选)
  53270. });
  53271. this.scene = new Scene();
  53272. //this.camera = new THREE.PerspectiveCamera(30, 1, 1, this.radius*3);
  53273. var w = 50;
  53274. this.camera = new OrthographicCamera(-w / 2, w / 2, w / 2, -w / 2, 1, w * 4);
  53275. this.camera.zoom = 2.7; //(domElement.clientWidth || 300) / w * 1.267//zoom越大视野越小
  53276. this.camera.updateProjectionMatrix();
  53277. this.view = new ExtendView();
  53278. this.view.radius = 70;
  53279. this.viewports = [new Viewport(this.view, this.camera, {
  53280. left: 0,
  53281. bottom: 0,
  53282. width: 1,
  53283. height: 1,
  53284. name: 'axis'
  53285. })];
  53286. this.updateScreenSize();
  53287. this.createAxis();
  53288. var updateCamera = e => {
  53289. if (e.viewport == listenViewport && e.changeInfo.quaternionChanged) {
  53290. this.update();
  53291. }
  53292. };
  53293. viewer.addEventListener('camera_changed', updateCamera);
  53294. var repos = () => {
  53295. if (!listenViewport.active || listenViewport.width == 0 || listenViewport.height == 0) {
  53296. return domElement.css('visibility', 'hidden');
  53297. }
  53298. domElement.css('visibility', 'visible');
  53299. var props = [['left', 'right', 'width'], ['bottom', 'top', 'height']];
  53300. var set = prop => {
  53301. var str;
  53302. var name = posInfo[prop[1]] != void 0 ? prop[1] : prop[0];
  53303. var percent = posInfo[prop[1]] != void 0 ? 1 - listenViewport[prop[0]] - listenViewport[prop[2]] : listenViewport[prop[0]];
  53304. if (posInfo[name] == 0 || posInfo[name].includes('%')) {
  53305. str = parseFloat(posInfo[name]) + percent * 100 + '%';
  53306. } else {
  53307. //px
  53308. str = 'calc(' + percent * 100 + '% + ' + posInfo[name] + ')';
  53309. }
  53310. domElement.css(name, str);
  53311. };
  53312. set(props[0]);
  53313. set(props[1]);
  53314. };
  53315. this.listenViewport.addEventListener('resize', repos);
  53316. this.addEventListener('dispose', () => {
  53317. viewer.removeEventListener('camera_changed', updateCamera);
  53318. viewer.removeEventListener('resize', repos);
  53319. });
  53320. repos();
  53321. this.update();
  53322. }
  53323. createAxis() {
  53324. var axis = new Object3D();
  53325. ['x', 'y', 'z'].forEach(axisText => {
  53326. var color = new Color().set(Potree.config.axis[axisText].color);
  53327. var group = new Object3D();
  53328. var line = LineDraw.createLine([new Vector3(), new Vector3(0, 0, 7)], {
  53329. color
  53330. });
  53331. var label = this.createLabel(axisText, color);
  53332. label.position.set(0, 0, 11 /* + this.renderArea.clientWidth/200 */);
  53333. if (axisText == 'y') {
  53334. group.rotation.x = -Math.PI / 2;
  53335. } else if (axisText == 'x') {
  53336. group.rotation.y = Math.PI / 2;
  53337. }
  53338. group.add(line);
  53339. group.add(label);
  53340. axis.add(group);
  53341. });
  53342. this.axis = axis;
  53343. this.scene.add(this.axis);
  53344. }
  53345. createLabel(text, color) {
  53346. var fontsize = this.renderArea.clientWidth / 5; //20//Math.round( Potree.math.linearClamp(this.renderArea.clientWidth, [80,500],[12,50]))
  53347. var s = 3100 / this.renderArea.clientWidth;
  53348. console.log('fontsize', fontsize);
  53349. var label = new TextSprite$2({
  53350. backgroundColor: {
  53351. r: 0,
  53352. g: 0,
  53353. b: 0,
  53354. a: 0
  53355. },
  53356. textColor: {
  53357. r: color.r * 255,
  53358. g: color.g * 255,
  53359. b: color.b * 255,
  53360. a: 1
  53361. },
  53362. fontsize,
  53363. //useDepth : true ,
  53364. renderOrder: 5,
  53365. // pickOrder:5,
  53366. fontWeight: 'Lighter',
  53367. text,
  53368. name: 'axis',
  53369. viewports: this.viewports
  53370. });
  53371. label.scale.set(s, s, s);
  53372. return label;
  53373. }
  53374. update() {
  53375. this.updateCamera();
  53376. this.render();
  53377. }
  53378. updateCamera() {
  53379. var view = this.listenViewport.view;
  53380. this.view.yaw = view.yaw;
  53381. this.view.pitch = view.pitch;
  53382. var dir = view.direction; //相机朝向
  53383. this.view.position.copy(dir.multiplyScalar(this.view.radius).negate()); //相机绕着指南针中心(000)转动
  53384. this.view.applyToCamera(this.camera);
  53385. }
  53386. render() {
  53387. viewer.dispatchEvent({
  53388. type: "render.begin",
  53389. viewport: this.viewports[0]
  53390. }); //update sprite
  53391. this.renderer.render(this.scene, this.camera);
  53392. }
  53393. dispose() {
  53394. this.axis.traverse(child => {
  53395. if (child instanceof TextSprite$2) {
  53396. child.dispose();
  53397. } else if (child instanceof LineSegments) {
  53398. child.material.dispose();
  53399. child.geometry.dispose();
  53400. }
  53401. });
  53402. super.dispose();
  53403. delete this.listenViewport.axis;
  53404. }
  53405. }
  53406. // Copied from three.js: WebGLRenderer.js
  53407. function paramThreeToGL$1(_gl, p) {
  53408. var extension;
  53409. if (p === RepeatWrapping) return _gl.REPEAT;
  53410. if (p === ClampToEdgeWrapping) return _gl.CLAMP_TO_EDGE;
  53411. if (p === MirroredRepeatWrapping) return _gl.MIRRORED_REPEAT;
  53412. if (p === NearestFilter) return _gl.NEAREST;
  53413. if (p === NearestMipMapNearestFilter) return _gl.NEAREST_MIPMAP_NEAREST;
  53414. if (p === NearestMipMapLinearFilter) return _gl.NEAREST_MIPMAP_LINEAR;
  53415. if (p === LinearFilter) return _gl.LINEAR;
  53416. if (p === LinearMipMapNearestFilter) return _gl.LINEAR_MIPMAP_NEAREST;
  53417. if (p === LinearMipMapLinearFilter) return _gl.LINEAR_MIPMAP_LINEAR;
  53418. if (p === UnsignedByteType) return _gl.UNSIGNED_BYTE;
  53419. if (p === UnsignedShort4444Type) return _gl.UNSIGNED_SHORT_4_4_4_4;
  53420. if (p === UnsignedShort5551Type) return _gl.UNSIGNED_SHORT_5_5_5_1;
  53421. if (p === UnsignedShort565Type) return _gl.UNSIGNED_SHORT_5_6_5;
  53422. if (p === ByteType) return _gl.BYTE;
  53423. if (p === ShortType) return _gl.SHORT;
  53424. if (p === UnsignedShortType) return _gl.UNSIGNED_SHORT;
  53425. if (p === IntType) return _gl.INT;
  53426. if (p === UnsignedIntType) return _gl.UNSIGNED_INT;
  53427. if (p === FloatType) return _gl.FLOAT;
  53428. if (p === HalfFloatType) {
  53429. extension = extensions.get('OES_texture_half_float');
  53430. if (extension !== null) return extension.HALF_FLOAT_OES;
  53431. }
  53432. if (p === AlphaFormat) return _gl.ALPHA;
  53433. if (p === RGBFormat) return _gl.RGB;
  53434. if (p === RGBAFormat) return _gl.RGBA;
  53435. if (p === LuminanceFormat) return _gl.LUMINANCE;
  53436. if (p === LuminanceAlphaFormat) return _gl.LUMINANCE_ALPHA;
  53437. if (p === DepthFormat) return _gl.DEPTH_COMPONENT;
  53438. if (p === DepthStencilFormat) return _gl.DEPTH_STENCIL;
  53439. if (p === AddEquation) return _gl.FUNC_ADD;
  53440. if (p === SubtractEquation) return _gl.FUNC_SUBTRACT;
  53441. if (p === ReverseSubtractEquation) return _gl.FUNC_REVERSE_SUBTRACT;
  53442. if (p === ZeroFactor) return _gl.ZERO;
  53443. if (p === OneFactor) return _gl.ONE;
  53444. if (p === SrcColorFactor) return _gl.SRC_COLOR;
  53445. if (p === OneMinusSrcColorFactor) return _gl.ONE_MINUS_SRC_COLOR;
  53446. if (p === SrcAlphaFactor) return _gl.SRC_ALPHA;
  53447. if (p === OneMinusSrcAlphaFactor) return _gl.ONE_MINUS_SRC_ALPHA;
  53448. if (p === DstAlphaFactor) return _gl.DST_ALPHA;
  53449. if (p === OneMinusDstAlphaFactor) return _gl.ONE_MINUS_DST_ALPHA;
  53450. if (p === DstColorFactor) return _gl.DST_COLOR;
  53451. if (p === OneMinusDstColorFactor) return _gl.ONE_MINUS_DST_COLOR;
  53452. if (p === SrcAlphaSaturateFactor) return _gl.SRC_ALPHA_SATURATE;
  53453. if (p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format) {
  53454. extension = extensions.get('WEBGL_compressed_texture_s3tc');
  53455. if (extension !== null) {
  53456. if (p === RGB_S3TC_DXT1_Format) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  53457. if (p === RGBA_S3TC_DXT1_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  53458. if (p === RGBA_S3TC_DXT3_Format) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  53459. if (p === RGBA_S3TC_DXT5_Format$1) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  53460. }
  53461. }
  53462. if (p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format) {
  53463. extension = extensions.get('WEBGL_compressed_texture_pvrtc');
  53464. if (extension !== null) {
  53465. if (p === RGB_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  53466. if (p === RGB_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  53467. if (p === RGBA_PVRTC_4BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  53468. if (p === RGBA_PVRTC_2BPPV1_Format) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  53469. }
  53470. }
  53471. if (p === RGB_ETC1_Format) {
  53472. extension = extensions.get('WEBGL_compressed_texture_etc1');
  53473. if (extension !== null) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  53474. }
  53475. if (p === MinEquation || p === MaxEquation) {
  53476. extension = extensions.get('EXT_blend_minmax');
  53477. if (extension !== null) {
  53478. if (p === MinEquation) return extension.MIN_EXT;
  53479. if (p === MaxEquation) return extension.MAX_EXT;
  53480. }
  53481. }
  53482. if (p === UnsignedInt248Type) {
  53483. extension = extensions.get('WEBGL_depth_texture');
  53484. if (extension !== null) return extension.UNSIGNED_INT_24_8_WEBGL;
  53485. }
  53486. return 0;
  53487. }
  53488. ;
  53489. var attributeLocations$1 = {
  53490. "position": {
  53491. name: "position",
  53492. location: 0
  53493. },
  53494. "color": {
  53495. name: "color",
  53496. location: 1
  53497. },
  53498. "rgba": {
  53499. name: "color",
  53500. location: 1
  53501. },
  53502. "intensity": {
  53503. name: "intensity",
  53504. location: 2
  53505. },
  53506. "classification": {
  53507. name: "classification",
  53508. location: 3
  53509. },
  53510. "returnNumber": {
  53511. name: "returnNumber",
  53512. location: 4
  53513. },
  53514. "return number": {
  53515. name: "returnNumber",
  53516. location: 4
  53517. },
  53518. "returns": {
  53519. name: "returnNumber",
  53520. location: 4
  53521. },
  53522. "numberOfReturns": {
  53523. name: "numberOfReturns",
  53524. location: 5
  53525. },
  53526. "number of returns": {
  53527. name: "numberOfReturns",
  53528. location: 5
  53529. },
  53530. "pointSourceID": {
  53531. name: "pointSourceID",
  53532. location: 6
  53533. },
  53534. "source id": {
  53535. name: "pointSourceID",
  53536. location: 6
  53537. },
  53538. "point source id": {
  53539. name: "pointSourceID",
  53540. location: 6
  53541. },
  53542. "indices": {
  53543. name: "indices",
  53544. location: 7
  53545. },
  53546. "normal": {
  53547. name: "normal",
  53548. location: 8
  53549. },
  53550. "spacing": {
  53551. name: "spacing",
  53552. location: 9
  53553. },
  53554. "gps-time": {
  53555. name: "gpsTime",
  53556. location: 10
  53557. },
  53558. "aExtra": {
  53559. name: "aExtra",
  53560. location: 11
  53561. }
  53562. };
  53563. class Shader$1 {
  53564. constructor(gl, name, vsSource, fsSource) {
  53565. this.gl = gl;
  53566. this.name = name;
  53567. this.vsSource = vsSource;
  53568. this.fsSource = fsSource;
  53569. this.cache = new Map();
  53570. this.vs = null;
  53571. this.fs = null;
  53572. this.program = null;
  53573. this.uniformLocations = {};
  53574. this.attributeLocations = {};
  53575. this.uniformBlockIndices = {};
  53576. this.uniformBlocks = {};
  53577. this.uniforms = {};
  53578. this.update(vsSource, fsSource);
  53579. }
  53580. update(vsSource, fsSource) {
  53581. this.vsSource = vsSource;
  53582. this.fsSource = fsSource;
  53583. this.linkProgram();
  53584. }
  53585. compileShader(shader, source) {
  53586. var gl = this.gl;
  53587. gl.shaderSource(shader, source);
  53588. gl.compileShader(shader);
  53589. var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
  53590. if (!success) {
  53591. var info = gl.getShaderInfoLog(shader);
  53592. var numberedSource = source.split("\n").map((a, i) => "".concat(i + 1).padEnd(5) + a).join("\n");
  53593. throw "could not compile shader ".concat(this.name, ": ").concat(info, ", \n").concat(numberedSource);
  53594. }
  53595. }
  53596. linkProgram() {
  53597. var tStart = performance.now();
  53598. var gl = this.gl;
  53599. this.uniformLocations = {};
  53600. this.attributeLocations = {};
  53601. this.uniforms = {};
  53602. gl.useProgram(null);
  53603. var cached = this.cache.get("".concat(this.vsSource, ", ").concat(this.fsSource));
  53604. if (cached) {
  53605. this.program = cached.program;
  53606. this.vs = cached.vs;
  53607. this.fs = cached.fs;
  53608. this.attributeLocations = cached.attributeLocations;
  53609. this.uniformLocations = cached.uniformLocations;
  53610. this.uniformBlocks = cached.uniformBlocks;
  53611. this.uniforms = cached.uniforms;
  53612. return;
  53613. } else {
  53614. this.vs = gl.createShader(gl.VERTEX_SHADER);
  53615. this.fs = gl.createShader(gl.FRAGMENT_SHADER);
  53616. this.program = gl.createProgram();
  53617. if (!gl.isProgram(this.program)) {
  53618. //创建失败 开启多个页面可能会,原因是webglcontextlost
  53619. //console.error('创建program失败');
  53620. viewer.dispatchEvent('webglError', {
  53621. msg: 'potreeRenderer创建program失败'
  53622. });
  53623. console.log(this.vs);
  53624. console.log(this.fs);
  53625. return;
  53626. }
  53627. for (var name of Object.keys(attributeLocations$1)) {
  53628. var location = attributeLocations$1[name].location;
  53629. var glslName = attributeLocations$1[name].name;
  53630. gl.bindAttribLocation(this.program, location, glslName);
  53631. }
  53632. this.compileShader(this.vs, this.vsSource);
  53633. this.compileShader(this.fs, this.fsSource);
  53634. var program = this.program;
  53635. gl.attachShader(program, this.vs);
  53636. gl.attachShader(program, this.fs);
  53637. gl.linkProgram(program);
  53638. gl.detachShader(program, this.vs);
  53639. gl.detachShader(program, this.fs);
  53640. // 检测当前程序链接状态
  53641. var success = gl.getProgramParameter(program, gl.LINK_STATUS);
  53642. if (!success) {
  53643. var info = gl.getProgramInfoLog(program);
  53644. throw "could not link program ".concat(this.name, ": ").concat(info);
  53645. }
  53646. {
  53647. // attribute locations
  53648. var numAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  53649. for (var i = 0; i < numAttributes; i++) {
  53650. var attribute = gl.getActiveAttrib(program, i);
  53651. var _location = gl.getAttribLocation(program, attribute.name);
  53652. this.attributeLocations[attribute.name] = _location;
  53653. }
  53654. }
  53655. {
  53656. // uniform locations
  53657. var numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  53658. for (var _i = 0; _i < numUniforms; _i++) {
  53659. var uniform = gl.getActiveUniform(program, _i);
  53660. var _location2 = gl.getUniformLocation(program, uniform.name);
  53661. this.uniformLocations[uniform.name] = _location2;
  53662. this.uniforms[uniform.name] = {
  53663. location: _location2,
  53664. value: null
  53665. };
  53666. }
  53667. }
  53668. // uniform blocks
  53669. if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {
  53670. //WebGL2RenderingContext在mac的safari14以下是没有定义的
  53671. var numBlocks = gl.getProgramParameter(program, gl.ACTIVE_UNIFORM_BLOCKS);
  53672. for (var _i2 = 0; _i2 < numBlocks; _i2++) {
  53673. var blockName = gl.getActiveUniformBlockName(program, _i2);
  53674. var blockIndex = gl.getUniformBlockIndex(program, blockName);
  53675. this.uniformBlockIndices[blockName] = blockIndex;
  53676. gl.uniformBlockBinding(program, blockIndex, blockIndex);
  53677. var dataSize = gl.getActiveUniformBlockParameter(program, blockIndex, gl.UNIFORM_BLOCK_DATA_SIZE);
  53678. var uBuffer = gl.createBuffer();
  53679. gl.bindBuffer(gl.UNIFORM_BUFFER, uBuffer);
  53680. gl.bufferData(gl.UNIFORM_BUFFER, dataSize, gl.DYNAMIC_READ);
  53681. gl.bindBufferBase(gl.UNIFORM_BUFFER, blockIndex, uBuffer);
  53682. gl.bindBuffer(gl.UNIFORM_BUFFER, null);
  53683. this.uniformBlocks[blockName] = {
  53684. name: blockName,
  53685. index: blockIndex,
  53686. dataSize: dataSize,
  53687. buffer: uBuffer
  53688. };
  53689. }
  53690. }
  53691. var _cached = {
  53692. program: this.program,
  53693. vs: this.vs,
  53694. fs: this.fs,
  53695. attributeLocations: this.attributeLocations,
  53696. uniformLocations: this.uniformLocations,
  53697. uniforms: this.uniforms,
  53698. uniformBlocks: this.uniformBlocks
  53699. };
  53700. this.cache.set("".concat(this.vsSource, ", ").concat(this.fsSource), _cached);
  53701. }
  53702. var tEnd = performance.now();
  53703. var duration = tEnd - tStart;
  53704. //console.log(`shader compile duration: ${duration.toFixed(3)}`);
  53705. }
  53706. setUniformMatrix4(name, value) {
  53707. var gl = this.gl;
  53708. var location = this.uniformLocations[name];
  53709. if (location == null) {
  53710. return;
  53711. }
  53712. var tmp = new Float32Array(value.elements);
  53713. gl.uniformMatrix4fv(location, false, tmp);
  53714. }
  53715. setUniform1f(name, value) {
  53716. var gl = this.gl;
  53717. var uniform = this.uniforms[name];
  53718. if (uniform === undefined) {
  53719. return;
  53720. }
  53721. if (uniform.value === value) {
  53722. return;
  53723. }
  53724. uniform.value = value;
  53725. gl.uniform1f(uniform.location, value);
  53726. }
  53727. setUniformBoolean(name, value) {
  53728. var gl = this.gl;
  53729. var uniform = this.uniforms[name];
  53730. if (uniform === undefined) {
  53731. return;
  53732. }
  53733. if (uniform.value === value) {
  53734. return;
  53735. }
  53736. uniform.value = value;
  53737. gl.uniform1i(uniform.location, value);
  53738. }
  53739. setUniformTexture(name, value) {
  53740. var gl = this.gl;
  53741. var location = this.uniformLocations[name];
  53742. if (location == null) {
  53743. return;
  53744. }
  53745. gl.uniform1i(location, value);
  53746. }
  53747. setUniform2f(name, value) {
  53748. var gl = this.gl;
  53749. var location = this.uniformLocations[name];
  53750. if (location == null) {
  53751. return;
  53752. }
  53753. gl.uniform2f(location, value[0], value[1]);
  53754. }
  53755. setUniform3f(name, value) {
  53756. var gl = this.gl;
  53757. var location = this.uniformLocations[name];
  53758. if (location == null) {
  53759. return;
  53760. }
  53761. gl.uniform3f(location, value[0], value[1], value[2]);
  53762. }
  53763. setUniform(name, value) {
  53764. if (value.constructor === Matrix4) {
  53765. this.setUniformMatrix4(name, value);
  53766. } else if (typeof value === "number") {
  53767. this.setUniform1f(name, value);
  53768. } else if (typeof value === "boolean") {
  53769. this.setUniformBoolean(name, value);
  53770. } else if (value instanceof WebGLTexture$1) {
  53771. this.setUniformTexture(name, value);
  53772. } else if (value instanceof Array) {
  53773. if (value.length === 2) {
  53774. this.setUniform2f(name, value);
  53775. } else if (value.length === 3) {
  53776. this.setUniform3f(name, value);
  53777. }
  53778. } else {
  53779. console.error("unhandled uniform type: ", name, value);
  53780. }
  53781. }
  53782. setUniform1i(name, value) {
  53783. var gl = this.gl;
  53784. var location = this.uniformLocations[name];
  53785. if (location == null) {
  53786. return;
  53787. }
  53788. gl.uniform1i(location, value);
  53789. }
  53790. }
  53791. ;
  53792. class WebGLTexture$1 {
  53793. constructor(gl, texture, threeRenderer) {
  53794. this.gl = gl;
  53795. this.texture = texture;
  53796. if (texture.image && !(texture.image instanceof Image) && !texture.isCanvasTexture && !texture.isDataTexture) {
  53797. //renderTarget的texture在创建renderTarget时已经初始化过 见setupRenderTarget
  53798. this.id = threeRenderer.properties.get(texture).__webglTexture || gl.createTexture();
  53799. this.isFromRenderTarget = true;
  53800. } else {
  53801. this.id = gl.createTexture();
  53802. }
  53803. this.target = gl.TEXTURE_2D;
  53804. this.version = -1;
  53805. this.update(texture);
  53806. }
  53807. update() {
  53808. if (!this.texture.image) {
  53809. this.version = this.texture.version;
  53810. return;
  53811. }
  53812. //if(this.isFromRenderTarget)return //没找到怎么update。 在three.js里的uploadTexture没找到。 这里会报错,可能是 state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null ),类似depthTex的写法
  53813. var gl = this.gl;
  53814. var texture = this.texture;
  53815. if (this.version === texture.version) {
  53816. return;
  53817. }
  53818. this.target = gl.TEXTURE_2D;
  53819. gl.bindTexture(this.target, this.id);
  53820. var level = 0;
  53821. var internalFormat = paramThreeToGL$1(gl, texture.format);
  53822. var width = texture.image.width;
  53823. var height = texture.image.height;
  53824. var border = 0;
  53825. var srcFormat = internalFormat;
  53826. var srcType = paramThreeToGL$1(gl, texture.type);
  53827. var data;
  53828. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, texture.flipY);
  53829. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha);
  53830. gl.pixelStorei(gl.UNPACK_ALIGNMENT, texture.unpackAlignment);
  53831. if (texture instanceof DataTexture) {
  53832. data = texture.image.data;
  53833. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  53834. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  53835. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter));
  53836. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter));
  53837. gl.texImage2D(this.target, level, internalFormat, width, height, border, srcFormat, srcType, data);
  53838. } else if (texture instanceof CanvasTexture || texture instanceof Texture) {
  53839. data = texture.image;
  53840. gl.texParameteri(this.target, gl.TEXTURE_WRAP_S, paramThreeToGL$1(gl, texture.wrapS));
  53841. gl.texParameteri(this.target, gl.TEXTURE_WRAP_T, paramThreeToGL$1(gl, texture.wrapT));
  53842. gl.texParameteri(this.target, gl.TEXTURE_MAG_FILTER, paramThreeToGL$1(gl, texture.magFilter));
  53843. gl.texParameteri(this.target, gl.TEXTURE_MIN_FILTER, paramThreeToGL$1(gl, texture.minFilter));
  53844. if (this.isFromRenderTarget) {
  53845. //咋写?
  53846. //gl.texImage2D( 3553, 0, internalFormat, width, height, 0, srcFormat, srcType, null )
  53847. //console.log('isFromRenderTarget')
  53848. } else {
  53849. gl.texImage2D(this.target, level, internalFormat, internalFormat, srcType, data); //这个参数怎么跟我查的不一样呢
  53850. }
  53851. if (texture instanceof Texture) {
  53852. gl.generateMipmap(gl.TEXTURE_2D);
  53853. }
  53854. }
  53855. gl.bindTexture(this.target, null);
  53856. this.version = texture.version;
  53857. }
  53858. }
  53859. ;
  53860. class WebGLBuffer$1 {
  53861. constructor() {
  53862. this.numElements = 0;
  53863. this.vao = null;
  53864. this.vbos = new Map();
  53865. }
  53866. }
  53867. ;
  53868. class Renderer$1 {
  53869. constructor(threeRenderer) {
  53870. this.threeRenderer = threeRenderer;
  53871. this.gl = this.threeRenderer.getContext();
  53872. this.buffers = new Map();
  53873. this.shaders = new Map();
  53874. this.textures = new Map();
  53875. this.glTypeMapping = new Map();
  53876. this.glTypeMapping.set(Float32Array, this.gl.FLOAT);
  53877. this.glTypeMapping.set(Uint8Array, this.gl.UNSIGNED_BYTE);
  53878. this.glTypeMapping.set(Uint16Array, this.gl.UNSIGNED_SHORT);
  53879. this.toggle = 0;
  53880. }
  53881. deleteBuffer(geometry) {
  53882. var gl = this.gl;
  53883. var webglBuffer = this.buffers.get(geometry);
  53884. if (webglBuffer != null) {
  53885. for (var attributeName in geometry.attributes) {
  53886. gl.deleteBuffer(webglBuffer.vbos.get(attributeName).handle);
  53887. }
  53888. this.buffers.delete(geometry);
  53889. }
  53890. }
  53891. createBuffer(geometry) {
  53892. var gl = this.gl;
  53893. var webglBuffer = new WebGLBuffer$1();
  53894. webglBuffer.vao = gl.createVertexArray();
  53895. webglBuffer.numElements = geometry.attributes.position.count;
  53896. gl.bindVertexArray(webglBuffer.vao);
  53897. for (var attributeName in geometry.attributes) {
  53898. var bufferAttribute = geometry.attributes[attributeName];
  53899. var vbo = gl.createBuffer();
  53900. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  53901. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  53902. var normalized = bufferAttribute.normalized;
  53903. var type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  53904. if (attributeLocations$1[attributeName] === undefined) {
  53905. //attributeLocation = attributeLocations["aExtra"];
  53906. } else {
  53907. var attributeLocation = attributeLocations$1[attributeName].location;
  53908. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  53909. gl.enableVertexAttribArray(attributeLocation);
  53910. }
  53911. webglBuffer.vbos.set(attributeName, {
  53912. handle: vbo,
  53913. name: attributeName,
  53914. count: bufferAttribute.count,
  53915. itemSize: bufferAttribute.itemSize,
  53916. type: geometry.attributes.position.array.constructor,
  53917. version: 0
  53918. });
  53919. }
  53920. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  53921. gl.bindVertexArray(null);
  53922. var disposeHandler = event => {
  53923. this.deleteBuffer(geometry);
  53924. geometry.removeEventListener("dispose", disposeHandler);
  53925. };
  53926. geometry.addEventListener("dispose", disposeHandler);
  53927. return webglBuffer;
  53928. }
  53929. updateBuffer(geometry) {
  53930. var gl = this.gl;
  53931. var webglBuffer = this.buffers.get(geometry);
  53932. gl.bindVertexArray(webglBuffer.vao);
  53933. for (var attributeName in geometry.attributes) {
  53934. var bufferAttribute = geometry.attributes[attributeName];
  53935. var normalized = bufferAttribute.normalized;
  53936. var type = this.glTypeMapping.get(bufferAttribute.array.constructor);
  53937. var vbo = null;
  53938. if (!webglBuffer.vbos.has(attributeName)) {
  53939. vbo = gl.createBuffer();
  53940. webglBuffer.vbos.set(attributeName, {
  53941. handle: vbo,
  53942. name: attributeName,
  53943. count: bufferAttribute.count,
  53944. itemSize: bufferAttribute.itemSize,
  53945. type: geometry.attributes.position.array.constructor,
  53946. version: bufferAttribute.version
  53947. });
  53948. } else {
  53949. vbo = webglBuffer.vbos.get(attributeName).handle;
  53950. webglBuffer.vbos.get(attributeName).version = bufferAttribute.version;
  53951. }
  53952. gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
  53953. gl.bufferData(gl.ARRAY_BUFFER, bufferAttribute.array, gl.STATIC_DRAW);
  53954. if (attributeLocations$1[attributeName] === undefined) {
  53955. //attributeLocation = attributeLocations["aExtra"];
  53956. } else {
  53957. var attributeLocation = attributeLocations$1[attributeName].location;
  53958. gl.vertexAttribPointer(attributeLocation, bufferAttribute.itemSize, type, normalized, 0, 0);
  53959. gl.enableVertexAttribArray(attributeLocation);
  53960. }
  53961. }
  53962. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  53963. gl.bindVertexArray(null);
  53964. }
  53965. traverse(scene) {
  53966. var octrees = [];
  53967. var stack = [scene];
  53968. while (stack.length > 0) {
  53969. var node = stack.pop();
  53970. if (node instanceof PointCloudTree) {
  53971. octrees.push(node);
  53972. continue;
  53973. }
  53974. var visibleChildren = node.children.filter(c => c.visible);
  53975. stack.push(...visibleChildren);
  53976. }
  53977. var result = {
  53978. octrees: octrees
  53979. };
  53980. return result;
  53981. }
  53982. renderNodes(octree, nodes, visibilityTextureData, camera, target, shader, params) {
  53983. var _this = this;
  53984. viewer.addTimeMark('renderNodes', 'start');
  53985. var gl = this.gl;
  53986. var material = params.material ? params.material : octree.material;
  53987. var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  53988. var view = camera.matrixWorldInverse;
  53989. if (params.viewOverride) {
  53990. view = params.viewOverride;
  53991. }
  53992. var worldView = new Matrix4();
  53993. var mat4holder = new Float32Array(16);
  53994. var i = 0;
  53995. //---------从renderOctree搬到这----
  53996. shader.setUniform1f("size", material.usePanoMap ? Potree.config.material.absolutePanoramaSize * Math.min(window.devicePixelRatio, 2) : material.size); //usePanoMap时控制在不大不小的范围内感觉较好,考虑到有的点云稀疏,用大一点的点
  53997. shader.setUniform1f("uOpacity", material.usePanoMap ? 1 : material.opacity);
  53998. shader.setUniform3f("uColor", material.color.toArray());
  53999. var currentTextureBindingPoint = params.currentTextureBindingPoint;
  54000. if (material.pointSizeType >= 0 /* && window.needvisibilityTexture */) {
  54001. if (material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  54002. var vnNodes = params.vnTextureNodes != null ? params.vnTextureNodes : nodes;
  54003. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  54004. var vnt = material.visibleNodesTexture;
  54005. var data = vnt.image.data;
  54006. data.set(visibilityTextureData.data);
  54007. vnt.needsUpdate = true;
  54008. var webGLTexture = this.textures.get(vnt);
  54009. webGLTexture.update(); //不加这个会闪烁
  54010. var vnWebGLTexture = this.textures.get(material.visibleNodesTexture); //不知道为什么这段从renderOctree中移过来,会崩溃。暂时不移动了
  54011. if (vnWebGLTexture) {
  54012. shader.setUniform1i("visibleNodes", currentTextureBindingPoint);
  54013. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54014. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  54015. currentTextureBindingPoint++;
  54016. }
  54017. }
  54018. }
  54019. /* if (material.pointSizeType >= 0) {
  54020. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  54021. material.activeAttributeName === "level of detail") {
  54022. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  54023. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  54024. const vnt = material.visibleNodesTexture;
  54025. const data = vnt.image.data;
  54026. data.set(visibilityTextureData.data);
  54027. vnt.needsUpdate = true;
  54028. }
  54029. } */
  54030. var transparent = false;
  54031. if (params.transparent !== undefined) {
  54032. transparent = params.transparent && material.opacity < 1;
  54033. } else {
  54034. transparent = material.usePanoMap ? false : material.useFilterByNormal || material.opacity < 1; //add useFilterByNormal
  54035. }
  54036. if (transparent) {
  54037. gl.enable(gl.BLEND);
  54038. if (params.notAdditiveBlending) {
  54039. gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); //NormalBlending
  54040. /* gl.enable(gl.DEPTH_TEST);
  54041. gl.depthMask(true); //如果不开启depthWrite, 深度会错乱。 */ //无解
  54042. gl.disable(gl.DEPTH_TEST);
  54043. gl.depthMask(true);
  54044. } else {
  54045. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  54046. gl.disable(gl.DEPTH_TEST);
  54047. gl.depthMask(false);
  54048. }
  54049. } else {
  54050. gl.disable(gl.BLEND);
  54051. gl.depthMask(true);
  54052. gl.enable(gl.DEPTH_TEST);
  54053. }
  54054. if (params.blendFunc !== undefined) {
  54055. gl.enable(gl.BLEND);
  54056. gl.blendFunc(...params.blendFunc);
  54057. }
  54058. if (params.depthTest !== undefined) {
  54059. if (params.depthTest === true) {
  54060. gl.enable(gl.DEPTH_TEST);
  54061. } else {
  54062. gl.disable(gl.DEPTH_TEST);
  54063. }
  54064. }
  54065. if (params.depthWrite !== undefined) {
  54066. if (params.depthWrite === true) {
  54067. gl.depthMask(true);
  54068. } else {
  54069. gl.depthMask(false);
  54070. }
  54071. }
  54072. //---------------------------------
  54073. var _loop = function _loop() {
  54074. if (exports.debug.allowedNodes !== undefined) {
  54075. if (!exports.debug.allowedNodes.includes(node.name)) {
  54076. return 1; // continue
  54077. }
  54078. }
  54079. var world = node.sceneNode.matrixWorld;
  54080. worldView.multiplyMatrices(view, world);
  54081. if (visibilityTextureData) {
  54082. var vnStart = visibilityTextureData.offsets.get(node);
  54083. //console.log('vnStart',vnStart)
  54084. shader.setUniform1f("uVNStart", vnStart);
  54085. }
  54086. var level = node.getLevel();
  54087. if (node.debug) {
  54088. shader.setUniform("uDebug", true);
  54089. } else {
  54090. shader.setUniform("uDebug", false);
  54091. }
  54092. // let isLeaf = false;
  54093. // if(node instanceof PointCloudOctreeNode){
  54094. // isLeaf = Object.keys(node.children).length === 0;
  54095. // }else if(node instanceof PointCloudArena4DNode){
  54096. // isLeaf = node.geometryNode.isLeaf;
  54097. // }
  54098. // shader.setUniform("uIsLeafNode", isLeaf);
  54099. // let isLeaf = node.children.filter(n => n != null).length === 0;
  54100. // if(!isLeaf){
  54101. // continue;
  54102. // }
  54103. // TODO consider passing matrices in an array to avoid uniformMatrix4fv overhead
  54104. var lModel = shader.uniformLocations["modelMatrix"];
  54105. if (lModel) {
  54106. mat4holder.set(world.elements);
  54107. gl.uniformMatrix4fv(lModel, false, mat4holder);
  54108. }
  54109. var lModelView = shader.uniformLocations["modelViewMatrix"];
  54110. //mat4holder.set(worldView.elements);
  54111. // faster then set in chrome 63
  54112. for (var j = 0; j < 16; j++) {
  54113. mat4holder[j] = worldView.elements[j];
  54114. }
  54115. gl.uniformMatrix4fv(lModelView, false, mat4holder);
  54116. {
  54117. // Clip Polygons
  54118. if (material.clipPolygons && material.clipPolygons.length > 0) {
  54119. var clipPolygonVCount = [];
  54120. var worldViewProjMatrices = [];
  54121. for (var clipPolygon of material.clipPolygons) {
  54122. var _view = clipPolygon.viewMatrix;
  54123. var proj = clipPolygon.projMatrix;
  54124. var worldViewProj = proj.clone().multiply(_view).multiply(world);
  54125. clipPolygonVCount.push(clipPolygon.markers.length);
  54126. worldViewProjMatrices.push(worldViewProj);
  54127. }
  54128. var flattenedMatrices = [].concat(...worldViewProjMatrices.map(m => m.elements));
  54129. var flattenedVertices = new Array(8 * 3 * material.clipPolygons.length);
  54130. for (var _i3 = 0; _i3 < material.clipPolygons.length; _i3++) {
  54131. var _clipPolygon = material.clipPolygons[_i3];
  54132. for (var _j = 0; _j < _clipPolygon.markers.length; _j++) {
  54133. flattenedVertices[_i3 * 24 + (_j * 3 + 0)] = _clipPolygon.markers[_j].position.x;
  54134. flattenedVertices[_i3 * 24 + (_j * 3 + 1)] = _clipPolygon.markers[_j].position.y;
  54135. flattenedVertices[_i3 * 24 + (_j * 3 + 2)] = _clipPolygon.markers[_j].position.z;
  54136. }
  54137. }
  54138. var lClipPolygonVCount = shader.uniformLocations["uClipPolygonVCount[0]"];
  54139. gl.uniform1iv(lClipPolygonVCount, clipPolygonVCount);
  54140. var lClipPolygonVP = shader.uniformLocations["uClipPolygonWVP[0]"];
  54141. gl.uniformMatrix4fv(lClipPolygonVP, false, flattenedMatrices);
  54142. var lClipPolygons = shader.uniformLocations["uClipPolygonVertices[0]"];
  54143. gl.uniform3fv(lClipPolygons, flattenedVertices);
  54144. }
  54145. }
  54146. //shader.setUniformMatrix4("modelMatrix", world);
  54147. //shader.setUniformMatrix4("modelViewMatrix", worldView);
  54148. shader.setUniform1f("uLevel", level);
  54149. shader.setUniform1f("levelPercent", octree.nodeMaxLevel ? level / octree.nodeMaxLevel : 0.5); //xzw add
  54150. shader.setUniform1f("uNodeSpacing", node.geometryNode.estimatedSpacing);
  54151. shader.setUniform1f("uPCIndex", i);
  54152. // uBBSize
  54153. if (shadowMaps.length > 0) {
  54154. var lShadowMap = shader.uniformLocations["uShadowMap[0]"];
  54155. shader.setUniform3f("uShadowColor", material.uniforms.uShadowColor.value);
  54156. var bindingStart = 5;
  54157. var bindingPoints = new Array(shadowMaps.length).fill(bindingStart).map((a, i) => a + i);
  54158. gl.uniform1iv(lShadowMap, bindingPoints);
  54159. for (var _i4 = 0; _i4 < shadowMaps.length; _i4++) {
  54160. var shadowMap = shadowMaps[_i4];
  54161. var bindingPoint = bindingPoints[_i4];
  54162. var glTexture = _this.threeRenderer.properties.get(shadowMap.target.texture).__webglTexture;
  54163. gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]);
  54164. gl.bindTexture(gl.TEXTURE_2D, glTexture);
  54165. }
  54166. {
  54167. var worldViewMatrices = shadowMaps.map(sm => sm.camera.matrixWorldInverse).map(view => new Matrix4().multiplyMatrices(view, world));
  54168. var _flattenedMatrices = [].concat(...worldViewMatrices.map(c => c.elements));
  54169. var lWorldView = shader.uniformLocations["uShadowWorldView[0]"];
  54170. gl.uniformMatrix4fv(lWorldView, false, _flattenedMatrices);
  54171. }
  54172. {
  54173. var _flattenedMatrices2 = [].concat(...shadowMaps.map(sm => sm.camera.projectionMatrix.elements));
  54174. var lProj = shader.uniformLocations["uShadowProj[0]"];
  54175. gl.uniformMatrix4fv(lProj, false, _flattenedMatrices2);
  54176. }
  54177. }
  54178. var geometry = node.geometryNode.geometry;
  54179. if (geometry.attributes["gps-time"]) {
  54180. var bufferAttribute = geometry.attributes["gps-time"];
  54181. var attGPS = octree.getAttribute("gps-time");
  54182. var initialRange = attGPS.initialRange;
  54183. var initialRangeSize = initialRange[1] - initialRange[0];
  54184. var globalRange = attGPS.range;
  54185. var globalRangeSize = globalRange[1] - globalRange[0];
  54186. var scale = initialRangeSize / globalRangeSize;
  54187. var offset = -(globalRange[0] - initialRange[0]) / initialRangeSize;
  54188. scale = Number.isNaN(scale) ? 1 : scale;
  54189. offset = Number.isNaN(offset) ? 0 : offset;
  54190. shader.setUniform1f("uGpsScale", scale);
  54191. shader.setUniform1f("uGpsOffset", offset);
  54192. //shader.setUniform2f("uFilterGPSTimeClipRange", [-Infinity, Infinity]);
  54193. var uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  54194. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  54195. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  54196. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  54197. var normalizedClipRange = [(uFilterGPSTimeClipRange[0] - globalRange[0]) / globalRangeSize, (uFilterGPSTimeClipRange[1] - globalRange[0]) / globalRangeSize];
  54198. shader.setUniform2f("uFilterGPSTimeClipRange", normalizedClipRange);
  54199. // // ranges in full gps coordinate system
  54200. // const globalRange = attGPS.range;
  54201. // const bufferRange = bufferAttribute.potree.range;
  54202. // // ranges in [0, 1]
  54203. // // normalizedGlobalRange = [0, 1]
  54204. // // normalizedBufferRange: norm buffer within norm global range e.g. [0.2, 0.8]
  54205. // const globalWidth = globalRange[1] - globalRange[0];
  54206. // const normalizedBufferRange = [
  54207. // (bufferRange[0] - globalRange[0]) / globalWidth,
  54208. // (bufferRange[1] - globalRange[0]) / globalWidth,
  54209. // ];
  54210. // shader.setUniform2f("uNormalizedGpsBufferRange", normalizedBufferRange);
  54211. // let uFilterGPSTimeClipRange = material.uniforms.uFilterGPSTimeClipRange.value;
  54212. // let gpsCliPRangeMin = uFilterGPSTimeClipRange[0]
  54213. // let gpsCliPRangeMax = uFilterGPSTimeClipRange[1]
  54214. // shader.setUniform2f("uFilterGPSTimeClipRange", [gpsCliPRangeMin, gpsCliPRangeMax]);
  54215. // shader.setUniform1f("uGpsScale", bufferAttribute.potree.scale);
  54216. // shader.setUniform1f("uGpsOffset", bufferAttribute.potree.offset);
  54217. }
  54218. {
  54219. var uFilterReturnNumberRange = material.uniforms.uFilterReturnNumberRange.value;
  54220. var uFilterNumberOfReturnsRange = material.uniforms.uFilterNumberOfReturnsRange.value;
  54221. var uFilterPointSourceIDClipRange = material.uniforms.uFilterPointSourceIDClipRange.value;
  54222. shader.setUniform2f("uFilterReturnNumberRange", uFilterReturnNumberRange);
  54223. shader.setUniform2f("uFilterNumberOfReturnsRange", uFilterNumberOfReturnsRange);
  54224. shader.setUniform2f("uFilterPointSourceIDClipRange", uFilterPointSourceIDClipRange);
  54225. }
  54226. var webglBuffer = null;
  54227. if (!_this.buffers.has(geometry)) {
  54228. webglBuffer = _this.createBuffer(geometry);
  54229. _this.buffers.set(geometry, webglBuffer);
  54230. } else {
  54231. webglBuffer = _this.buffers.get(geometry);
  54232. for (var attributeName in geometry.attributes) {
  54233. var attribute = geometry.attributes[attributeName];
  54234. if (attribute.version > webglBuffer.vbos.get(attributeName).version) {
  54235. _this.updateBuffer(geometry);
  54236. }
  54237. }
  54238. }
  54239. gl.bindVertexArray(webglBuffer.vao);
  54240. var isExtraAttribute = attributeLocations$1[material.activeAttributeName] === undefined && Object.keys(geometry.attributes).includes(material.activeAttributeName);
  54241. if (isExtraAttribute) {
  54242. var attributeLocation = attributeLocations$1["aExtra"].location;
  54243. for (var _attributeName in geometry.attributes) {
  54244. var _bufferAttribute = geometry.attributes[_attributeName];
  54245. var _vbo = webglBuffer.vbos.get(_attributeName);
  54246. gl.bindBuffer(gl.ARRAY_BUFFER, _vbo.handle);
  54247. gl.disableVertexAttribArray(attributeLocation);
  54248. }
  54249. var attName = material.activeAttributeName;
  54250. var _bufferAttribute2 = geometry.attributes[attName];
  54251. var vbo = webglBuffer.vbos.get(attName);
  54252. if (_bufferAttribute2 !== undefined && vbo !== undefined) {
  54253. var type = _this.glTypeMapping.get(_bufferAttribute2.array.constructor);
  54254. var normalized = _bufferAttribute2.normalized;
  54255. gl.bindBuffer(gl.ARRAY_BUFFER, vbo.handle);
  54256. gl.vertexAttribPointer(attributeLocation, _bufferAttribute2.itemSize, type, normalized, 0, 0);
  54257. gl.enableVertexAttribArray(attributeLocation);
  54258. }
  54259. {
  54260. var attExtra = octree.pcoGeometry.pointAttributes.attributes.find(a => a.name === attName);
  54261. var range = material.getRange(attName);
  54262. if (!range) {
  54263. range = attExtra.range;
  54264. }
  54265. if (!range) {
  54266. range = [0, 1];
  54267. }
  54268. var _initialRange = attExtra.initialRange;
  54269. var _initialRangeSize = _initialRange[1] - _initialRange[0];
  54270. var _globalRange = range;
  54271. var _globalRangeSize = _globalRange[1] - _globalRange[0];
  54272. var _scale = _initialRangeSize / _globalRangeSize;
  54273. var _offset = -(_globalRange[0] - _initialRange[0]) / _initialRangeSize;
  54274. _scale = Number.isNaN(_scale) ? 1 : _scale;
  54275. _offset = Number.isNaN(_offset) ? 0 : _offset;
  54276. shader.setUniform1f("uExtraScale", _scale);
  54277. shader.setUniform1f("uExtraOffset", _offset);
  54278. }
  54279. } else {
  54280. for (var _attributeName2 in geometry.attributes) {
  54281. var _bufferAttribute3 = geometry.attributes[_attributeName2];
  54282. var _vbo2 = webglBuffer.vbos.get(_attributeName2);
  54283. if (attributeLocations$1[_attributeName2] !== undefined) {
  54284. var _attributeLocation = attributeLocations$1[_attributeName2].location;
  54285. var _type = _this.glTypeMapping.get(_bufferAttribute3.array.constructor);
  54286. var _normalized = _bufferAttribute3.normalized;
  54287. gl.bindBuffer(gl.ARRAY_BUFFER, _vbo2.handle);
  54288. gl.vertexAttribPointer(_attributeLocation, _bufferAttribute3.itemSize, _type, _normalized, 0, 0);
  54289. gl.enableVertexAttribArray(_attributeLocation);
  54290. }
  54291. }
  54292. }
  54293. var numPoints = webglBuffer.numElements;
  54294. gl.drawArrays(gl.POINTS, 0, numPoints);
  54295. //gl.drawArrays(gl.TRIANGLES, 0, numPoints);
  54296. i++;
  54297. };
  54298. for (var node of nodes) {
  54299. if (_loop()) continue;
  54300. }
  54301. gl.bindVertexArray(null);
  54302. viewer.addTimeMark('renderNodes', 'end');
  54303. }
  54304. renderOctree(octrees, nodes, camera, target) {
  54305. var params = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  54306. viewer.addTimeMark('renderOctree', 'start');
  54307. var octree;
  54308. if (octrees instanceof Array) {
  54309. octree = octrees[0];
  54310. } else {
  54311. octree = octrees;
  54312. octrees = [octree];
  54313. }
  54314. var gl = this.gl;
  54315. var material = params.material ? params.material : octree.material;
  54316. var shadowMaps = params.shadowMaps == null ? [] : params.shadowMaps;
  54317. var view = camera.matrixWorldInverse;
  54318. var viewInv = camera.matrixWorld;
  54319. if (params.viewOverride) {
  54320. view = params.viewOverride;
  54321. viewInv = view.clone().invert();
  54322. }
  54323. var proj = camera.projectionMatrix;
  54324. var projInv = proj.clone().invert();
  54325. //let worldView = new THREE.Matrix4();
  54326. var shader = null;
  54327. var visibilityTextureData = null;
  54328. var currentTextureBindingPoint = 0;
  54329. /* if (material.pointSizeType >= 0) {//最好搬到renderNodes
  54330. if (material.pointSizeType === PointSizeType.ADAPTIVE ||
  54331. material.activeAttributeName === "level of detail") {
  54332. let vnNodes = (params.vnTextureNodes != null) ? params.vnTextureNodes : nodes;
  54333. visibilityTextureData = octree.computeVisibilityTextureData(vnNodes, camera);
  54334. const vnt = material.visibleNodesTexture;
  54335. const data = vnt.image.data;
  54336. data.set(visibilityTextureData.data);
  54337. vnt.needsUpdate = true;
  54338. }
  54339. }
  54340. */
  54341. {
  54342. // UPDATE SHADER AND TEXTURES
  54343. if (!this.shaders.has(material)) {
  54344. var [vs, fs] = [material.vertexShader, material.fragmentShader];
  54345. var _shader = new Shader$1(gl, "pointcloud", vs, fs);
  54346. this.shaders.set(material, _shader);
  54347. }
  54348. shader = this.shaders.get(material);
  54349. if (material.shaderNeedsUpdate) {
  54350. var [_vs, _fs] = [material.vertexShader, material.fragmentShader];
  54351. var numSnapshots = material.snapEnabled ? material.numSnapshots : 0;
  54352. var num_in_clipboxes = material.clipBoxes_in && material.clipBoxes_in.length ? material.clipBoxes_in.length : 0;
  54353. var num_out_clipboxes = material.clipBoxes_out && material.clipBoxes_out.length ? material.clipBoxes_out.length : 0;
  54354. var num_highlightBox = material.highlightBoxes && material.highlightBoxes.length ? material.highlightBoxes.length : 0;
  54355. var numClipSpheres = params.clipSpheres && params.clipSpheres.length ? params.clipSpheres.length : 0;
  54356. var numClipPolygons = material.clipPolygons && material.clipPolygons.length ? material.clipPolygons.length : 0;
  54357. var defines = ["#define num_shadowmaps ".concat(shadowMaps.length), "#define num_snapshots ".concat(numSnapshots), "#define num_in_clipboxes ".concat(num_in_clipboxes), //改
  54358. "#define num_out_clipboxes ".concat(num_out_clipboxes), //改
  54359. "#define num_highlightBox ".concat(num_highlightBox), //改
  54360. "#define num_clipspheres ".concat(numClipSpheres), "#define num_prism ".concat(material.prisms.pointsCount ? material.prisms.length : 0), //土方量数 如果num_prism>0,prismPointCountSum为0 会报错 :array size must be greater than zero
  54361. "#define prismPointCountSum ".concat(material.prisms.pointsCount), //点总个数
  54362. "#define prism_maxPointsCount ".concat(material.prisms.maxPointsCount) //单个prism最大点个数 (如果define也能传递个数数组,就不用再uniform里传了,呜 )
  54363. ];
  54364. //add:-----------
  54365. if (material.bigClipInBox) {
  54366. //裁剪下载
  54367. defines.push('#define bigClipInBox');
  54368. }
  54369. if (material.usePanoMap) {
  54370. defines.push("#define usePanoMap");
  54371. }
  54372. if (material.useFilterByNormal) {
  54373. defines.push("#define use_filter_by_normal");
  54374. //Potree.settings.editType == 'pano' ? defines.push("#define attenuated_opacity2") : defines.push("#define attenuated_opacity");
  54375. }
  54376. if (material.uniforms.baseHeightAreaMap.value) {
  54377. //根据模型高亮土方
  54378. defines.push('#define showBaseHeight');
  54379. }
  54380. //---------------
  54381. if (octree.pcoGeometry.root.isLoaded()) {
  54382. var attributes = octree.pcoGeometry.root.geometry.attributes;
  54383. if (attributes["gps-time"]) {
  54384. defines.push("#define clip_gps_enabled");
  54385. }
  54386. if (attributes["return number"]) {
  54387. defines.push("#define clip_return_number_enabled");
  54388. }
  54389. if (attributes["number of returns"]) {
  54390. defines.push("#define clip_number_of_returns_enabled");
  54391. }
  54392. if (attributes["source id"] || attributes["point source id"]) {
  54393. defines.push("#define clip_point_source_id_enabled");
  54394. }
  54395. }
  54396. var definesString = defines.join("\n");
  54397. var vsVersionIndex = _vs.indexOf("#version ");
  54398. var fsVersionIndex = _fs.indexOf("#version ");
  54399. if (vsVersionIndex >= 0) {
  54400. _vs = _vs.replace(/(#version .*)/, "$1\n".concat(definesString));
  54401. } else {
  54402. _vs = "".concat(definesString, "\n").concat(_vs);
  54403. }
  54404. if (fsVersionIndex >= 0) {
  54405. _fs = _fs.replace(/(#version .*)/, "$1\n".concat(definesString));
  54406. } else {
  54407. _fs = "".concat(definesString, "\n").concat(_fs);
  54408. }
  54409. shader.update(_vs, _fs);
  54410. material.shaderNeedsUpdate = false;
  54411. }
  54412. for (var uniformName of Object.keys(material.uniforms)) {
  54413. var uniform = material.uniforms[uniformName];
  54414. if (uniform.type == "t") {
  54415. var texture = uniform.value;
  54416. if (!texture) {
  54417. continue;
  54418. }
  54419. //add
  54420. if (uniformName == 'pano0Map' || uniformName == 'pano1Map') {
  54421. //属于cubeTex,另外设置
  54422. continue;
  54423. }
  54424. /* if(texture.image && !(texture.image instanceof Image) && !(texture instanceof THREE.CanvasTexture)){
  54425. //renderTarget的texture在创建renderTarget时已经初始化过 见setupRenderTarget
  54426. continue
  54427. } */
  54428. if (!this.textures.has(texture) || texture.needsRebuild) {
  54429. var webglTexture = new WebGLTexture$1(gl, texture, this.threeRenderer);
  54430. this.textures.set(texture, webglTexture);
  54431. delete texture.needsRebuild; //renderTarget在resize后会触发dispose, 然后 _gl.deleteTexture( textureProperties.__webglTexture )所以需要重新建立
  54432. }
  54433. var webGLTexture = this.textures.get(texture);
  54434. webGLTexture.update();
  54435. }
  54436. }
  54437. }
  54438. gl.useProgram(shader.program);
  54439. /* let transparent = false;
  54440. if(params.transparent !== undefined){
  54441. transparent = params.transparent && material.opacity < 1;
  54442. }else{
  54443. transparent = material.usePanoMap ? false : (material.useFilterByNormal || material.opacity < 1); //add useFilterByNormal
  54444. }
  54445. if (transparent){
  54446. gl.enable(gl.BLEND);
  54447. if(params.notAdditiveBlending){
  54448. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); //NormalBlending
  54449. gl.enable(gl.DEPTH_TEST);
  54450. gl.depthMask(true); //如果不开启depthWrite,深度会错乱。
  54451. }else{
  54452. gl.blendFunc(gl.SRC_ALPHA, gl.ONE); //AdditiveBlending 原本
  54453. gl.disable(gl.DEPTH_TEST);
  54454. gl.depthMask(false);
  54455. }
  54456. } else {
  54457. gl.disable(gl.BLEND);
  54458. gl.depthMask(true);
  54459. gl.enable(gl.DEPTH_TEST);
  54460. }
  54461. if(params.blendFunc !== undefined){
  54462. gl.enable(gl.BLEND);
  54463. gl.blendFunc(...params.blendFunc);
  54464. }
  54465. if(params.depthTest !== undefined){
  54466. if(params.depthTest === true){
  54467. gl.enable(gl.DEPTH_TEST);
  54468. }else{
  54469. gl.disable(gl.DEPTH_TEST);
  54470. }
  54471. }
  54472. if(params.depthWrite !== undefined){
  54473. if(params.depthWrite === true){
  54474. gl.depthMask(true);
  54475. }else{
  54476. gl.depthMask(false);
  54477. }
  54478. } */
  54479. {
  54480. // UPDATE UNIFORMS
  54481. shader.setUniformMatrix4("projectionMatrix", proj);
  54482. shader.setUniformMatrix4("viewMatrix", view);
  54483. shader.setUniformMatrix4("uViewInv", viewInv);
  54484. shader.setUniformMatrix4("uProjInv", projInv);
  54485. /* let screenWidth = target ? target.width : material.screenWidth;
  54486. let screenHeight = target ? target.height : material.screenHeight;
  54487. shader.setUniform1f("uScreenWidth", screenWidth);
  54488. shader.setUniform1f("uScreenHeight", screenHeight); */
  54489. shader.setUniform2f('resolution', material.resolution.toArray());
  54490. shader.setUniform1f("fov", Math.PI * camera.fov / 180);
  54491. shader.setUniform1f("near", camera.near);
  54492. shader.setUniform1f("far", camera.far);
  54493. if (camera instanceof OrthographicCamera) {
  54494. shader.setUniform("uUseOrthographicCamera", true);
  54495. shader.setUniform("uOrthoWidth", (camera.right - camera.left) / camera.zoom); //改
  54496. shader.setUniform("uOrthoHeight", camera.top - camera.bottom);
  54497. } else {
  54498. shader.setUniform("uUseOrthographicCamera", false);
  54499. }
  54500. /* if(material.clipBoxes.length + material.clipPolygons.length === 0){//改
  54501. shader.setUniform1i("clipTask", ClipTask.NONE);
  54502. }else{
  54503. shader.setUniform1i("clipTask", material.clipTask);
  54504. }
  54505. shader.setUniform1i("clipMethod", material.clipMethod);*/
  54506. //改
  54507. if (material.clipBoxes_in && material.clipBoxes_in.length > 0) {
  54508. //let flattenedMatrices = [].concat(...material.clipBoxes.map(c => c.inverse.elements));
  54509. var lClipBoxes = shader.uniformLocations["clipBoxes_in[0]"];
  54510. gl.uniformMatrix4fv(lClipBoxes, false, material.uniforms.clipBoxes_in.value);
  54511. }
  54512. if (material.clipBoxes_out && material.clipBoxes_out.length > 0) {
  54513. //add
  54514. var lClipBoxes2 = shader.uniformLocations["clipBoxes_out[0]"];
  54515. gl.uniformMatrix4fv(lClipBoxes2, false, material.uniforms.clipBoxes_out.value);
  54516. }
  54517. if (material.highlightBoxes && material.highlightBoxes.length > 0) {
  54518. //add
  54519. var boxes_highlight = shader.uniformLocations["boxes_highlight[0]"];
  54520. gl.uniformMatrix4fv(boxes_highlight, false, material.uniforms.boxes_highlight.value);
  54521. }
  54522. if (material.bigClipInBox) {
  54523. //add
  54524. shader.setUniformMatrix4("clipBoxBig_in", material.uniforms.clipBoxBig_in.value);
  54525. }
  54526. if (material.uniforms.baseHeightAreaMap.value) {
  54527. //根据模型高亮土方
  54528. var baseHeightBoundZ = shader.uniformLocations["baseHeightBoundZ"];
  54529. gl.uniform2f(baseHeightBoundZ, ...material.uniforms.baseHeightBoundZ.value.toArray());
  54530. var baseHeightBoundXY = shader.uniformLocations["baseHeightBoundXY"];
  54531. gl.uniform4f(baseHeightBoundXY, ...material.uniforms.baseHeightBoundXY.value.toArray());
  54532. }
  54533. if (material.prisms.length) {
  54534. var prismList = shader.uniformLocations["prismList[0]"];
  54535. gl.uniformMatrix3fv(prismList, false, material.uniforms.prismList.value);
  54536. var prismPoints = shader.uniformLocations["prismPoints[0]"];
  54537. gl.uniform2fv(prismPoints, material.uniforms.prismPoints.value);
  54538. }
  54539. // TODO CLIPSPHERES
  54540. if (params.clipSpheres && params.clipSpheres.length > 0) {
  54541. var clipSpheres = params.clipSpheres;
  54542. var matrices = [];
  54543. for (var clipSphere of clipSpheres) {
  54544. //let mScale = new THREE.Matrix4().makeScale(...clipSphere.scale.toArray());
  54545. //let mTranslate = new THREE.Matrix4().makeTranslation(...clipSphere.position.toArray());
  54546. //let clipToWorld = new THREE.Matrix4().multiplyMatrices(mTranslate, mScale);
  54547. var clipToWorld = clipSphere.matrixWorld;
  54548. var viewToWorld = camera.matrixWorld;
  54549. var worldToClip = clipToWorld.clone().invert();
  54550. var viewToClip = new Matrix4().multiplyMatrices(worldToClip, viewToWorld);
  54551. matrices.push(viewToClip);
  54552. }
  54553. var flattenedMatrices = [].concat(...matrices.map(matrix => matrix.elements));
  54554. var lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  54555. gl.uniformMatrix4fv(lClipSpheres, false, flattenedMatrices);
  54556. //const lClipSpheres = shader.uniformLocations["uClipSpheres[0]"];
  54557. //gl.uniformMatrix4fv(lClipSpheres, false, material.uniforms.clipSpheres.value);
  54558. }
  54559. shader.setUniform1f("orthoMaxSize", material.uniforms.orthoMaxSize.value);
  54560. shader.setUniform1f("maxSize", material.uniforms.maxSize.value);
  54561. shader.setUniform1f("minSize", material.uniforms.minSize.value);
  54562. // uniform float uPCIndex
  54563. shader.setUniform1f("uOctreeSpacing", material.spacing);
  54564. shader.setUniform("uOctreeSize", material.uniforms.octreeSize.value);
  54565. shader.setUniform2f("elevationRange", material.elevationRange);
  54566. shader.setUniform2f("intensityRange", material.intensityRange);
  54567. shader.setUniform3f("uIntensity_gbc", [material.intensityGamma, material.intensityBrightness, material.intensityContrast]);
  54568. shader.setUniform3f("uRGB_gbc", [material.rgbGamma, material.rgbBrightness, material.rgbContrast]);
  54569. shader.setUniform1f("uTransition", material.transition);
  54570. shader.setUniform1f("wRGB", material.weightRGB);
  54571. shader.setUniform1f("wIntensity", material.weightIntensity);
  54572. shader.setUniform1f("wElevation", material.weightElevation);
  54573. shader.setUniform1f("wClassification", material.weightClassification);
  54574. shader.setUniform1f("wReturnNumber", material.weightReturnNumber);
  54575. shader.setUniform1f("wSourceID", material.weightSourceID);
  54576. shader.setUniform("backfaceCulling", material.uniforms.backfaceCulling.value);
  54577. //==========================
  54578. //gl.TEXTURE_CUBE_MAP: 34067
  54579. //gl.TEXTURE0=33984 , vnWebGLTexture.target=gl.TEXTURE_2D = 3353
  54580. /* let vnWebGLTexture = this.textures.get(material.visibleNodesTexture);//最好搬到renderNodes
  54581. if(vnWebGLTexture){
  54582. shader.setUniform1i("visibleNodes", currentTextureBindingPoint); //为何之前写的是"visibleNodesTexture",但和"visibleNodes"效果相同?可shader里只有"visibleNodes"
  54583. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54584. gl.bindTexture(vnWebGLTexture.target, vnWebGLTexture.id);
  54585. currentTextureBindingPoint++;
  54586. } */
  54587. var gradientTexture = this.textures.get(material.gradientTexture);
  54588. shader.setUniform1i("gradient", currentTextureBindingPoint);
  54589. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54590. gl.bindTexture(gradientTexture.target, gradientTexture.id);
  54591. currentTextureBindingPoint++;
  54592. var repeat = material.elevationGradientRepeat;
  54593. if (repeat === ElevationGradientRepeat.REPEAT) {
  54594. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.REPEAT);
  54595. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.REPEAT);
  54596. } else if (repeat === ElevationGradientRepeat.MIRRORED_REPEAT) {
  54597. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
  54598. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
  54599. } else {
  54600. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  54601. gl.texParameteri(gradientTexture.target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  54602. }
  54603. currentTextureBindingPoint++;
  54604. var classificationTexture = this.textures.get(material.classificationTexture);
  54605. shader.setUniform1i("classificationLUT", currentTextureBindingPoint);
  54606. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54607. gl.bindTexture(classificationTexture.target, classificationTexture.id);
  54608. currentTextureBindingPoint++;
  54609. /* let matcapTexture = this.textures.get(material.matcapTexture);
  54610. shader.setUniform1i("matcapTextureUniform", currentTextureBindingPoint);
  54611. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54612. gl.bindTexture(matcapTexture.target, matcapTexture.id);
  54613. currentTextureBindingPoint++; */
  54614. var baseHeightAreaMap = material.uniforms.baseHeightAreaMap.value;
  54615. if (baseHeightAreaMap) {
  54616. //根据模型高亮土方
  54617. var map = this.textures.get(baseHeightAreaMap);
  54618. shader.setUniform1i("baseHeightAreaMap", currentTextureBindingPoint);
  54619. gl.activeTexture(gl.TEXTURE0 + currentTextureBindingPoint);
  54620. gl.bindTexture(map.target, map.id);
  54621. currentTextureBindingPoint++;
  54622. }
  54623. if (material.snapEnabled === true) {
  54624. {
  54625. var lSnapshot = shader.uniformLocations["uSnapshot[0]"];
  54626. var lSnapshotDepth = shader.uniformLocations["uSnapshotDepth[0]"];
  54627. var bindingStart = currentTextureBindingPoint;
  54628. var lSnapshotBindingPoints = new Array(5).fill(bindingStart).map((a, i) => a + i);
  54629. var lSnapshotDepthBindingPoints = new Array(5).fill(1 + Math.max(...lSnapshotBindingPoints)).map((a, i) => a + i);
  54630. currentTextureBindingPoint = 1 + Math.max(...lSnapshotDepthBindingPoints);
  54631. gl.uniform1iv(lSnapshot, lSnapshotBindingPoints);
  54632. gl.uniform1iv(lSnapshotDepth, lSnapshotDepthBindingPoints);
  54633. for (var i = 0; i < 5; i++) {
  54634. var _texture = material.uniforms["uSnapshot"].value[i];
  54635. var textureDepth = material.uniforms["uSnapshotDepth"].value[i];
  54636. if (!_texture) {
  54637. break;
  54638. }
  54639. var snapTexture = this.threeRenderer.properties.get(_texture).__webglTexture;
  54640. var snapTextureDepth = this.threeRenderer.properties.get(textureDepth).__webglTexture;
  54641. var bindingPoint = lSnapshotBindingPoints[i];
  54642. var depthBindingPoint = lSnapshotDepthBindingPoints[i];
  54643. gl.activeTexture(gl["TEXTURE".concat(bindingPoint)]);
  54644. gl.bindTexture(gl.TEXTURE_2D, snapTexture);
  54645. gl.activeTexture(gl["TEXTURE".concat(depthBindingPoint)]);
  54646. gl.bindTexture(gl.TEXTURE_2D, snapTextureDepth);
  54647. }
  54648. }
  54649. {
  54650. var _flattenedMatrices3 = [].concat(...material.uniforms.uSnapView.value.map(c => c.elements));
  54651. var lSnapView = shader.uniformLocations["uSnapView[0]"];
  54652. gl.uniformMatrix4fv(lSnapView, false, _flattenedMatrices3);
  54653. }
  54654. {
  54655. var _flattenedMatrices4 = [].concat(...material.uniforms.uSnapProj.value.map(c => c.elements));
  54656. var lSnapProj = shader.uniformLocations["uSnapProj[0]"];
  54657. gl.uniformMatrix4fv(lSnapProj, false, _flattenedMatrices4);
  54658. }
  54659. {
  54660. var _flattenedMatrices5 = [].concat(...material.uniforms.uSnapProjInv.value.map(c => c.elements));
  54661. var lSnapProjInv = shader.uniformLocations["uSnapProjInv[0]"];
  54662. gl.uniformMatrix4fv(lSnapProjInv, false, _flattenedMatrices5);
  54663. }
  54664. {
  54665. var _flattenedMatrices6 = [].concat(...material.uniforms.uSnapViewInv.value.map(c => c.elements));
  54666. var lSnapViewInv = shader.uniformLocations["uSnapViewInv[0]"];
  54667. gl.uniformMatrix4fv(lSnapViewInv, false, _flattenedMatrices6);
  54668. }
  54669. }
  54670. //=============add===========
  54671. if (material.usePanoMap) {
  54672. //为什么pointsize失效
  54673. shader.setUniform1f("progress", material.uniforms.progress.value);
  54674. shader.setUniform1f("easeInOutRatio", material.uniforms.easeInOutRatio.value);
  54675. shader.setUniform3f("pano0Position", material.uniforms.pano0Position.value.toArray());
  54676. shader.setUniform3f("pano1Position", material.uniforms.pano1Position.value.toArray());
  54677. shader.setUniform('pano0Matrix', material.uniforms.pano0Matrix.value);
  54678. shader.setUniform('pano1Matrix', material.uniforms.pano1Matrix.value);
  54679. var pano0Map = material.uniforms.pano0Map.value;
  54680. if (pano0Map) {
  54681. this.threeRenderer._textures.safeSetTextureCube(pano0Map, ++currentTextureBindingPoint);
  54682. shader.setUniform1i('pano0Map', currentTextureBindingPoint);
  54683. }
  54684. var pano1Map = material.uniforms.pano1Map.value;
  54685. if (pano1Map) {
  54686. this.threeRenderer._textures.safeSetTextureCube(pano1Map, ++currentTextureBindingPoint);
  54687. shader.setUniform1i('pano1Map', currentTextureBindingPoint);
  54688. }
  54689. //注: three.js我添加了个 _textures, safeSetTextureCube里主要就是activeTexture和bindTexture
  54690. }
  54691. }
  54692. viewer.addTimeMark('renderOctree', 'end');
  54693. params.currentTextureBindingPoint = ++currentTextureBindingPoint;
  54694. octrees.forEach(octree => {
  54695. this.renderNodes(octree, nodes || octree.visibleNodes, visibilityTextureData, camera, target, shader, params);
  54696. });
  54697. gl.activeTexture(gl.TEXTURE2);
  54698. gl.bindTexture(gl.TEXTURE_2D, null);
  54699. gl.activeTexture(gl.TEXTURE0);
  54700. //gl.bindTexture(gl.TEXTURE_2D, null); //add
  54701. //add 恢复为不透明(否则renderToCubeMap时的贴图会被渲染成高亮的颜色)
  54702. gl.disable(gl.BLEND);
  54703. gl.depthMask(true);
  54704. gl.enable(gl.DEPTH_TEST);
  54705. //DEPTH_TEST等需要恢复吗
  54706. }
  54707. render(scene, camera) {
  54708. var target = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
  54709. var params = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  54710. var gl = this.gl;
  54711. // PREPARE
  54712. if (target != null) {
  54713. this.threeRenderer.setRenderTarget(target);
  54714. }
  54715. //camera.updateProjectionMatrix();
  54716. // camera.matrixWorldInverse.invert(camera.matrixWorld);
  54717. var traversalResult = this.traverse(scene);
  54718. //排序
  54719. if (params.notAdditiveBlending) {
  54720. //add
  54721. traversalResult.octrees.forEach(tree => {
  54722. if (tree.material.opacity == 1) {
  54723. tree._z = Infinity; //不透明的先渲染
  54724. } else {
  54725. var center = tree.boundCenter ? tree.boundCenter.clone() : tree.boundingBox.getCenter(tree.boundCenter).applyMatrix4(tree.matrixWorld);
  54726. center.project(camera);
  54727. tree._z = center.z;
  54728. }
  54729. });
  54730. traversalResult.octrees.sort((tree1, tree2) => {
  54731. return tree2._z - tree1._z; //降序 (-1 朝外)。 离屏幕近的后渲染
  54732. });
  54733. }
  54734. // RENDER
  54735. var mat = params.material || traversalResult.octrees[0].material;
  54736. if (Potree.settings.cloudSameMat && viewer.scene.volumes.length == 0 && mat.pointSizeType != PointSizeType.ADAPTIVE && mat.activeAttributeName != "level of detail") {
  54737. this.renderOctree(traversalResult.octrees, null, camera, target, params); //所有点云除了个别属性需要在shader中更新,其他都使用第一个点云的材质
  54738. } else for (var octree of traversalResult.octrees) {
  54739. for (var _octree of traversalResult.octrees) {
  54740. this.renderOctree(_octree, _octree.visibleNodes, camera, target, params);
  54741. }
  54742. }
  54743. //if (octree material.pointSizeType === PointSizeType.ADAPTIVE || material.activeAttributeName === "level of detail") {
  54744. // CLEANUP
  54745. gl.activeTexture(gl.TEXTURE1);
  54746. gl.bindTexture(gl.TEXTURE_2D, null);
  54747. gl.bindBuffer(gl.ARRAY_BUFFER, null);
  54748. gl.bindVertexArray(null);
  54749. this.threeRenderer.resetState();
  54750. }
  54751. }
  54752. ;
  54753. /*
  54754. 中东的链接http://indoor.popsmart.cn:8094/zdoblh-yz/?vlon=5.14&vlat=-0.13&fov=100.0&pc=true&lon=121.61136592&lat=29.87855579&z=16.577
  54755. geometry: 有的attributes: 属性是:
  54756. classification:
  54757. color:
  54758. indices:
  54759. normal:
  54760. position:
  54761. 最好有个spacing
  54762. */
  54763. //
  54764. // Algorithm by Christian Boucheny
  54765. // shader code taken and adapted from CloudCompare
  54766. //
  54767. // see
  54768. // https://github.com/cloudcompare/trunk/tree/master/plugins/qEDL/shaders/EDL
  54769. // http://www.kitware.com/source/home/post/9
  54770. // https://tel.archives-ouvertes.fr/tel-00438464/document p. 115+ (french)
  54771. class ExtendEyeDomeLightingMaterial extends EyeDomeLightingMaterial {
  54772. constructor() {
  54773. var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  54774. super(parameters);
  54775. delete this.uniforms.screenWidth;
  54776. delete this.uniforms.screenHeight;
  54777. this.uniforms.resolution = {
  54778. type: 'v2',
  54779. value: new Vector2()
  54780. };
  54781. this.uniforms.useEDL = {
  54782. type: 'i',
  54783. value: 1
  54784. };
  54785. this.vertexShader = this.getDefines() + Shaders['edl_new.vs']; //改
  54786. this.fragmentShader = this.getDefines() + Shaders['edl_new.fs']; //改
  54787. }
  54788. }
  54789. var copyShader = {
  54790. uniforms: {
  54791. tDiffuse: {
  54792. type: "t",
  54793. value: null
  54794. },
  54795. opacity: {
  54796. type: "f",
  54797. value: 1
  54798. },
  54799. depthTex: {
  54800. type: "t",
  54801. value: null
  54802. }
  54803. },
  54804. vertexShader: " \n varying vec2 vUv;\n void main() {\n vUv = uv; \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }\n ",
  54805. fragmentShader: "\n #extension GL_EXT_frag_depth : enable\n uniform float opacity;\n uniform sampler2D tDiffuse;\n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n uniform sampler2D depthTex;\n #endif\n \n varying vec2 vUv;\n void main() { \n #if defined(GL_EXT_frag_depth) && defined(useDepth) \n float depth = texture2D(depthTex, vUv).r;\n /* if(depth >= 1.0){ //\u8D85\u7EA7\u8FDC\uFF08\u4F46\u662F\u5728modelTex\u91CC\u6211\u628A\u5929\u7A7A\u8DDD\u79BB\u8D85\u51FAfar\u4E86\uFF0C\u6240\u4EE5\u4E0D\u5220\uFF09\n discard;\n } */\n gl_FragDepthEXT = depth; \n #endif\n \n \n \n vec4 texel = texture2D( tDiffuse, vUv );\n gl_FragColor = opacity * texel; \n \n \n } \n "
  54806. };
  54807. //import DepthTexSampler from "../custom/utils/DepthTexSampler.js";
  54808. class EDLRenderer {
  54809. //Eye-Dome Lighting 眼罩照明
  54810. constructor(viewer) {
  54811. this.viewer = viewer;
  54812. this.edlMaterial = null;
  54813. //this.rtRegular;
  54814. this.rtEDLs = new Map();
  54815. this.gl = viewer.renderer.getContext();
  54816. //反正也没用到,注释了:
  54817. //this.shadowMap = new PointCloudSM(this.viewer.pRenderer);
  54818. viewer.addEventListener('resize', this.resize.bind(this));
  54819. this.initEDL(viewer);
  54820. }
  54821. initEDL(viewer) {
  54822. if (this.edlMaterial != null || !Features.EXT_DEPTH.isSupported()) {
  54823. return;
  54824. }
  54825. this.edlMaterial = new ExtendEyeDomeLightingMaterial();
  54826. this.edlMaterial.depthTest = true;
  54827. this.edlMaterial.depthWrite = true;
  54828. this.edlMaterial.transparent = true;
  54829. var copyUniforms = UniformsUtils.clone(copyShader.uniforms);
  54830. var {
  54831. vs,
  54832. fs
  54833. } = Common.changeShaderToWebgl2(copyShader.vertexShader, copyShader.fragmentShader, 'ShaderMaterial');
  54834. this.recoverToScreenMat = new ShaderMaterial({
  54835. uniforms: copyUniforms,
  54836. vertexShader: vs,
  54837. fragmentShader: fs,
  54838. transparent: true,
  54839. defines: {
  54840. useDepth: true //开启后,其他物体才能被遮挡
  54841. }
  54842. });
  54843. /* let copyUniforms = THREE.UniformsUtils.clone( copyShader.uniforms );
  54844. this.copyMaterial = new THREE.ShaderMaterial( {
  54845. uniforms: copyUniforms,
  54846. vertexShader: copyShader.vertexShader,
  54847. fragmentShader: copyShader.fragmentShader,
  54848. //premultipliedAlpha: true,
  54849. transparent: true,
  54850. //blending: THREE.AdditiveBlending,
  54851. depthTest: false,
  54852. depthWrite: false
  54853. }); */
  54854. if (Potree.settings.useRTskybox != Potree.settings.useRTPoint) {
  54855. //如果两个只开了一个
  54856. viewer.images360.addEventListener('endChangeMode', () => {
  54857. this.resize({
  54858. viewport: viewer.mainViewport
  54859. });
  54860. });
  54861. }
  54862. //this.depthTexSampler = new DepthTexSampler(this);
  54863. }
  54864. resize(e) {
  54865. if (Features.EXT_DEPTH.isSupported()) {
  54866. var viewport = e.viewport;
  54867. var size = (Potree.settings.displayMode == 'showPanos' ? Potree.settings.useRTskybox : Potree.settings.useRTPoint) ? viewport.resolution2 : viewport.resolution; //若要渲染skybox,需要和设备一样精度的rt
  54868. this.getRtEDL(viewport).setSize(size.x, size.y); //理论上可以是任意尺寸,但会影响精度,且aspect最好和渲染的一致
  54869. }
  54870. }
  54871. clearTargets() {
  54872. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  54873. var viewer = this.viewer;
  54874. var {
  54875. renderer
  54876. } = viewer;
  54877. var oldTarget = renderer.getRenderTarget();
  54878. if (params.target) {
  54879. //add
  54880. renderer.setRenderTarget(params.target);
  54881. renderer.clear();
  54882. }
  54883. if (Features.EXT_DEPTH.isSupported()) {
  54884. if (params.rtEDL) {
  54885. renderer.setRenderTarget(params.rtEDL);
  54886. renderer.clear();
  54887. } else {
  54888. var rtEDL = this.getRtEDL(params.viewport);
  54889. if (rtEDL) {
  54890. renderer.setRenderTarget(rtEDL);
  54891. renderer.setClearAlpha(0);
  54892. renderer.clear(true, true, true);
  54893. }
  54894. }
  54895. }
  54896. //renderer.setRenderTarget( this.rtRegular );
  54897. //renderer.clear( true, true, false );
  54898. renderer.setRenderTarget(oldTarget);
  54899. }
  54900. getRtEDL(viewport) {
  54901. //根据不同viewport返回rtEDL的texture
  54902. if (!viewport) {
  54903. console.warn('getRtEDL没传viewport!!!! !!!!!!!!!!');
  54904. viewport = viewer.mainViewport;
  54905. }
  54906. var rtEDL = this.rtEDLs.get(viewport);
  54907. if (!rtEDL) {
  54908. if (Features.EXT_DEPTH.isSupported()) {
  54909. rtEDL = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, {
  54910. minFilter: NearestFilter,
  54911. magFilter: NearestFilter,
  54912. format: RGBAFormat,
  54913. type: FloatType,
  54914. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  54915. });
  54916. //注: 部分手机在resize时会崩溃,经检验去掉rtEDL的resize可以解决,所以更应该注释掉这个
  54917. this.rtEDLs.set(viewport, rtEDL);
  54918. }
  54919. }
  54920. //注:当pc窗口缩小,deviceRatio变小后,resolution2会小于resolution,然后遮挡会出现精度损失而有细微不准,是正常现象。
  54921. return rtEDL;
  54922. }
  54923. renderShadowMap(visiblePointClouds, camera, lights) {
  54924. var {
  54925. viewer
  54926. } = this;
  54927. var doShadows = lights.length > 0 && !lights[0].disableShadowUpdates;
  54928. if (doShadows) {
  54929. var light = lights[0];
  54930. this.shadowMap.setLight(light);
  54931. var originalAttributes = new Map();
  54932. for (var pointcloud of viewer.scene.pointclouds) {
  54933. // TODO IMPORTANT !!! check
  54934. originalAttributes.set(pointcloud, pointcloud.material.activeAttributeName);
  54935. pointcloud.material.disableEvents();
  54936. pointcloud.material.activeAttributeName = "depth";
  54937. //pointcloud.material.pointColorType = PointColorType.DEPTH;
  54938. }
  54939. this.shadowMap.render(viewer.scene.scenePointCloud, camera);
  54940. for (var _pointcloud of visiblePointClouds) {
  54941. var originalAttribute = originalAttributes.get(_pointcloud);
  54942. // TODO IMPORTANT !!! check
  54943. _pointcloud.material.activeAttributeName = originalAttribute;
  54944. _pointcloud.material.enableEvents();
  54945. }
  54946. viewer.shadowTestCam.updateMatrixWorld();
  54947. viewer.shadowTestCam.matrixWorldInverse.copy(viewer.shadowTestCam.matrixWorld).invert();
  54948. viewer.shadowTestCam.updateProjectionMatrix();
  54949. }
  54950. }
  54951. render() {
  54952. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  54953. var viewer = this.viewer;
  54954. var camera = params.camera ? params.camera : viewer.scene.getActiveCamera();
  54955. var rtEDL = (Potree.settings.pointEnableRT || Potree.settings.displayMode == 'showPanos' || viewer.useEDL) && Features.EXT_DEPTH.isSupported() && camera.type != "OrthographicCamera" && !params.dontRenderRtEDL && (params.rtEDL || this.getRtEDL(params.viewport)); // 平面相机不用depthTex直接打开depthTest?且不使用edl
  54956. var useEDL = viewer.useEDL && rtEDL && Potree.settings.displayMode != 'showPanos';
  54957. var target = params.target || null;
  54958. var resolution = rtEDL && Potree.settings.useRTPoint ? new Vector2(rtEDL.width, rtEDL.height) : params.target ? new Vector2(params.target.width, params.target.height) : params.viewport ? params.viewport.resolution2 : this.viewer.renderer.getSize(new Vector2()); //截图时需要用target的大小
  54959. viewer.renderer.setRenderTarget(target);
  54960. //viewer.dispatchEvent({type: "render.pass.begin",viewer: viewer});
  54961. var lights = [];
  54962. /* viewer.scene.scene.traverse(node => {
  54963. if(node.type === "SpotLight"){
  54964. lights.push(node);
  54965. }
  54966. }); */
  54967. //skybox 全景图
  54968. if (!params.magnifier) {
  54969. if (Potree.settings.displayMode == 'showPanos' || Potree.settings.testCube) {
  54970. Potree.Utils.setCameraLayers(camera, ['skybox']);
  54971. if (Potree.settings.displayMode == 'showPanos' && viewer.images360.currentPano.pointcloud.hasDepthTex && rtEDL) {
  54972. //渲染深度图
  54973. viewer.renderer.setRenderTarget(rtEDL); //将带有深度图的skybox画在rtEDL一下,这样就不需要绘制后边的点云了
  54974. viewer.renderer.render(viewer.scene.scene, camera);
  54975. viewer.renderer.setRenderTarget(target);
  54976. if (Potree.settings.useRTskybox) {
  54977. //直接使用rtEDL,但是会失去抗锯齿,不知在skybox上需要抗锯齿吗
  54978. this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture;
  54979. this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture;
  54980. Utils.screenPass.render(viewer.renderer, this.recoverToScreenMat, target);
  54981. } else {
  54982. viewer.renderer.render(viewer.scene.scene, camera);
  54983. }
  54984. } else {
  54985. viewer.renderer.render(viewer.scene.scene, camera);
  54986. }
  54987. if (Potree.settings.displayMode == 'showPanos') {
  54988. if (Potree.settings.fastTran && viewer.images360.fastTranMaskPass.enabled) {
  54989. viewer.images360.fastTranMaskPass.render();
  54990. }
  54991. return;
  54992. }
  54993. }
  54994. }
  54995. var visiblePointClouds2 = viewer.scene.pointclouds.filter(pc => Potree.Utils.getObjVisiByReason(pc, 'datasetSelection')); //需要绘制到rtEDL的
  54996. var showPointClouds = params.magnifier ? visiblePointClouds2.length > 0 : viewer.scene.pointclouds.some(e => e.visible); //是否有需要绘制到屏幕的
  54997. visiblePointClouds2.forEach(e => {
  54998. //为了绘制到depthTexture,先显示(展示全景图时隐藏了点云,所以需要显示下。且放大镜需要绘制点云)
  54999. e.oldVisi = e.visible;
  55000. e.visible = true;
  55001. });
  55002. Potree.Utils.setCameraLayers(camera, ['pointcloud']); //设置多少都会渲染出来,因为渲染里没有sort
  55003. //camera.layers.set(Potree.config.renderLayers.pointcloud);
  55004. //TODO adapt to multiple lights
  55005. //this.renderShadowMap(visiblePointClouds2, camera, lights); //???????
  55006. {
  55007. for (var pointcloud of visiblePointClouds2) {
  55008. var material = pointcloud.material;
  55009. var octreeSize = pointcloud.pcoGeometry.boundingBox.getSize(new Vector3()).x;
  55010. material.fov = MathUtils.degToRad(camera.fov);
  55011. material.resolution = resolution;
  55012. material.spacing = pointcloud.pcoGeometry.spacing; // * Math.max(this.scale.x, this.scale.y, this.scale.z);
  55013. material.near = camera.near;
  55014. material.far = camera.far;
  55015. material.uniforms.octreeSize.value = octreeSize;
  55016. if (useEDL) {
  55017. material.useEDL = true;
  55018. //material.fakeEDL = false; //add
  55019. } else {
  55020. material.useEDL = false;
  55021. //material.fakeEDL = true; //add 使也输出深度
  55022. }
  55023. }
  55024. if (rtEDL) {
  55025. //借用rtEDL存储深度信息
  55026. viewer.renderer.setRenderTarget(rtEDL);
  55027. if (visiblePointClouds2.length > 0) {
  55028. //渲染scenePointCloud到rtEDL
  55029. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, rtEDL, {
  55030. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  55031. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1),
  55032. transparent: true,
  55033. //如果点云透明需要透明
  55034. notAdditiveBlending: Potree.settings.notAdditiveBlending
  55035. });
  55036. }
  55037. if (Potree.settings.intersectOnObjs) {
  55038. // model也要渲染到rtEDL
  55039. Potree.Utils.setCameraLayers(camera, ['model', 'light']);
  55040. viewer.objs.traverse(e => {
  55041. if (e.material) e._OlddepthWrite = e.material.depthWrite, e.material.depthWrite = true;
  55042. }); //否则半透明的mesh无法遮住测量线
  55043. viewer.renderer.render(viewer.scene.scene, camera);
  55044. viewer.objs.traverse(e => {
  55045. if (e.material) e.material.depthWrite = e._OlddepthWrite;
  55046. });
  55047. //缺点:半透明的model 就算完全透明, 也会遮住测量线
  55048. }
  55049. }
  55050. }
  55051. //渲染到rtEDL完毕
  55052. viewer.dispatchEvent({
  55053. type: "render.pass.scene",
  55054. viewer: viewer
  55055. });
  55056. viewer.renderer.setRenderTarget(target);
  55057. if (!params.magnifier) visiblePointClouds2.forEach(e => {
  55058. //放大镜显示点云
  55059. e.visible = e.oldVisi;
  55060. });
  55061. if (showPointClouds) {
  55062. //绘制点云到画布
  55063. if (useEDL) {
  55064. //设置edlMaterial //Features.EXT_DEPTH不支持的话不会到这一块
  55065. var uniforms = this.edlMaterial.uniforms;
  55066. uniforms.resolution.value.copy(resolution);
  55067. uniforms.edlStrength.value = viewer.edlStrength;
  55068. uniforms.radius.value = viewer.edlRadius;
  55069. uniforms.useEDL.value = 1; //add
  55070. var proj = camera.projectionMatrix;
  55071. var projArray = new Float32Array(16);
  55072. projArray.set(proj.elements);
  55073. uniforms.uProj.value = projArray;
  55074. uniforms.uEDLColor.value = rtEDL.texture;
  55075. uniforms.opacity.value = viewer.edlOpacity; // HACK
  55076. Utils.screenPass.render(viewer.renderer, this.edlMaterial, target); //相当于一个描边后期特效。 缺点: 因为target上的没有抗锯齿,所以点云在晃动镜头时会不稳定地闪烁1px位置。优点:比不打开edl少绘制一次点云,更流畅了?!
  55077. } else if (Potree.settings.useRTPoint && rtEDL) {
  55078. this.recoverToScreenMat.uniforms.tDiffuse.value = rtEDL.texture;
  55079. if (this.recoverToScreenMat.defines.useDepth) {
  55080. this.recoverToScreenMat.uniforms.depthTex.value = rtEDL.depthTexture;
  55081. }
  55082. Utils.screenPass.render(viewer.renderer, this.recoverToScreenMat, target /* , Potree.settings.useFxaa && viewer.composer2 */);
  55083. params.drawedModelOnRT = Potree.settings.intersectOnObjs;
  55084. } else {
  55085. //渲染点云 (直接用rtEDL上的会失去抗锯齿, 导致频闪、密集时出现条纹, 自己写抗锯齿也要渲染好几次。另外透明度也要处理下)
  55086. var prop = {
  55087. shadowMaps: lights.length > 0 ? [this.shadowMap] : null,
  55088. clipSpheres: viewer.scene.volumes.filter(v => v instanceof SphereVolume$1),
  55089. notAdditiveBlending: Potree.settings.notAdditiveBlending //add 否则透明的点云会挡住后面的模型。 加上这句后竟然透明不会叠加了!
  55090. };
  55091. viewer.pRenderer.render(viewer.scene.scenePointCloud, camera, null, prop);
  55092. }
  55093. }
  55094. visiblePointClouds2.forEach(e => {
  55095. e.visible = e.oldVisi;
  55096. });
  55097. //viewer.dispatchEvent({type: "render.pass.end",viewer: viewer});
  55098. }
  55099. /*
  55100. 渲染顺序:
  55101. 底层:背景 -> skybox(也可中间)
  55102. 中间层(含有深度信息):1 点云、marker等mesh,
  55103. 2 测量线(现在被做成借用depthTex
  55104. 顶层:maginifier
  55105. magnifier的贴图渲染不需要顶层、中间层只需要点云。
  55106. */
  55107. }
  55108. class NavigationCube extends Object3D {
  55109. constructor(viewer) {
  55110. super();
  55111. this.viewer = viewer;
  55112. var createPlaneMaterial = img => {
  55113. var material = new MeshBasicMaterial({
  55114. depthTest: true,
  55115. depthWrite: true,
  55116. side: DoubleSide
  55117. });
  55118. new TextureLoader().load(exports.resourcePath + '/textures/navigation/' + img, function (texture) {
  55119. texture.anisotropy = viewer.renderer.capabilities.getMaxAnisotropy();
  55120. material.map = texture;
  55121. material.needsUpdate = true;
  55122. });
  55123. return material;
  55124. };
  55125. var planeGeometry = new PlaneGeometry(1, 1);
  55126. this.front = new Mesh(planeGeometry, createPlaneMaterial('F.png'));
  55127. this.front.position.y = -0.5;
  55128. this.front.rotation.x = Math.PI / 2.0;
  55129. this.front.updateMatrixWorld();
  55130. this.front.name = "F";
  55131. this.add(this.front);
  55132. this.back = new Mesh(planeGeometry, createPlaneMaterial('B.png'));
  55133. this.back.position.y = 0.5;
  55134. this.back.rotation.x = Math.PI / 2.0;
  55135. this.back.updateMatrixWorld();
  55136. this.back.name = "B";
  55137. this.add(this.back);
  55138. this.left = new Mesh(planeGeometry, createPlaneMaterial('L.png'));
  55139. this.left.position.x = -0.5;
  55140. this.left.rotation.y = Math.PI / 2.0;
  55141. this.left.updateMatrixWorld();
  55142. this.left.name = "L";
  55143. this.add(this.left);
  55144. this.right = new Mesh(planeGeometry, createPlaneMaterial('R.png'));
  55145. this.right.position.x = 0.5;
  55146. this.right.rotation.y = Math.PI / 2.0;
  55147. this.right.updateMatrixWorld();
  55148. this.right.name = "R";
  55149. this.add(this.right);
  55150. this.bottom = new Mesh(planeGeometry, createPlaneMaterial('D.png'));
  55151. this.bottom.position.z = -0.5;
  55152. this.bottom.updateMatrixWorld();
  55153. this.bottom.name = "D";
  55154. this.add(this.bottom);
  55155. this.top = new Mesh(planeGeometry, createPlaneMaterial('U.png'));
  55156. this.top.position.z = 0.5;
  55157. this.top.updateMatrixWorld();
  55158. this.top.name = "U";
  55159. this.add(this.top);
  55160. this.width = 150; // in px
  55161. this.camera = new OrthographicCamera(-1, 1, 1, -1, -1, 1);
  55162. this.camera.position.copy(new Vector3(0, 0, 0));
  55163. this.camera.lookAt(new Vector3(0, 1, 0));
  55164. this.camera.updateMatrixWorld();
  55165. this.camera.rotation.order = "ZXY";
  55166. var onMouseDown = event => {
  55167. if (!this.visible) {
  55168. return;
  55169. }
  55170. this.pickedFace = null;
  55171. var mouse = new Vector2();
  55172. mouse.x = event.clientX - (window.innerWidth - this.width);
  55173. mouse.y = event.clientY;
  55174. if (mouse.x < 0 || mouse.y > this.width) return;
  55175. mouse.x = mouse.x / this.width * 2 - 1;
  55176. mouse.y = -(mouse.y / this.width) * 2 + 1;
  55177. var raycaster = new Raycaster();
  55178. raycaster.setFromCamera(mouse, this.camera);
  55179. raycaster.ray.origin.sub(this.camera.getWorldDirection(new Vector3()));
  55180. var intersects = raycaster.intersectObjects(this.children);
  55181. var minDistance = 1000;
  55182. for (var i = 0; i < intersects.length; i++) {
  55183. if (intersects[i].distance < minDistance) {
  55184. this.pickedFace = intersects[i].object.name;
  55185. minDistance = intersects[i].distance;
  55186. }
  55187. }
  55188. if (this.pickedFace) {
  55189. this.viewer.setView(this.pickedFace);
  55190. }
  55191. };
  55192. this.viewer.renderer.domElement.addEventListener('mousedown', onMouseDown, false);
  55193. }
  55194. update(rotation) {
  55195. this.camera.rotation.copy(rotation);
  55196. this.visible && this.camera.updateMatrixWorld();
  55197. }
  55198. }
  55199. /**
  55200. *
  55201. * @author sigeom sa / http://sigeom.ch
  55202. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  55203. * @author Markus Schütz / http://potree.org
  55204. *
  55205. */
  55206. class GeoJSONExporter {
  55207. static measurementToFeatures(measurement) {
  55208. var coords = measurement.points.map(e => e.position.toArray());
  55209. var features = [];
  55210. if (coords.length === 1) {
  55211. var feature = {
  55212. type: 'Feature',
  55213. geometry: {
  55214. type: 'Point',
  55215. coordinates: coords[0]
  55216. },
  55217. properties: {
  55218. name: measurement.name
  55219. }
  55220. };
  55221. features.push(feature);
  55222. } else if (coords.length > 1 && !measurement.closed) {
  55223. var object = {
  55224. 'type': 'Feature',
  55225. 'geometry': {
  55226. 'type': 'LineString',
  55227. 'coordinates': coords
  55228. },
  55229. 'properties': {
  55230. name: measurement.name
  55231. }
  55232. };
  55233. features.push(object);
  55234. } else if (coords.length > 1 && measurement.closed) {
  55235. var _object = {
  55236. 'type': 'Feature',
  55237. 'geometry': {
  55238. 'type': 'Polygon',
  55239. 'coordinates': [[...coords, coords[0]]]
  55240. },
  55241. 'properties': {
  55242. name: measurement.name
  55243. }
  55244. };
  55245. features.push(_object);
  55246. }
  55247. if (measurement.showDistances) {
  55248. measurement.edgeLabels.forEach(label => {
  55249. var labelPoint = {
  55250. type: 'Feature',
  55251. geometry: {
  55252. type: 'Point',
  55253. coordinates: label.position.toArray()
  55254. },
  55255. properties: {
  55256. distance: label.text
  55257. }
  55258. };
  55259. features.push(labelPoint);
  55260. });
  55261. }
  55262. if (measurement.showArea) {
  55263. var point = measurement.areaLabel.position;
  55264. var labelArea = {
  55265. type: 'Feature',
  55266. geometry: {
  55267. type: 'Point',
  55268. coordinates: point.toArray()
  55269. },
  55270. properties: {
  55271. area: measurement.areaLabel.text
  55272. }
  55273. };
  55274. features.push(labelArea);
  55275. }
  55276. return features;
  55277. }
  55278. static toString(measurements) {
  55279. if (!(measurements instanceof Array)) {
  55280. measurements = [measurements];
  55281. }
  55282. measurements = measurements.filter(m => m instanceof Measure);
  55283. var features = [];
  55284. for (var measure of measurements) {
  55285. var f = GeoJSONExporter.measurementToFeatures(measure);
  55286. features = features.concat(f);
  55287. }
  55288. var geojson = {
  55289. 'type': 'FeatureCollection',
  55290. 'features': features
  55291. };
  55292. return JSON.stringify(geojson, null, '\t');
  55293. }
  55294. }
  55295. /**
  55296. *
  55297. * @author sigeom sa / http://sigeom.ch
  55298. * @author Ioda-Net Sàrl / https://www.ioda-net.ch/
  55299. * @author Markus Schuetz / http://potree.org
  55300. *
  55301. */
  55302. class DXFExporter {
  55303. static measurementPointSection(measurement) {
  55304. var position = measurement.points[0].position;
  55305. if (!position) {
  55306. return '';
  55307. }
  55308. var dxfSection = "0\nCIRCLE\n8\nlayer_point\n10\n".concat(position.x, "\n20\n").concat(position.y, "\n30\n").concat(position.z, "\n40\n1.0\n");
  55309. return dxfSection;
  55310. }
  55311. static measurementPolylineSection(measurement) {
  55312. // bit code for polygons/polylines:
  55313. // https://www.autodesk.com/techpubs/autocad/acad2000/dxf/polyline_dxf_06.htm
  55314. var geomCode = 8;
  55315. if (measurement.closed) {
  55316. geomCode += 1;
  55317. }
  55318. var dxfSection = "0\nPOLYLINE\n8\nlayer_polyline\n62\n1\n66\n1\n10\n0.0\n20\n0.0\n30\n0.0\n70\n".concat(geomCode, "\n");
  55319. var xMax = 0.0;
  55320. var yMax = 0.0;
  55321. var zMax = 0.0;
  55322. for (var point of measurement.points) {
  55323. point = point.position;
  55324. xMax = Math.max(xMax, point.x);
  55325. yMax = Math.max(yMax, point.y);
  55326. zMax = Math.max(zMax, point.z);
  55327. dxfSection += "0\nVERTEX\n8\n0\n10\n".concat(point.x, "\n20\n").concat(point.y, "\n30\n").concat(point.z, "\n70\n32\n");
  55328. }
  55329. dxfSection += "0\nSEQEND\n";
  55330. return dxfSection;
  55331. }
  55332. static measurementSection(measurement) {
  55333. // if(measurement.points.length <= 1){
  55334. // return "";
  55335. // }
  55336. if (measurement.points.length === 0) {
  55337. return '';
  55338. } else if (measurement.points.length === 1) {
  55339. return DXFExporter.measurementPointSection(measurement);
  55340. } else if (measurement.points.length >= 2) {
  55341. return DXFExporter.measurementPolylineSection(measurement);
  55342. }
  55343. }
  55344. static toString(measurements) {
  55345. if (!(measurements instanceof Array)) {
  55346. measurements = [measurements];
  55347. }
  55348. measurements = measurements.filter(m => m instanceof Measure);
  55349. var points = measurements.filter(m => m instanceof Measure).map(m => m.points).reduce((a, v) => a.concat(v)).map(p => p.position);
  55350. var min = new Vector3(Infinity, Infinity, Infinity);
  55351. var max = new Vector3(-Infinity, -Infinity, -Infinity);
  55352. for (var point of points) {
  55353. min.min(point);
  55354. max.max(point);
  55355. }
  55356. var dxfHeader = "999\nDXF created from potree\n0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1006\n9\n$INSBASE\n10\n0.0\n20\n0.0\n30\n0.0\n9\n$EXTMIN\n10\n".concat(min.x, "\n20\n").concat(min.y, "\n30\n").concat(min.z, "\n9\n$EXTMAX\n10\n").concat(max.x, "\n20\n").concat(max.y, "\n30\n").concat(max.z, "\n0\nENDSEC\n");
  55357. var dxfBody = "0\nSECTION\n2\nENTITIES\n";
  55358. for (var measurement of measurements) {
  55359. dxfBody += DXFExporter.measurementSection(measurement);
  55360. }
  55361. dxfBody += "0\nENDSEC\n";
  55362. var dxf = dxfHeader + dxfBody + '0\nEOF';
  55363. return dxf;
  55364. }
  55365. }
  55366. class HandleSvg extends EventDispatcher {
  55367. constructor(position, color) {
  55368. super();
  55369. this.position = position;
  55370. this.color = '#' + new Color(color).getHexString();
  55371. this.svg = this.create();
  55372. this.visible_ = true;
  55373. var update = () => {
  55374. this.update();
  55375. };
  55376. viewer.addEventListener("camera_changed", update);
  55377. this.addEventListener('dispose', () => {
  55378. viewer.removeEventListener("camera_changed", update);
  55379. });
  55380. }
  55381. create() {
  55382. var svgns = "http://www.w3.org/2000/svg";
  55383. var svg = document.createElementNS(svgns, "svg");
  55384. svg.setAttribute("width", "2em");
  55385. svg.setAttribute("height", "2em");
  55386. svg.setAttribute("position", "absolute");
  55387. svg.style.left = "50px";
  55388. svg.style.top = "50px";
  55389. svg.style.position = "absolute";
  55390. svg.style.zIndex = "10000";
  55391. svg.style.cursor = 'grab';
  55392. svg.style.transform = 'translate(-50%,-50%)';
  55393. var circle = document.createElementNS(svgns, 'circle');
  55394. circle.setAttributeNS(null, 'cx', "1em");
  55395. circle.setAttributeNS(null, 'cy', "1em");
  55396. circle.setAttributeNS(null, 'r', "0.5em");
  55397. circle.setAttributeNS(null, 'style', 'fill: ' + this.color + '; stroke: black; stroke-width: 0.2em;');
  55398. svg.appendChild(circle);
  55399. var element = viewer.renderer.domElement.parentElement;
  55400. element.appendChild(svg);
  55401. var startDrag = evt => {
  55402. /* if(evt.button === THREE.MOUSE.RIGHT){
  55403. return
  55404. } */
  55405. this.selectedElement = svg;
  55406. document.addEventListener("mousemove", drag);
  55407. };
  55408. var endDrag = evt => {
  55409. this.selectedElement = null;
  55410. document.removeEventListener("mousemove", drag);
  55411. };
  55412. var drag = evt => {
  55413. if (this.selectedElement) {
  55414. evt.preventDefault();
  55415. var rect = viewer.renderer.domElement.getBoundingClientRect();
  55416. var x = evt.clientX - rect.x;
  55417. var y = evt.clientY - rect.y;
  55418. var {
  55419. width,
  55420. height
  55421. } = viewer.renderer.getSize(new Vector2());
  55422. var camera = viewer.scene.getActiveCamera();
  55423. var projected = this.position.clone().project(camera);
  55424. projected.x = (x / width - 0.5) / 0.5;
  55425. projected.y = (-(y - height) / height - 0.5) / 0.5;
  55426. var unprojected = projected.clone().unproject(camera);
  55427. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  55428. this.update();
  55429. this.dispatchEvent({
  55430. type: 'dragged',
  55431. position: this.position
  55432. });
  55433. }
  55434. };
  55435. svg.addEventListener('mousedown', startDrag);
  55436. svg.addEventListener('mouseup', endDrag);
  55437. svg.style.display = this.visible ? "" : "none";
  55438. this.addEventListener('dispose', () => {
  55439. svg.removeEventListener('mousedown', startDrag);
  55440. svg.removeEventListener('mouseup', endDrag);
  55441. });
  55442. return svg;
  55443. }
  55444. set visible(v) {
  55445. this.visible_ = v;
  55446. if (v) {
  55447. this.update();
  55448. } else {
  55449. this.svg.style.display = "none";
  55450. }
  55451. }
  55452. get visible() {
  55453. return this.visible_;
  55454. }
  55455. update() {
  55456. if (!this.visible) return;
  55457. var camera = viewer.scene.getActiveCamera();
  55458. var p = Potree.Utils.getPos2d(this.position, viewer.mainViewport, viewer.renderArea);
  55459. if (!p.trueSide) {
  55460. return this.svg.style.display = 'none';
  55461. }
  55462. this.svg.style.left = p.posInViewport.x;
  55463. this.svg.style.top = p.posInViewport.y;
  55464. this.svg.style.display = '';
  55465. }
  55466. dispose() {
  55467. this.svg.remove();
  55468. this.dispatchEvent('dispose');
  55469. }
  55470. }
  55471. /*
  55472. 两种拖拽方式:
  55473. 1 只依附在点云上
  55474. 2 平行于镜头view移动 */
  55475. var geo$1 = new PlaneBufferGeometry(1, 1);
  55476. class HandleSprite extends Sprite$2 {
  55477. constructor(position) {
  55478. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  55479. options.sizeInfo = {
  55480. width2d: 60
  55481. };
  55482. super(options);
  55483. this.position.copy(position);
  55484. this.dragStyle = options.dragStyle || 'default'; //'default'||'onPointCloud'
  55485. this.bindEvent();
  55486. }
  55487. bindEvent() {
  55488. var projectedStart, pointerStart;
  55489. var drag = e => {
  55490. /* if(e.hoverViewport != e.drag.dragViewport){//不能使用e.dragViewport,要使用drag中的,因为drag中存储的要一直继承下来,不因mouseup了而改变。
  55491. viewer.dispatchEvent({
  55492. type : "CursorChange", action : "add", name:"polygon_AtWrongPlace"
  55493. })
  55494. return
  55495. } */
  55496. var camera = viewer.scene.getActiveCamera();
  55497. if (projectedStart) {
  55498. var move2d = new Vector2().subVectors(e.pointer, pointerStart);
  55499. var projectNow = projectedStart.clone();
  55500. projectNow.x += move2d.x;
  55501. projectNow.y += move2d.y;
  55502. var unprojected = projectNow.clone().unproject(camera);
  55503. this.position.set(unprojected.x, unprojected.y, unprojected.z);
  55504. } else {
  55505. projectedStart = this.position.clone().project(camera);
  55506. pointerStart = e.pointer.clone();
  55507. }
  55508. this.update();
  55509. this.dispatchEvent({
  55510. type: 'dragged',
  55511. position: this.position
  55512. });
  55513. };
  55514. var drop = e => {
  55515. projectedStart = null, pointerStart = null;
  55516. };
  55517. var mouseover = e => {
  55518. viewer.dispatchEvent({
  55519. type: "CursorChange",
  55520. action: "add",
  55521. name: "markerMove"
  55522. });
  55523. };
  55524. var mouseleave = e => {
  55525. viewer.dispatchEvent({
  55526. type: "CursorChange",
  55527. action: "remove",
  55528. name: "markerMove"
  55529. });
  55530. };
  55531. this.addEventListener('drag', drag);
  55532. this.addEventListener('drop', drop);
  55533. this.addEventListener('mouseover', mouseover);
  55534. this.addEventListener('mouseleave', mouseleave);
  55535. }
  55536. }
  55537. var sphere = new Mesh(new SphereBufferGeometry(0.08, 0.08, 3, 2), new MeshBasicMaterial({
  55538. color: '#f88'
  55539. }));
  55540. class CurveCtrl extends Object3D {
  55541. constructor(points, lineMat, color, name) {
  55542. var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
  55543. super();
  55544. this.curve = new CatmullRomCurve3(points, false, "centripetal" /* , tension */);
  55545. this.name = name || 'curveNode';
  55546. this.handleMat = options.handleMat;
  55547. this.lineMat = lineMat;
  55548. this.createPath();
  55549. this.color = color;
  55550. this.handles = [];
  55551. this.wholeLength = 0;
  55552. this.viewports = options.viewports || [viewer.mainViewport]; //for HandleSprite
  55553. for (var i = 0, j = this.points.length; i < j; i++) {
  55554. this.handles.push(this.createHandle(this.points[i]));
  55555. }
  55556. this.visible_ = true;
  55557. if (Potree.settings.isTest) {
  55558. this.spheres = new Object3D();
  55559. /* let i = Count+1;
  55560. while(i>0){
  55561. this.spheres.add(sphere.clone());
  55562. i--;
  55563. } */
  55564. this.add(this.spheres);
  55565. }
  55566. this.updatePath();
  55567. }
  55568. addPoint(position, index, ifUpdate) {
  55569. var length = this.points.length;
  55570. if (index == void 0) {
  55571. index = length;
  55572. }
  55573. var handle = this.createHandle(position);
  55574. this.handles = [...this.handles.slice(0, index), handle, ...this.handles.slice(index, length)];
  55575. this.points = [...this.points.slice(0, index), position, ...this.points.slice(index, length)];
  55576. ifUpdate && (this.updatePath(), this.updateHandle(index));
  55577. }
  55578. removePoint(index) {
  55579. var handle = this.handles[index];
  55580. handle.dispose();
  55581. this.handles.splice(index, 1);
  55582. this.points.splice(index, 1);
  55583. this.updatePath();
  55584. }
  55585. createPath() {
  55586. var line = LineDraw.createFatLine([], this.lineMat);
  55587. this.line = line;
  55588. this.add(line);
  55589. }
  55590. updatePath() {
  55591. this.curve.needsUpdate = true; //如果不更新,得到的点不均匀,开头点少。
  55592. var points,
  55593. length = this.points.length;
  55594. this.wholeLength = this.points.reduce((total, currentValue, currentIndex, arr) => {
  55595. //所有端点的距离总和
  55596. if (currentIndex == 0) return 0;
  55597. return total + currentValue.distanceTo(arr[currentIndex - 1]);
  55598. }, 0);
  55599. if (length > 1) {
  55600. var count = MathUtils.clamp(Math.ceil(this.wholeLength * 5), 30, 500);
  55601. points = this.curve.getSpacedPoints(count);
  55602. if (this.needsPercent) {
  55603. //获取每个节点在整条中的百分比,便于定位(但不精确)
  55604. this.pointsPercent = [0];
  55605. var sums = [0];
  55606. var sum = 0,
  55607. last = points[0];
  55608. for (var i = 1; i < length; i++) {
  55609. var point = this.points[i];
  55610. sum += point.distanceTo(last); //参考getLengths函数,根据长度得到百分比
  55611. last = point;
  55612. sums.push(sum);
  55613. }
  55614. for (var _i = 1; _i < length; _i++) {
  55615. this.pointsPercent.push(sum == 0 ? _i / length : sums[_i] / sum);
  55616. }
  55617. }
  55618. if (Potree.settings.isTest) {
  55619. this.spheres.children.forEach(e => e.visible = false);
  55620. points.forEach((e, i) => {
  55621. var sphere1 = this.spheres.children[i];
  55622. if (!sphere1) {
  55623. sphere1 = sphere.clone();
  55624. this.spheres.add(sphere1);
  55625. }
  55626. sphere1.position.copy(e);
  55627. sphere1.visible = true;
  55628. });
  55629. }
  55630. } else {
  55631. points = [];
  55632. }
  55633. LineDraw.updateLine(this.line, points);
  55634. this.dispatchEvent('updatePath');
  55635. }
  55636. createHandle(position) {
  55637. if (this.handleMat) {
  55638. var handle = new HandleSprite(position, {
  55639. mat: this.handleMat,
  55640. viewports: this.viewports
  55641. });
  55642. this.add(handle);
  55643. } else {
  55644. var handle = new HandleSvg(position, this.color);
  55645. }
  55646. handle.visible = this.visible;
  55647. handle.addEventListener('dragged', e => {
  55648. var index = this.handles.indexOf(handle);
  55649. this.points[index].copy(e.position);
  55650. this.updatePath();
  55651. this.dispatchEvent({
  55652. type: 'dragCurvePoint',
  55653. index
  55654. });
  55655. });
  55656. return handle;
  55657. }
  55658. updateHandle(index) {
  55659. if (!this.visible) return;
  55660. this.handles[index].update();
  55661. }
  55662. updateHandles() {
  55663. this.handles.forEach((handle, index) => {
  55664. this.updateHandle(index);
  55665. });
  55666. }
  55667. update() {
  55668. this.updateHandles();
  55669. this.updatePath();
  55670. }
  55671. set visible(v) {
  55672. if (v != this.visible_) {
  55673. this.visible_ = v;
  55674. this.visible = v;
  55675. if (this.handles) {
  55676. this.handles.forEach(e => e.visible = v);
  55677. if (v) this.updateHandles(); //因为不可见时没更新位置
  55678. }
  55679. }
  55680. }
  55681. get visible() {
  55682. return this.visible_;
  55683. }
  55684. /* set visible(v){
  55685. this.handles.forEach(e=>e.svg.style.display = v ? "" : "none" )
  55686. if(v) this.updateHandles() //因为不可见时没更新位置
  55687. } */
  55688. get points() {
  55689. return this.curve.points;
  55690. }
  55691. set points(points) {
  55692. this.curve.points = points;
  55693. }
  55694. getPointAt(t) {
  55695. return this.curve.getPointAt(t);
  55696. }
  55697. getSpacedPoints(t) {
  55698. return this.curve.getSpacedPoints(t);
  55699. }
  55700. dispose() {
  55701. this.parent && this.parent.remove(this);
  55702. this.handles.forEach(e => e.dispose());
  55703. this.line.geometry && this.line.geometry.dispose();
  55704. }
  55705. }
  55706. var colors$1 = {
  55707. position: 'red',
  55708. target: 'blue'
  55709. };
  55710. var lineMats$1;
  55711. var getLineMat = function getLineMat(name) {
  55712. if (!lineMats$1) {
  55713. lineMats$1 = {
  55714. position: LineDraw.createFatLineMat({
  55715. color: colors$1.position,
  55716. lineWidth: 3
  55717. }),
  55718. target: LineDraw.createFatLineMat({
  55719. color: colors$1.target,
  55720. lineWidth: 3
  55721. }),
  55722. frustum: LineDraw.createFatLineMat({
  55723. color: colors$1.position,
  55724. lineWidth: 2
  55725. }),
  55726. aimAtTarget: new LineBasicMaterial({
  55727. color: colors$1.target,
  55728. depthTest: false
  55729. })
  55730. };
  55731. }
  55732. return lineMats$1[name];
  55733. };
  55734. class CameraAnimation$1 extends EventDispatcher {
  55735. constructor(viewer) {
  55736. super();
  55737. this.viewer = viewer;
  55738. this.selectedElement = null;
  55739. //this.controlPoints = [];
  55740. this.uuid = MathUtils.generateUUID();
  55741. this.node = new Object3D();
  55742. this.node.name = "camera animation";
  55743. this.viewer.scene.scene.add(this.node);
  55744. this.frustum = this.createFrustum();
  55745. this.node.add(this.frustum);
  55746. this.name = "Camera Animation";
  55747. // "centripetal", "chordal", "catmullrom"
  55748. this.curveType = "centripetal";
  55749. this.visible = true;
  55750. this.targets = [];
  55751. this.createPath();
  55752. this.duration = 5;
  55753. this.percent = 0;
  55754. this.currentIndex = 0;
  55755. this.durations = [];
  55756. this.quaternions = [];
  55757. if (!Potree.settings.isTest && Potree.settings.isOfficial) {
  55758. this.setVisible(false);
  55759. }
  55760. this.addEventListener('dispose', () => {
  55761. this.dispose();
  55762. });
  55763. this.targetLines = new Object3D();
  55764. this.node.add(this.targetLines);
  55765. }
  55766. static defaultFromView(viewer) {
  55767. var animation = new CameraAnimation$1(viewer);
  55768. var camera = viewer.scene.getActiveCamera();
  55769. var target = viewer.scene.view.getPivot();
  55770. var cpCenter = new Vector3(0.3 * camera.position.x + 0.7 * target.x, 0.3 * camera.position.y + 0.7 * target.y, 0.3 * camera.position.z + 0.7 * target.z);
  55771. var targetCenter = new Vector3(0.05 * camera.position.x + 0.95 * target.x, 0.05 * camera.position.y + 0.95 * target.y, 0.05 * camera.position.z + 0.95 * target.z);
  55772. var r = 2; //camera.position.distanceTo(target) * 0.3;
  55773. //const dir = target.clone().sub(camera.position).normalize();
  55774. var angle = Utils.computeAzimuth(camera.position, target);
  55775. var n = 5;
  55776. for (var i = 0; i < n; i++) {
  55777. var u = 1.5 * Math.PI * (i / n) + angle;
  55778. var dx = r * Math.cos(u);
  55779. var dy = r * Math.sin(u);
  55780. var cpPos = new Vector3(cpCenter.x + dx, cpCenter.y + dy, cpCenter.z);
  55781. var targetPos = new Vector3(targetCenter.x + dx * 0.1, targetCenter.y + dy * 0.1, targetCenter.z);
  55782. animation.createControlPoint(null, {
  55783. position: cpPos,
  55784. target: targetPos
  55785. });
  55786. }
  55787. animation.changeCallback();
  55788. return animation;
  55789. }
  55790. createControlPoint(index, posInfo) {
  55791. var length = this.posCurve.points.length;
  55792. var position = new Vector3();
  55793. var target = new Vector3();
  55794. if (index == void 0) {
  55795. index = length;
  55796. }
  55797. if (!posInfo) {
  55798. if (length >= 2 && index === 0) {
  55799. var dir = new Vector3().subVectors(this.posCurve.points[0], this.posCurve.points[1]);
  55800. position.copy(this.posCurve.points[0]).add(dir);
  55801. var tDir = new Vector3().subVectors(this.targets[0].position, this.targets[1].position);
  55802. target.copy(this.targets[0].position).add(dir);
  55803. } else if (length >= 2 && index === length) {
  55804. var _dir = new Vector3().subVectors(this.posCurve.points[length - 1], this.posCurve.points[length - 2]);
  55805. position.copy(this.posCurve.points[length - 2]).add(_dir);
  55806. var _tDir = new Vector3().subVectors(this.targets[length - 1].position, this.targets[length - 2].position);
  55807. target.copy(this.targets[length - 2].position).add(_dir);
  55808. } else if (length >= 2) {
  55809. position.copy(this.posCurve.points[index - 1].clone().add(this.posCurve.points[index]).multiplyScalar(0.5));
  55810. target.copy(this.targets[index - 1].position.clone().add(this.targets[index].position).multiplyScalar(0.5));
  55811. }
  55812. } else {
  55813. position.copy(posInfo.position);
  55814. target.copy(posInfo.target);
  55815. }
  55816. this.posCurve.addPoint(position, index /* , true */);
  55817. //this.targetCurve.addPoint(target, index/* , true */)
  55818. var targetSvg = new HandleSvg(target, colors$1.target);
  55819. targetSvg.visible = this.visible;
  55820. this.targets = [...this.targets.slice(0, index), targetSvg, ...this.targets.slice(index, length)];
  55821. if (this.useDurSlice) {
  55822. //不使用全局的duration,而是分段的
  55823. this.durations = [...this.durations.slice(0, index), posInfo.duration, ...this.durations.slice(index, length)];
  55824. }
  55825. this.dispatchEvent({
  55826. type: "controlpoint_added",
  55827. index
  55828. });
  55829. {
  55830. var targetLine = LineDraw.createLine([position, target], {
  55831. mat: getLineMat('aimAtTarget')
  55832. });
  55833. this.targetLines.children = [...this.targetLines.children.slice(0, index), targetLine, ...this.targetLines.children.slice(index, length)];
  55834. this.targets[index].addEventListener('dragged', e => {
  55835. this.updatePathCallback();
  55836. this.dragPointCallback(e);
  55837. });
  55838. }
  55839. }
  55840. dragPointCallback(e) {
  55841. var index = e.index;
  55842. if (e.index == void 0) {
  55843. index = this.targets.indexOf(e.target);
  55844. }
  55845. LineDraw.moveLine(this.targetLines.children[index], [this.posCurve.points[index], this.targets[index].position]);
  55846. viewer.dispatchEvent('content_changed');
  55847. this.updateFrustum();
  55848. }
  55849. updatePathCallback() {
  55850. {
  55851. this.quaternions = [];
  55852. var length = this.posCurve.points.length;
  55853. for (var i = 0; i < length; i++) {
  55854. var quaternion = math.getQuaFromPosAim(this.posCurve.points[i], this.targets[i].position);
  55855. this.quaternions.push(quaternion);
  55856. }
  55857. }
  55858. this.reMapCurvePercent();
  55859. }
  55860. removeControlPoint(index) {
  55861. this.posCurve.removePoint(index);
  55862. //this.targetCurve.removePoint(index)
  55863. this.targets[index].dispose();
  55864. this.targets.splice(index, 1);
  55865. this.dispatchEvent({
  55866. type: "controlpoint_removed",
  55867. index
  55868. });
  55869. this.targetLines.remove(this.targetLines.children[index]);
  55870. if (this.useDurSlice) {
  55871. this.durations.splice(index, 1);
  55872. }
  55873. }
  55874. createPath() {
  55875. this.posCurve = new CurveCtrl([], getLineMat('position'), colors$1.position, 'posCurve');
  55876. //this.targetCurve = new CurveCtrl([], getLineMat('target'), colors.target, 'targetCurve', {noLine:true});
  55877. this.posCurve.needsPercent = true;
  55878. this.node.add(this.posCurve);
  55879. //this.node.add(this.targetCurve)
  55880. this.posCurve.addEventListener('dragCurvePoint', this.dragPointCallback.bind(this));
  55881. this.posCurve.addEventListener('updatePath', this.updatePathCallback.bind(this));
  55882. }
  55883. createFrustum() {
  55884. var f = 0.3;
  55885. var positions = [new Vector3(0, 0, 0), new Vector3(-f, -f, +1), new Vector3(0, 0, 0), new Vector3(f, -f, +1), new Vector3(0, 0, 0), new Vector3(f, f, +1), new Vector3(0, 0, 0), new Vector3(-f, f, +1), new Vector3(-f, -f, +1), new Vector3(f, -f, +1), new Vector3(f, -f, +1), new Vector3(f, f, +1), new Vector3(f, f, +1), new Vector3(-f, f, +1), new Vector3(-f, f, +1), new Vector3(-f, -f, +1)];
  55886. positions.forEach(e => e.z *= -1); //因为得到的rotation是camera的,作用在物体上要反向,所以这里反向一下
  55887. //geometry.computeBoundingSphere();//?
  55888. var line = LineDraw.createFatLine(positions, {
  55889. mat: getLineMat('frustum')
  55890. });
  55891. //line.scale.set(20, 20, 20);
  55892. line.visible = false;
  55893. return line;
  55894. }
  55895. reMapCurvePercent() {
  55896. //因在不同点在相同位置旋转,由于间隔仅和位置距离相关,导致时间间隔为0,采取重新调整间隔的策略。
  55897. var length = this.posCurve.points.length;
  55898. if (length < 2) {
  55899. return this.newPointsPercents = [];
  55900. }
  55901. var newPercents = [0];
  55902. if (this.useDurSlice) {
  55903. //已经设定好了每一段的duration的话
  55904. var sums = [0];
  55905. var sum = 0,
  55906. last;
  55907. for (var i = 0; i < length - 1; i++) {
  55908. //去掉最后一个duration,因为已到终点
  55909. var duration = this.durations[i];
  55910. sum += duration;
  55911. last = duration;
  55912. sums.push(sum);
  55913. }
  55914. for (var _i = 1; _i < length; _i++) {
  55915. newPercents.push(sum == 0 ? _i / length : sums[_i] / sum);
  55916. }
  55917. } else {
  55918. var maxSpaceDur = this.duration / length; //每两点之间修改间隔时间后,最大时间
  55919. var durPerRad = 0.8; //每弧度应该占用的时间
  55920. var minSpaceDur = Math.min(0.8, maxSpaceDur); //每两点之间修改间隔时间后,最小时间
  55921. var maxAngleSpaceDur = MathUtils.clamp(durPerRad * Math.PI, minSpaceDur, maxSpaceDur); // 最大可能差距是180度
  55922. var percents = this.posCurve.pointsPercent;
  55923. for (var _i2 = 1; _i2 < length; _i2++) {
  55924. var diff = (percents[_i2] - percents[_i2 - 1]) * this.duration; //间隔时间
  55925. var percent = void 0;
  55926. var curMin = minSpaceDur;
  55927. if (diff < maxAngleSpaceDur) {
  55928. //若小于最大旋转时间
  55929. var rad = this.quaternions[_i2].angleTo(this.quaternions[_i2 - 1]);
  55930. curMin = MathUtils.clamp(rad * durPerRad, minSpaceDur, maxSpaceDur);
  55931. }
  55932. diff = Math.max(diff, curMin);
  55933. percent = newPercents[_i2 - 1] + diff / this.duration; //得到新的percent
  55934. newPercents.push(percent);
  55935. }
  55936. var maxPercent = newPercents[length - 1]; //最后一个,若扩充过时间,就会>1
  55937. if (!math.closeTo(maxPercent, 1)) {
  55938. var scale = 1 / maxPercent; //需要压缩的比例 <1 这一步会让实际得到的间隔更小
  55939. newPercents = newPercents.map(e => e *= scale);
  55940. }
  55941. }
  55942. this.newPointsPercents = newPercents;
  55943. //console.log(newPercents)
  55944. }
  55945. at(originPercent, delta, transitionRatio) {
  55946. originPercent = MathUtils.clamp(originPercent, 0, 1);
  55947. //修改第一层:起始时间
  55948. var percent = originPercent;
  55949. /* const easePercent = 0.3; //缓动占比 //如果能在所有从静止到运动的中间加缓动就好了呀:lastPos * 0.9 + currentPos * 0.1 ?
  55950. if(originPercent < easePercent){
  55951. console.log('easeIn')
  55952. percent = easing.easeInSine(originPercent, 0, easePercent, easePercent) //currentTime, startY, wholeY, duration 选了一个衔接时接近斜率1的缓动函数
  55953. }else if(originPercent > 1-easePercent){
  55954. console.log('easeOut')
  55955. percent = easing.easeOutSine(originPercent-(1-easePercent), 1-easePercent, easePercent, easePercent)
  55956. } */
  55957. var quaternion;
  55958. if (percent < 1) {
  55959. //修改第二层:使用每个点的重定位的 newPointsPercents
  55960. this.currentIndex = this.newPointsPercents.findIndex(e => e > percent) - 1;
  55961. //假设每个节点的百分比是精确的,那么:
  55962. var curIndexPercent = this.newPointsPercents[this.currentIndex];
  55963. var nextIndexPercent = this.newPointsPercents[this.currentIndex + 1];
  55964. var progress = (percent - curIndexPercent) / (nextIndexPercent - curIndexPercent); //在这两个节点间的百分比
  55965. //投影到原本的 posCurve.pointsPercent上:
  55966. var curIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex];
  55967. var nextIndexOriPercent = this.posCurve.pointsPercent[this.currentIndex + 1];
  55968. percent = curIndexOriPercent + (nextIndexOriPercent - curIndexOriPercent) * progress;
  55969. var endQuaternion = this.quaternions[this.currentIndex + 1];
  55970. var startQuaternion = this.quaternions[this.currentIndex];
  55971. quaternion = new Quaternion().copy(startQuaternion);
  55972. lerp.quaternion(quaternion, endQuaternion)(progress);
  55973. } else {
  55974. this.currentIndex = this.posCurve.points.length - 1;
  55975. quaternion = math.getQuaFromPosAim(this.posCurve.points[this.currentIndex], this.targets[this.currentIndex].position);
  55976. }
  55977. var position = this.posCurve.getPointAt(percent); // 需要this.posCurve.points.length>1 否则报错
  55978. //console.log(this.currentIndex, originPercent)
  55979. //缓动:
  55980. var aimQua, aimPos;
  55981. if (delta != void 0) {
  55982. if (Potree.settings.tourTestCameraMove) {
  55983. aimQua = this.frustum.quaternion.clone();
  55984. aimPos = this.frustum.position.clone();
  55985. } else {
  55986. var camera = viewer.scene.getActiveCamera();
  55987. aimQua = camera.quaternion.clone();
  55988. aimPos = camera.position.clone();
  55989. }
  55990. transitionRatio = transitionRatio || 1 / Potree.settings.cameraAniSmoothRatio; //渐变系数,越小缓动程度越高,越平滑
  55991. transitionRatio *= delta * 60; //假设标准帧率为60fps,当帧率低时(delta大时)要降低缓动
  55992. //console.log(transitionRatio, delta) //画面ui变化会使delta变大
  55993. transitionRatio = MathUtils.clamp(transitionRatio, 0, 1);
  55994. lerp.quaternion(aimQua, quaternion)(transitionRatio); //每次只改变一点点
  55995. lerp.vector(aimPos, position)(transitionRatio);
  55996. } else {
  55997. aimQua = quaternion;
  55998. aimPos = position;
  55999. }
  56000. var rotation = new Euler().setFromQuaternion(aimQua);
  56001. var frame = {
  56002. position: aimPos,
  56003. rotation
  56004. };
  56005. return frame;
  56006. }
  56007. set(percent) {
  56008. this.percent = percent;
  56009. }
  56010. setVisible(visible) {
  56011. this.node.visible = visible;
  56012. this.posCurve.visible = visible;
  56013. this.targets.forEach(e => e.visible = visible);
  56014. this.visible = visible;
  56015. }
  56016. setDuration(duration) {
  56017. if (duration != this.duration) {
  56018. this.duration = duration;
  56019. if (this.quaternions.length == this.posCurve.points.length) this.reMapCurvePercent();
  56020. }
  56021. }
  56022. getDuration(duration) {
  56023. return this.duration;
  56024. }
  56025. play() {
  56026. var startOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  56027. if (this.onUpdate) {
  56028. return console.error('已经开始播放');
  56029. }
  56030. var startPercent = 0,
  56031. currentIndex = 0;
  56032. if (startOptions.percent != void 0) {
  56033. startPercent = startOptions.percent;
  56034. } else if (startOptions.index) {
  56035. currentIndex = index;
  56036. //startPercent = index/(this.posCurve.points.length-1)
  56037. startPercent = this.posCurve.pointsPercent[index];
  56038. }
  56039. //const tStart = performance.now();
  56040. var duration = this.duration;
  56041. this.originalyVisible = this.visible;
  56042. Potree.settings.tourTestCameraMove || this.setVisible(false);
  56043. var tStart,
  56044. startTransitionRatio = 0.2;
  56045. var startDelay = 1 / startTransitionRatio / 20; //因为缓动所以延迟开始,前面前都是at(0),使过渡到开始点位(但是依旧不能准确停在起始点,因为缓动是乘百分比有残留。所以直接平滑衔接到开始后的位置)
  56046. var hasPlayedTime = 0;
  56047. var finishDelay = Potree.settings.cameraAniSmoothRatio / 60 * 3; //结束后还需要多久时间才能大致达到缓动的最终目标
  56048. var hasStoppedTime = 0;
  56049. this.onUpdate = e => {
  56050. if (this.posCurve.points.length < 2) {
  56051. if (this.posCurve.points.length == 1) {
  56052. viewer.scene.view.position.copy(this.posCurve.points[0]);
  56053. viewer.scene.view.rotation = new Euler().setFromQuaternion(this.quaternions[0]);
  56054. }
  56055. this.pause();
  56056. return;
  56057. }
  56058. var percent, transitionRatio;
  56059. if (tStart) {
  56060. var tNow = performance.now();
  56061. var elapsed = (tNow - tStart) / 1000;
  56062. percent = elapsed / duration + startPercent;
  56063. } else {
  56064. //从当前位置过渡到开始位置
  56065. percent = 0;
  56066. hasPlayedTime += e.delta;
  56067. transitionRatio = startTransitionRatio;
  56068. //console.log('延迟开始')
  56069. if (hasPlayedTime > startDelay) {
  56070. tStart = performance.now();
  56071. }
  56072. }
  56073. this.set(percent);
  56074. var frame = this.at(percent, e.delta, transitionRatio);
  56075. if (currentIndex != this.currentIndex) {
  56076. currentIndex = this.currentIndex;
  56077. console.log('updateCurrentIndex', currentIndex);
  56078. this.dispatchEvent({
  56079. type: 'updateCurrentIndex',
  56080. currentIndex
  56081. });
  56082. }
  56083. if (!Potree.settings.tourTestCameraMove) {
  56084. viewer.scene.view.position.copy(frame.position);
  56085. //viewer.scene.view.lookAt(frame.target);
  56086. viewer.scene.view.rotation = frame.rotation;
  56087. }
  56088. this.updateFrustum(frame);
  56089. if (percent >= 1) {
  56090. if (hasStoppedTime > finishDelay) {
  56091. this.pause();
  56092. } else {
  56093. hasStoppedTime += e.delta;
  56094. //console.log('延迟结束')
  56095. }
  56096. }
  56097. };
  56098. this.viewer.addEventListener("update", this.onUpdate);
  56099. }
  56100. pause() {
  56101. this.setVisible(this.originalyVisible);
  56102. this.viewer.removeEventListener("update", this.onUpdate);
  56103. this.dispatchEvent('playDone');
  56104. this.onUpdate = null;
  56105. }
  56106. updateFrustum(frame) {
  56107. var frustum = this.frustum;
  56108. if (this.posCurve.points.length > 1) {
  56109. frustum.visible = true;
  56110. } else {
  56111. frustum.visible = false;
  56112. return;
  56113. }
  56114. frame = frame || this.at(this.percent);
  56115. frustum.position.copy(frame.position);
  56116. //frustum.lookAt(...frame.target.toArray());
  56117. frustum.rotation.copy(frame.rotation);
  56118. viewer.dispatchEvent('content_changed');
  56119. }
  56120. changeCallback(i) {
  56121. this.posCurve.update();
  56122. //this.targets.forEach(e=>e.update())
  56123. this.updatePathCallback();
  56124. if (i == void 0) {
  56125. var length = this.posCurve.points.length;
  56126. for (var _i3 = 0; _i3 < length; _i3++) {
  56127. this.dragPointCallback({
  56128. index: _i3
  56129. });
  56130. }
  56131. } else this.dragPointCallback({
  56132. index: i
  56133. });
  56134. this.updateFrustum();
  56135. }
  56136. dispose() {
  56137. //add
  56138. this.posCurve.dispose();
  56139. //this.targetCurve.dispatchEvent({type:'dispose'})
  56140. this.targets.forEach(e => e.dispose());
  56141. this.durations = [];
  56142. this.node.parent.remove(this.node);
  56143. }
  56144. }
  56145. //scene.removeCameraAnimation
  56146. //修改:不使用targetCurve作为target曲线,因为播放时posCuve的节点和targetCurve并没有对应,且使用target的曲线会使角度变化大的情况过渡生硬。
  56147. // 改完旋转了。但是位置也有问题。速度完全和路程相关,当在同一位置设置多点时,这段的总时长为0. (是否要设置最小时长?不过也做不到 - -)
  56148. class MeasurePanel {
  56149. constructor(viewer, measurement, propertiesPanel) {
  56150. this.viewer = viewer;
  56151. this.measurement = measurement;
  56152. this.propertiesPanel = propertiesPanel;
  56153. this._update = () => {
  56154. this.update();
  56155. };
  56156. }
  56157. createCoordinatesTable(points) {
  56158. var _this = this;
  56159. var table = $("\n\t\t\t<table class=\"measurement_value_table\">\n\t\t\t\t<tr>\n\t\t\t\t\t<th>x</th>\n\t\t\t\t\t<th>y</th>\n\t\t\t\t\t<th>z</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t");
  56160. var copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  56161. var _loop = function _loop(point) {
  56162. var x = Utils.addCommas(point.x.toFixed(3));
  56163. var y = Utils.addCommas(point.y.toFixed(3));
  56164. var z = Utils.addCommas(point.z.toFixed(3));
  56165. var row = $("\n\t\t\t\t<tr>\n\t\t\t\t\t<td><span>".concat(x, "</span></td>\n\t\t\t\t\t<td><span>").concat(y, "</span></td>\n\t\t\t\t\t<td><span>").concat(z, "</span></td>\n\t\t\t\t\t<td align=\"right\" style=\"width: 25%\">\n\t\t\t\t\t\t<img name=\"copy\" title=\"copy\" class=\"button-icon\" src=\"").concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t"));
  56166. _this.elCopy = row.find("img[name=copy]");
  56167. _this.elCopy.click(() => {
  56168. var msg = point.toArray().map(c => c.toFixed(3)).join(", ");
  56169. Utils.clipboardCopy(msg);
  56170. _this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56171. duration: 3000
  56172. });
  56173. });
  56174. table.append(row);
  56175. };
  56176. for (var point of points) {
  56177. _loop(point);
  56178. }
  56179. return table;
  56180. }
  56181. createAttributesTable() {
  56182. var elTable = $('<table class="measurement_value_table"></table>');
  56183. var point = this.measurement.points[0];
  56184. /* for(let attributeName of Object.keys(point)){
  56185. if(attributeName === "position"){
  56186. }else if(attributeName === "rgba"){
  56187. let color = point.rgba;
  56188. let text = color.join(', ');
  56189. elTable.append($(`
  56190. <tr>
  56191. <td>rgb</td>
  56192. <td>${text}</td>
  56193. </tr>
  56194. `));
  56195. }else{
  56196. let value = point[attributeName];
  56197. let text = value.join(', ');
  56198. elTable.append($(`
  56199. <tr>
  56200. <td>${attributeName}</td>
  56201. <td>${text}</td>
  56202. </tr>
  56203. `));
  56204. }
  56205. } */
  56206. return elTable;
  56207. }
  56208. update() {}
  56209. }
  56210. ;
  56211. class DistancePanel extends MeasurePanel {
  56212. constructor(viewer, measurement, propertiesPanel) {
  56213. super(viewer, measurement, propertiesPanel);
  56214. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56215. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<table id=\"distances_table\" class=\"measurement_value_table\"></table>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span>\n\t\t\t\t\t\t<input type=\"button\" name=\"make_profile\" value=\"profile from measure\" />\n\t\t\t\t\t</span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56216. this.elRemove = this.elContent.find("img[name=remove]");
  56217. this.elRemove.click(() => {
  56218. this.viewer.scene.removeMeasurement(measurement);
  56219. });
  56220. this.elMakeProfile = this.elContent.find("input[name=make_profile]");
  56221. this.elMakeProfile.click(() => {
  56222. //measurement.points;
  56223. var profile = new Profile();
  56224. profile.name = measurement.name;
  56225. profile.width = measurement.getTotalDistance() / 50;
  56226. for (var point of measurement.points) {
  56227. profile.addMarker(point.position.clone());
  56228. }
  56229. this.viewer.scene.addProfile(profile);
  56230. });
  56231. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56232. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56233. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56234. this.update();
  56235. }
  56236. update() {
  56237. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56238. elCoordiantesContainer.empty();
  56239. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  56240. var positions = this.measurement.points.map(p => p.position);
  56241. var distances = [];
  56242. for (var i = 0; i < positions.length - 1; i++) {
  56243. var d = positions[i].distanceTo(positions[i + 1]);
  56244. distances.push(d.toFixed(3));
  56245. }
  56246. var totalDistance = this.measurement.getTotalDistance().toFixed(3);
  56247. var elDistanceTable = this.elContent.find("#distances_table");
  56248. elDistanceTable.empty();
  56249. for (var _i = 0; _i < distances.length; _i++) {
  56250. var label = _i === 0 ? 'Distances: ' : '';
  56251. var distance = distances[_i];
  56252. var elDistance = $("\n\t\t\t\t<tr>\n\t\t\t\t\t<th>".concat(label, "</th>\n\t\t\t\t\t<td style=\"width: 100%; padding-left: 10px\">").concat(distance, "</td>\n\t\t\t\t</tr>"));
  56253. elDistanceTable.append(elDistance);
  56254. }
  56255. var elTotal = $("\n\t\t\t<tr>\n\t\t\t\t<th>Total: </td><td style=\"width: 100%; padding-left: 10px\">".concat(totalDistance, "</th>\n\t\t\t</tr>"));
  56256. elDistanceTable.append(elTotal);
  56257. }
  56258. }
  56259. ;
  56260. class PointPanel extends MeasurePanel {
  56261. constructor(viewer, measurement, propertiesPanel) {
  56262. super(viewer, measurement, propertiesPanel);
  56263. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56264. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<span class=\"attributes_table_container\"></span>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56265. this.elRemove = this.elContent.find("img[name=remove]");
  56266. this.elRemove.click(() => {
  56267. this.viewer.scene.removeMeasurement(measurement);
  56268. });
  56269. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56270. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56271. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56272. this.update();
  56273. }
  56274. update() {
  56275. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56276. elCoordiantesContainer.empty();
  56277. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  56278. var elAttributesContainer = this.elContent.find('.attributes_table_container');
  56279. elAttributesContainer.empty();
  56280. elAttributesContainer.append(this.createAttributesTable());
  56281. }
  56282. }
  56283. ;
  56284. class AreaPanel extends MeasurePanel {
  56285. constructor(viewer, measurement, propertiesPanel) {
  56286. super(viewer, measurement, propertiesPanel);
  56287. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56288. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<span style=\"font-weight: bold\">Area: </span>\n\t\t\t\t<span id=\"measurement_area\"></span>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56289. this.elRemove = this.elContent.find("img[name=remove]");
  56290. this.elRemove.click(() => {
  56291. this.viewer.scene.removeMeasurement(measurement);
  56292. });
  56293. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56294. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56295. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56296. this.update();
  56297. }
  56298. update() {
  56299. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56300. elCoordiantesContainer.empty();
  56301. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  56302. var elArea = this.elContent.find("#measurement_area");
  56303. elArea.html(this.measurement.area.value.toFixed(3));
  56304. }
  56305. }
  56306. ;
  56307. class AnglePanel extends MeasurePanel {
  56308. constructor(viewer, measurement, propertiesPanel) {
  56309. super(viewer, measurement, propertiesPanel);
  56310. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56311. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<table class=\"measurement_value_table\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>\u03B1</th>\n\t\t\t\t\t\t<th>\u03B2</th>\n\t\t\t\t\t\t<th>\u03B3</th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_alpha\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_betta\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_gamma\" style=\"width: 33%\"></td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56312. this.elRemove = this.elContent.find("img[name=remove]");
  56313. this.elRemove.click(() => {
  56314. this.viewer.scene.removeMeasurement(measurement);
  56315. });
  56316. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56317. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56318. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56319. this.update();
  56320. }
  56321. update() {
  56322. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56323. elCoordiantesContainer.empty();
  56324. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  56325. var angles = [];
  56326. for (var i = 0; i < this.measurement.points.length; i++) {
  56327. angles.push(this.measurement.getAngle(i) * (180.0 / Math.PI));
  56328. }
  56329. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  56330. var elAlpha = this.elContent.find("#angle_cell_alpha");
  56331. var elBetta = this.elContent.find("#angle_cell_betta");
  56332. var elGamma = this.elContent.find("#angle_cell_gamma");
  56333. elAlpha.html(angles[0]);
  56334. elBetta.html(angles[1]);
  56335. elGamma.html(angles[2]);
  56336. }
  56337. }
  56338. ;
  56339. class CirclePanel extends MeasurePanel {
  56340. constructor(viewer, measurement, propertiesPanel) {
  56341. super(viewer, measurement, propertiesPanel);
  56342. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56343. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<table id=\"infos_table\" class=\"measurement_value_table\"></table>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56344. this.elRemove = this.elContent.find("img[name=remove]");
  56345. this.elRemove.click(() => {
  56346. this.viewer.scene.removeMeasurement(measurement);
  56347. });
  56348. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56349. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56350. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56351. this.update();
  56352. }
  56353. update() {
  56354. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56355. elCoordiantesContainer.empty();
  56356. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  56357. var elInfos = this.elContent.find("#infos_table");
  56358. if (this.measurement.points.length !== 3) {
  56359. elInfos.empty();
  56360. return;
  56361. }
  56362. var A = this.measurement.points[0].position;
  56363. var B = this.measurement.points[1].position;
  56364. var C = this.measurement.points[2].position;
  56365. var center = Potree.Utils.computeCircleCenter(A, B, C);
  56366. var radius = center.distanceTo(A);
  56367. var circumference = 2 * Math.PI * radius;
  56368. var format = number => {
  56369. return Potree.Utils.addCommas(number.toFixed(3));
  56370. };
  56371. var txtCenter = "".concat(format(center.x), " ").concat(format(center.y), " ").concat(format(center.z));
  56372. var txtRadius = format(radius);
  56373. var txtCircumference = format(circumference);
  56374. var thStyle = "style=\"text-align: left\"";
  56375. var tdStyle = "style=\"width: 100%; padding: 5px;\"";
  56376. elInfos.html("\n\t\t\t<tr>\n\t\t\t\t<th ".concat(thStyle, ">Center: </th>\n\t\t\t\t<td ").concat(tdStyle, "></td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<td ").concat(tdStyle, " colspan=\"2\">\n\t\t\t\t\t").concat(txtCenter, "\n\t\t\t\t</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th ").concat(thStyle, ">Radius: </th>\n\t\t\t\t<td ").concat(tdStyle, ">").concat(txtRadius, "</td>\n\t\t\t</tr>\n\t\t\t<tr>\n\t\t\t\t<th ").concat(thStyle, ">Circumference: </th>\n\t\t\t\t<td ").concat(tdStyle, ">").concat(txtCircumference, "</td>\n\t\t\t</tr>\n\t\t"));
  56377. }
  56378. }
  56379. ;
  56380. class HeightPanel extends MeasurePanel {
  56381. constructor(viewer, measurement, propertiesPanel) {
  56382. super(viewer, measurement, propertiesPanel);
  56383. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56384. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<span id=\"height_label\">Height: </span><br>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56385. this.elRemove = this.elContent.find("img[name=remove]");
  56386. this.elRemove.click(() => {
  56387. this.viewer.scene.removeMeasurement(measurement);
  56388. });
  56389. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56390. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56391. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56392. this.update();
  56393. }
  56394. update() {
  56395. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56396. elCoordiantesContainer.empty();
  56397. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points.map(p => p.position)));
  56398. {
  56399. var points = this.measurement.points;
  56400. var sorted = points.slice().sort((a, b) => a.position.z - b.position.z);
  56401. var lowPoint = sorted[0].position.clone();
  56402. var highPoint = sorted[sorted.length - 1].position.clone();
  56403. var min = lowPoint.z;
  56404. var max = highPoint.z;
  56405. var height = max - min;
  56406. height = height.toFixed(3);
  56407. this.elHeightLabel = this.elContent.find("#height_label");
  56408. this.elHeightLabel.html("<b>Height:</b> ".concat(height));
  56409. }
  56410. }
  56411. }
  56412. ;
  56413. class VolumePanel extends MeasurePanel {
  56414. constructor(viewer, measurement, propertiesPanel) {
  56415. super(viewer, measurement, propertiesPanel);
  56416. var copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  56417. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56418. var lblLengthText = new Map([[BoxVolume, "length"], [SphereVolume$1, "rx"]]).get(measurement.constructor);
  56419. var lblWidthText = new Map([[BoxVolume, "width"], [SphereVolume$1, "ry"]]).get(measurement.constructor);
  56420. var lblHeightText = new Map([[BoxVolume, "height"], [SphereVolume$1, "rz"]]).get(measurement.constructor);
  56421. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\n\t\t\t\t<table class=\"measurement_value_table\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>\u03B1</th>\n\t\t\t\t\t\t<th>\u03B2</th>\n\t\t\t\t\t\t<th>\u03B3</th>\n\t\t\t\t\t\t<th></th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_alpha\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_betta\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"angle_cell_gamma\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"right\" style=\"width: 25%\">\n\t\t\t\t\t\t\t<img name=\"copyRotation\" title=\"copy\" class=\"button-icon\" src=\"".concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\n\t\t\t\t<table class=\"measurement_value_table\">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<th>").concat(lblLengthText, "</th>\n\t\t\t\t\t\t<th>").concat(lblWidthText, "</th>\n\t\t\t\t\t\t<th>").concat(lblHeightText, "</th>\n\t\t\t\t\t\t<th></th>\n\t\t\t\t\t</tr>\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td align=\"center\" id=\"cell_length\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"cell_width\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"center\" id=\"cell_height\" style=\"width: 33%\"></td>\n\t\t\t\t\t\t<td align=\"right\" style=\"width: 25%\">\n\t\t\t\t\t\t\t<img name=\"copyScale\" title=\"copy\" class=\"button-icon\" src=\"").concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t\t</td>\n\t\t\t\t\t</tr>\n\t\t\t\t</table>\n\n\t\t\t\t<br>\n\t\t\t\t<span style=\"font-weight: bold\">Volume: </span>\n\t\t\t\t<span id=\"measurement_volume\"></span>\n\n\t\t\t\t<!--\n\t\t\t\t<li>\n\t\t\t\t\t<label style=\"whitespace: nowrap\">\n\t\t\t\t\t\t<input id=\"volume_show\" type=\"checkbox\"/>\n\t\t\t\t\t\t<span>show volume</span>\n\t\t\t\t\t</label>\n\t\t\t\t</li>-->\n\n\t\t\t\t<li>\n\t\t\t\t\t<label style=\"whitespace: nowrap\">\n\t\t\t\t\t\t<input id=\"volume_clip\" type=\"checkbox\"/>\n\t\t\t\t\t\t<span>make clip volume</span>\n\t\t\t\t\t</label>\n\t\t\t\t</li>\n\n\t\t\t\t<li style=\"margin-top: 10px\">\n\t\t\t\t\t<input name=\"download_volume\" type=\"button\" value=\"prepare download\" style=\"width: 100%\" />\n\t\t\t\t\t<div name=\"download_message\"></div>\n\t\t\t\t</li>\n\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<li style=\"display: grid; grid-template-columns: auto auto; grid-column-gap: 5px; margin-top: 10px\">\n\t\t\t\t\t<input id=\"volume_reset_orientation\" type=\"button\" value=\"reset orientation\"/>\n\t\t\t\t\t<input id=\"volume_make_uniform\" type=\"button\" value=\"make uniform\"/>\n\t\t\t\t</li>\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"").concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56422. {
  56423. // download
  56424. this.elDownloadButton = this.elContent.find("input[name=download_volume]");
  56425. if (this.propertiesPanel.viewer.server) {
  56426. this.elDownloadButton.click(() => this.download());
  56427. } else {
  56428. this.elDownloadButton.hide();
  56429. }
  56430. }
  56431. this.elCopyRotation = this.elContent.find("img[name=copyRotation]");
  56432. this.elCopyRotation.click(() => {
  56433. var rotation = this.measurement.rotation.toArray().slice(0, 3);
  56434. var msg = rotation.map(c => c.toFixed(3)).join(", ");
  56435. Utils.clipboardCopy(msg);
  56436. this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56437. duration: 3000
  56438. });
  56439. });
  56440. this.elCopyScale = this.elContent.find("img[name=copyScale]");
  56441. this.elCopyScale.click(() => {
  56442. var scale = this.measurement.scale.toArray();
  56443. var msg = scale.map(c => c.toFixed(3)).join(", ");
  56444. Utils.clipboardCopy(msg);
  56445. this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56446. duration: 3000
  56447. });
  56448. });
  56449. this.elRemove = this.elContent.find("img[name=remove]");
  56450. this.elRemove.click(() => {
  56451. this.viewer.scene.removeVolume(measurement);
  56452. });
  56453. this.elContent.find("#volume_reset_orientation").click(() => {
  56454. measurement.rotation.set(0, 0, 0);
  56455. });
  56456. this.elContent.find("#volume_make_uniform").click(() => {
  56457. var mean = (measurement.scale.x + measurement.scale.y + measurement.scale.z) / 3;
  56458. measurement.scale.set(mean, mean, mean);
  56459. });
  56460. this.elCheckClip = this.elContent.find('#volume_clip');
  56461. this.elCheckClip.click(event => {
  56462. this.measurement.clip = event.target.checked;
  56463. });
  56464. this.elCheckShow = this.elContent.find('#volume_show');
  56465. this.elCheckShow.click(event => {
  56466. this.measurement.visible = event.target.checked;
  56467. });
  56468. this.propertiesPanel.addVolatileListener(measurement, "position_changed", this._update);
  56469. this.propertiesPanel.addVolatileListener(measurement, "orientation_changed", this._update);
  56470. this.propertiesPanel.addVolatileListener(measurement, "scale_changed", this._update);
  56471. this.propertiesPanel.addVolatileListener(measurement, "clip_changed", this._update);
  56472. this.update();
  56473. }
  56474. download() {
  56475. var _this = this;
  56476. return _asyncToGenerator(function* () {
  56477. var clipBox = _this.measurement;
  56478. var regions = [];
  56479. //for(let clipBox of boxes){
  56480. {
  56481. var toClip = clipBox.matrixWorld;
  56482. var px = new Vector3(+0.5, 0, 0).applyMatrix4(toClip);
  56483. var nx = new Vector3(-0.5, 0, 0).applyMatrix4(toClip);
  56484. var py = new Vector3(0, +0.5, 0).applyMatrix4(toClip);
  56485. var ny = new Vector3(0, -0.5, 0).applyMatrix4(toClip);
  56486. var pz = new Vector3(0, 0, +0.5).applyMatrix4(toClip);
  56487. var nz = new Vector3(0, 0, -0.5).applyMatrix4(toClip);
  56488. var pxN = new Vector3().subVectors(nx, px).normalize();
  56489. var nxN = pxN.clone().multiplyScalar(-1);
  56490. var pyN = new Vector3().subVectors(ny, py).normalize();
  56491. var nyN = pyN.clone().multiplyScalar(-1);
  56492. var pzN = new Vector3().subVectors(nz, pz).normalize();
  56493. var nzN = pzN.clone().multiplyScalar(-1);
  56494. var planes = [new Plane().setFromNormalAndCoplanarPoint(pxN, px), new Plane().setFromNormalAndCoplanarPoint(nxN, nx), new Plane().setFromNormalAndCoplanarPoint(pyN, py), new Plane().setFromNormalAndCoplanarPoint(nyN, ny), new Plane().setFromNormalAndCoplanarPoint(pzN, pz), new Plane().setFromNormalAndCoplanarPoint(nzN, nz)];
  56495. var planeQueryParts = [];
  56496. for (var plane of planes) {
  56497. var part = [plane.normal.toArray(), plane.constant].join(",");
  56498. part = "[".concat(part, "]");
  56499. planeQueryParts.push(part);
  56500. }
  56501. var region = "[" + planeQueryParts.join(",") + "]";
  56502. regions.push(region);
  56503. }
  56504. var regionsArg = regions.join(",");
  56505. var pointcloudArgs = [];
  56506. for (var pointcloud of _this.viewer.scene.pointclouds) {
  56507. if (!pointcloud.visible) {
  56508. continue;
  56509. }
  56510. var offset = pointcloud.pcoGeometry.offset.clone();
  56511. var negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  56512. var matrixWorld = pointcloud.matrixWorld;
  56513. var transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  56514. var path = "".concat(window.location.pathname, "/../").concat(pointcloud.pcoGeometry.url);
  56515. var arg = {
  56516. path: path,
  56517. transform: transform.elements
  56518. };
  56519. var argString = JSON.stringify(arg);
  56520. pointcloudArgs.push(argString);
  56521. }
  56522. var pointcloudsArg = pointcloudArgs.join(",");
  56523. var elMessage = _this.elContent.find("div[name=download_message]");
  56524. var error = message => {
  56525. elMessage.html("<div style=\"color: #ff0000\">ERROR: ".concat(message, "</div>"));
  56526. };
  56527. var info = message => {
  56528. elMessage.html("".concat(message));
  56529. };
  56530. var handle = null;
  56531. {
  56532. // START FILTER
  56533. var url = "".concat(viewer.server, "/create_regions_filter?pointclouds=[").concat(pointcloudsArg, "]&regions=[").concat(regionsArg, "]");
  56534. //console.log(url);
  56535. info("estimating results ...");
  56536. var response = yield fetch(url);
  56537. var jsResponse = yield response.json();
  56538. //console.log(jsResponse);
  56539. if (!jsResponse.handle) {
  56540. error(jsResponse.message);
  56541. return;
  56542. } else {
  56543. handle = jsResponse.handle;
  56544. }
  56545. }
  56546. {
  56547. // WAIT, CHECK PROGRESS, HANDLE FINISH
  56548. var _url = "".concat(viewer.server, "/check_regions_filter?handle=").concat(handle);
  56549. var sleep = function sleep(duration) {
  56550. return new Promise((res, rej) => {
  56551. setTimeout(() => {
  56552. res();
  56553. }, duration);
  56554. });
  56555. };
  56556. var handleFiltering = jsResponse => {
  56557. var {
  56558. progress,
  56559. estimate
  56560. } = jsResponse;
  56561. var progressFract = progress["processed points"] / estimate.points;
  56562. var progressPercents = parseInt(progressFract * 100);
  56563. info("progress: ".concat(progressPercents, "%"));
  56564. };
  56565. var handleFinish = jsResponse => {
  56566. var message = "downloads ready: <br>";
  56567. message += "<ul>";
  56568. for (var i = 0; i < jsResponse.pointclouds.length; i++) {
  56569. var _url2 = "".concat(viewer.server, "/download_regions_filter_result?handle=").concat(handle, "&index=").concat(i);
  56570. message += "<li><a href=\"".concat(_url2, "\">result_").concat(i, ".las</a> </li>\n");
  56571. }
  56572. var reportURL = "".concat(viewer.server, "/download_regions_filter_report?handle=").concat(handle);
  56573. message += "<li> <a href=\"".concat(reportURL, "\">report.json</a> </li>\n");
  56574. message += "</ul>";
  56575. info(message);
  56576. };
  56577. var handleUnexpected = jsResponse => {
  56578. var message = "Unexpected Response. <br>status: ".concat(jsResponse.status, " <br>message: ").concat(jsResponse.message);
  56579. info(message);
  56580. };
  56581. var handleError = jsResponse => {
  56582. var message = "ERROR: ".concat(jsResponse.message);
  56583. error(message);
  56584. throw new Error(message);
  56585. };
  56586. var start = Date.now();
  56587. while (true) {
  56588. var _response = yield fetch(_url);
  56589. var _jsResponse = yield _response.json();
  56590. if (_jsResponse.status === "ERROR") {
  56591. handleError(_jsResponse);
  56592. } else if (_jsResponse.status === "FILTERING") {
  56593. handleFiltering(_jsResponse);
  56594. } else if (_jsResponse.status === "FINISHED") {
  56595. handleFinish(_jsResponse);
  56596. break;
  56597. } else {
  56598. handleUnexpected(_jsResponse);
  56599. }
  56600. var durationS = (Date.now() - start) / 1000;
  56601. var sleepAmountMS = durationS < 10 ? 100 : 1000;
  56602. yield sleep(sleepAmountMS);
  56603. }
  56604. }
  56605. })();
  56606. }
  56607. update() {
  56608. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56609. elCoordiantesContainer.empty();
  56610. elCoordiantesContainer.append(this.createCoordinatesTable([this.measurement.position]));
  56611. {
  56612. var angles = this.measurement.rotation.toVector3();
  56613. angles = angles.toArray();
  56614. //angles = [angles.z, angles.x, angles.y];
  56615. angles = angles.map(v => 180 * v / Math.PI);
  56616. angles = angles.map(a => a.toFixed(1) + '\u00B0');
  56617. var elAlpha = this.elContent.find("#angle_cell_alpha");
  56618. var elBetta = this.elContent.find("#angle_cell_betta");
  56619. var elGamma = this.elContent.find("#angle_cell_gamma");
  56620. elAlpha.html(angles[0]);
  56621. elBetta.html(angles[1]);
  56622. elGamma.html(angles[2]);
  56623. }
  56624. {
  56625. var dimensions = this.measurement.scale.toArray();
  56626. dimensions = dimensions.map(v => Utils.addCommas(v.toFixed(2)));
  56627. var elLength = this.elContent.find("#cell_length");
  56628. var elWidth = this.elContent.find("#cell_width");
  56629. var elHeight = this.elContent.find("#cell_height");
  56630. elLength.html(dimensions[0]);
  56631. elWidth.html(dimensions[1]);
  56632. elHeight.html(dimensions[2]);
  56633. }
  56634. {
  56635. var elVolume = this.elContent.find("#measurement_volume");
  56636. var volume = this.measurement.getVolume();
  56637. elVolume.html(Utils.addCommas(volume.toFixed(2)));
  56638. }
  56639. this.elCheckClip.prop("checked", this.measurement.clip);
  56640. this.elCheckShow.prop("checked", this.measurement.visible);
  56641. }
  56642. }
  56643. ;
  56644. class ProfilePanel extends MeasurePanel {
  56645. constructor(viewer, measurement, propertiesPanel) {
  56646. super(viewer, measurement, propertiesPanel);
  56647. var removeIconPath = Potree.resourcePath + '/icons/remove.svg';
  56648. this.elContent = $("\n\t\t\t<div class=\"measurement_content selectable\">\n\t\t\t\t<span class=\"coordinates_table_container\"></span>\n\t\t\t\t<br>\n\t\t\t\t<span style=\"display:flex\">\n\t\t\t\t\t<span style=\"display:flex; align-items: center; padding-right: 10px\">Width: </span>\n\t\t\t\t\t<input id=\"sldProfileWidth\" name=\"sldProfileWidth\" value=\"5.06\" style=\"flex-grow: 1; width:100%\">\n\t\t\t\t</span>\n\t\t\t\t<br>\n\n\t\t\t\t<li style=\"margin-top: 10px\">\n\t\t\t\t\t<input name=\"download_profile\" type=\"button\" value=\"prepare download\" style=\"width: 100%\" />\n\t\t\t\t\t<div name=\"download_message\"></div>\n\t\t\t\t</li>\n\n\t\t\t\t<br>\n\n\t\t\t\t<input type=\"button\" id=\"show_2d_profile\" value=\"show 2d profile\" style=\"width: 100%\"/>\n\n\t\t\t\t<!-- ACTIONS -->\n\t\t\t\t<div style=\"display: flex; margin-top: 12px\">\n\t\t\t\t\t<span></span>\n\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t<img name=\"remove\" class=\"button-icon\" src=\"".concat(removeIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t"));
  56649. this.elRemove = this.elContent.find("img[name=remove]");
  56650. this.elRemove.click(() => {
  56651. this.viewer.scene.removeProfile(measurement);
  56652. });
  56653. {
  56654. // download
  56655. this.elDownloadButton = this.elContent.find("input[name=download_profile]");
  56656. if (this.propertiesPanel.viewer.server) {
  56657. this.elDownloadButton.click(() => this.download());
  56658. } else {
  56659. this.elDownloadButton.hide();
  56660. }
  56661. }
  56662. {
  56663. // width spinner
  56664. var elWidthSlider = this.elContent.find("#sldProfileWidth");
  56665. elWidthSlider.spinner({
  56666. min: 0,
  56667. max: 10 * 1000 * 1000,
  56668. step: 0.01,
  56669. numberFormat: 'n',
  56670. start: () => {},
  56671. spin: (event, ui) => {
  56672. var value = elWidthSlider.spinner('value');
  56673. measurement.setWidth(value);
  56674. },
  56675. change: (event, ui) => {
  56676. var value = elWidthSlider.spinner('value');
  56677. measurement.setWidth(value);
  56678. },
  56679. stop: (event, ui) => {
  56680. var value = elWidthSlider.spinner('value');
  56681. measurement.setWidth(value);
  56682. },
  56683. incremental: count => {
  56684. var value = elWidthSlider.spinner('value');
  56685. var step = elWidthSlider.spinner('option', 'step');
  56686. var delta = value * 0.05;
  56687. var increments = Math.max(1, parseInt(delta / step));
  56688. return increments;
  56689. }
  56690. });
  56691. elWidthSlider.spinner('value', measurement.getWidth());
  56692. elWidthSlider.spinner('widget').css('width', '100%');
  56693. var widthListener = event => {
  56694. var value = elWidthSlider.spinner('value');
  56695. if (value !== measurement.getWidth()) {
  56696. elWidthSlider.spinner('value', measurement.getWidth());
  56697. }
  56698. };
  56699. this.propertiesPanel.addVolatileListener(measurement, "width_changed", widthListener);
  56700. }
  56701. var elShow2DProfile = this.elContent.find("#show_2d_profile");
  56702. elShow2DProfile.click(() => {
  56703. this.propertiesPanel.viewer.profileWindow.show();
  56704. this.propertiesPanel.viewer.profileWindowController.setProfile(measurement);
  56705. });
  56706. this.propertiesPanel.addVolatileListener(measurement, "marker_added", this._update);
  56707. this.propertiesPanel.addVolatileListener(measurement, "marker_removed", this._update);
  56708. this.propertiesPanel.addVolatileListener(measurement, "marker_moved", this._update);
  56709. this.update();
  56710. }
  56711. update() {
  56712. var elCoordiantesContainer = this.elContent.find('.coordinates_table_container');
  56713. elCoordiantesContainer.empty();
  56714. elCoordiantesContainer.append(this.createCoordinatesTable(this.measurement.points));
  56715. }
  56716. download() {
  56717. var _this = this;
  56718. return _asyncToGenerator(function* () {
  56719. var profile = _this.measurement;
  56720. var regions = [];
  56721. {
  56722. var segments = profile.getSegments();
  56723. var width = profile.width;
  56724. for (var segment of segments) {
  56725. var start = segment.start.clone().multiply(new Vector3(1, 1, 0));
  56726. var end = segment.end.clone().multiply(new Vector3(1, 1, 0));
  56727. var center = new Vector3().addVectors(start, end).multiplyScalar(0.5);
  56728. var startEndDir = new Vector3().subVectors(end, start).normalize();
  56729. var endStartDir = new Vector3().subVectors(start, end).normalize();
  56730. var upDir = new Vector3(0, 0, 1);
  56731. var rightDir = new Vector3().crossVectors(startEndDir, upDir);
  56732. var leftDir = new Vector3().crossVectors(endStartDir, upDir);
  56733. console.log(leftDir);
  56734. var right = rightDir.clone().multiplyScalar(width * 0.5).add(center);
  56735. var left = leftDir.clone().multiplyScalar(width * 0.5).add(center);
  56736. var planes = [new Plane().setFromNormalAndCoplanarPoint(startEndDir, start), new Plane().setFromNormalAndCoplanarPoint(endStartDir, end), new Plane().setFromNormalAndCoplanarPoint(leftDir, right), new Plane().setFromNormalAndCoplanarPoint(rightDir, left)];
  56737. var planeQueryParts = [];
  56738. for (var plane of planes) {
  56739. var part = [plane.normal.toArray(), plane.constant].join(",");
  56740. part = "[".concat(part, "]");
  56741. planeQueryParts.push(part);
  56742. }
  56743. var region = "[" + planeQueryParts.join(",") + "]";
  56744. regions.push(region);
  56745. }
  56746. }
  56747. var regionsArg = regions.join(",");
  56748. var pointcloudArgs = [];
  56749. for (var pointcloud of _this.viewer.scene.pointclouds) {
  56750. if (!pointcloud.visible) {
  56751. continue;
  56752. }
  56753. var offset = pointcloud.pcoGeometry.offset.clone();
  56754. var negateOffset = new Matrix4().makeTranslation(...offset.multiplyScalar(-1).toArray());
  56755. var matrixWorld = pointcloud.matrixWorld;
  56756. var transform = new Matrix4().multiplyMatrices(matrixWorld, negateOffset);
  56757. var path = "".concat(window.location.pathname, "/../").concat(pointcloud.pcoGeometry.url);
  56758. var arg = {
  56759. path: path,
  56760. transform: transform.elements
  56761. };
  56762. var argString = JSON.stringify(arg);
  56763. pointcloudArgs.push(argString);
  56764. }
  56765. var pointcloudsArg = pointcloudArgs.join(",");
  56766. var elMessage = _this.elContent.find("div[name=download_message]");
  56767. var error = message => {
  56768. elMessage.html("<div style=\"color: #ff0000\">ERROR: ".concat(message, "</div>"));
  56769. };
  56770. var info = message => {
  56771. elMessage.html("".concat(message));
  56772. };
  56773. var handle = null;
  56774. {
  56775. // START FILTER
  56776. var url = "".concat(viewer.server, "/create_regions_filter?pointclouds=[").concat(pointcloudsArg, "]&regions=[").concat(regionsArg, "]");
  56777. //console.log(url);
  56778. info("estimating results ...");
  56779. var response = yield fetch(url);
  56780. var jsResponse = yield response.json();
  56781. //console.log(jsResponse);
  56782. if (!jsResponse.handle) {
  56783. error(jsResponse.message);
  56784. return;
  56785. } else {
  56786. handle = jsResponse.handle;
  56787. }
  56788. }
  56789. {
  56790. // WAIT, CHECK PROGRESS, HANDLE FINISH
  56791. var _url = "".concat(viewer.server, "/check_regions_filter?handle=").concat(handle);
  56792. var sleep = function sleep(duration) {
  56793. return new Promise((res, rej) => {
  56794. setTimeout(() => {
  56795. res();
  56796. }, duration);
  56797. });
  56798. };
  56799. var handleFiltering = jsResponse => {
  56800. var {
  56801. progress,
  56802. estimate
  56803. } = jsResponse;
  56804. var progressFract = progress["processed points"] / estimate.points;
  56805. var progressPercents = parseInt(progressFract * 100);
  56806. info("progress: ".concat(progressPercents, "%"));
  56807. };
  56808. var handleFinish = jsResponse => {
  56809. var message = "downloads ready: <br>";
  56810. message += "<ul>";
  56811. for (var i = 0; i < jsResponse.pointclouds.length; i++) {
  56812. var _url2 = "".concat(viewer.server, "/download_regions_filter_result?handle=").concat(handle, "&index=").concat(i);
  56813. message += "<li><a href=\"".concat(_url2, "\">result_").concat(i, ".las</a> </li>\n");
  56814. }
  56815. var reportURL = "".concat(viewer.server, "/download_regions_filter_report?handle=").concat(handle);
  56816. message += "<li> <a href=\"".concat(reportURL, "\">report.json</a> </li>\n");
  56817. message += "</ul>";
  56818. info(message);
  56819. };
  56820. var handleUnexpected = jsResponse => {
  56821. var message = "Unexpected Response. <br>status: ".concat(jsResponse.status, " <br>message: ").concat(jsResponse.message);
  56822. info(message);
  56823. };
  56824. var handleError = jsResponse => {
  56825. var message = "ERROR: ".concat(jsResponse.message);
  56826. error(message);
  56827. throw new Error(message);
  56828. };
  56829. var _start = Date.now();
  56830. while (true) {
  56831. var _response = yield fetch(_url);
  56832. var _jsResponse = yield _response.json();
  56833. if (_jsResponse.status === "ERROR") {
  56834. handleError(_jsResponse);
  56835. } else if (_jsResponse.status === "FILTERING") {
  56836. handleFiltering(_jsResponse);
  56837. } else if (_jsResponse.status === "FINISHED") {
  56838. handleFinish(_jsResponse);
  56839. break;
  56840. } else {
  56841. handleUnexpected(_jsResponse);
  56842. }
  56843. var durationS = (Date.now() - _start) / 1000;
  56844. var sleepAmountMS = durationS < 10 ? 100 : 1000;
  56845. yield sleep(sleepAmountMS);
  56846. }
  56847. }
  56848. })();
  56849. }
  56850. }
  56851. ;
  56852. class CameraPanel {
  56853. constructor(viewer, propertiesPanel) {
  56854. this.viewer = viewer;
  56855. this.propertiesPanel = propertiesPanel;
  56856. this._update = () => {
  56857. this.update();
  56858. };
  56859. var copyIconPath = Potree.resourcePath + '/icons/copy.svg';
  56860. this.elContent = $("\n\t\t<div class=\"propertypanel_content\">\n\t\t\t<table>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan=\"3\">position</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align=\"center\" id=\"camera_position_x\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"camera_position_y\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"camera_position_z\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"right\" id=\"copy_camera_position\" style=\"width: 25%\">\n\t\t\t\t\t\t<img name=\"copyPosition\" title=\"copy\" class=\"button-icon\" src=\"".concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan=\"3\">target</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align=\"center\" id=\"camera_target_x\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"camera_target_y\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"camera_target_z\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"right\" id=\"copy_camera_target\" style=\"width: 25%\">\n\t\t\t\t\t\t<img name=\"copyTarget\" title=\"copy\" class=\"button-icon\" src=\"").concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\t\t\t</table>\n\t\t</div>\n\t\t"));
  56861. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  56862. this.elCopyPosition.click(() => {
  56863. var pos = this.viewer.scene.getActiveCamera().position.toArray();
  56864. var msg = pos.map(c => c.toFixed(3)).join(", ");
  56865. Utils.clipboardCopy(msg);
  56866. this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56867. duration: 3000
  56868. });
  56869. });
  56870. this.elCopyTarget = this.elContent.find("img[name=copyTarget]");
  56871. this.elCopyTarget.click(() => {
  56872. var pos = this.viewer.scene.view.getPivot().toArray();
  56873. var msg = pos.map(c => c.toFixed(3)).join(", ");
  56874. Utils.clipboardCopy(msg);
  56875. this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56876. duration: 3000
  56877. });
  56878. });
  56879. this.propertiesPanel.addVolatileListener(viewer, "camera_changed", this._update);
  56880. this.update();
  56881. }
  56882. update() {
  56883. //console.log("updating camera panel");
  56884. var camera = this.viewer.scene.getActiveCamera();
  56885. var view = this.viewer.scene.view;
  56886. var pos = camera.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  56887. this.elContent.find("#camera_position_x").html(pos[0]);
  56888. this.elContent.find("#camera_position_y").html(pos[1]);
  56889. this.elContent.find("#camera_position_z").html(pos[2]);
  56890. var target = view.getPivot().toArray().map(c => Utils.addCommas(c.toFixed(3)));
  56891. this.elContent.find("#camera_target_x").html(target[0]);
  56892. this.elContent.find("#camera_target_y").html(target[1]);
  56893. this.elContent.find("#camera_target_z").html(target[2]);
  56894. }
  56895. }
  56896. ;
  56897. class AnnotationPanel {
  56898. constructor(viewer, propertiesPanel, annotation) {
  56899. this.viewer = viewer;
  56900. this.propertiesPanel = propertiesPanel;
  56901. this.annotation = annotation;
  56902. this._update = () => {
  56903. this.update();
  56904. };
  56905. var copyIconPath = "".concat(Potree.resourcePath, "/icons/copy.svg");
  56906. this.elContent = $("\n\t\t<div class=\"propertypanel_content\">\n\t\t\t<table>\n\t\t\t\t<tr>\n\t\t\t\t\t<th colspan=\"3\">position</th>\n\t\t\t\t\t<th></th>\n\t\t\t\t</tr>\n\t\t\t\t<tr>\n\t\t\t\t\t<td align=\"center\" id=\"annotation_position_x\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"annotation_position_y\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"center\" id=\"annotation_position_z\" style=\"width: 25%\"></td>\n\t\t\t\t\t<td align=\"right\" id=\"copy_annotation_position\" style=\"width: 25%\">\n\t\t\t\t\t\t<img name=\"copyPosition\" title=\"copy\" class=\"button-icon\" src=\"".concat(copyIconPath, "\" style=\"width: 16px; height: 16px\"/>\n\t\t\t\t\t</td>\n\t\t\t\t</tr>\n\n\t\t\t</table>\n\n\t\t\t<div>\n\n\t\t\t\t<div class=\"heading\">Title</div>\n\t\t\t\t<div id=\"annotation_title\" contenteditable=\"true\">\n\t\t\t\t\tAnnotation Title\n\t\t\t\t</div>\n\n\t\t\t\t<div class=\"heading\">Description</div>\n\t\t\t\t<div id=\"annotation_description\" contenteditable=\"true\">\n\t\t\t\t\tA longer description of this annotation. \n\t\t\t\t\t\tCan be multiple lines long. TODO: the user should be able\n\t\t\t\t\t\tto modify title and description. \n\t\t\t\t</div>\n\n\t\t\t</div>\n\n\t\t</div>\n\t\t"));
  56907. this.elCopyPosition = this.elContent.find("img[name=copyPosition]");
  56908. this.elCopyPosition.click(() => {
  56909. var pos = this.annotation.position.toArray();
  56910. var msg = pos.map(c => c.toFixed(3)).join(", ");
  56911. Utils.clipboardCopy(msg);
  56912. this.viewer.postMessage("Copied value to clipboard: <br>'".concat(msg, "'"), {
  56913. duration: 3000
  56914. });
  56915. });
  56916. this.elTitle = this.elContent.find("#annotation_title").html(annotation.title);
  56917. this.elDescription = this.elContent.find("#annotation_description").html(annotation.description);
  56918. this.elTitle[0].addEventListener("input", () => {
  56919. var title = this.elTitle.html();
  56920. annotation.title = title;
  56921. }, false);
  56922. this.elDescription[0].addEventListener("input", () => {
  56923. var description = this.elDescription.html();
  56924. annotation.description = description;
  56925. }, false);
  56926. this.update();
  56927. }
  56928. update() {
  56929. var {
  56930. annotation,
  56931. elContent,
  56932. elTitle,
  56933. elDescription
  56934. } = this;
  56935. var pos = annotation.position.toArray().map(c => Utils.addCommas(c.toFixed(3)));
  56936. elContent.find("#annotation_position_x").html(pos[0]);
  56937. elContent.find("#annotation_position_y").html(pos[1]);
  56938. elContent.find("#annotation_position_z").html(pos[2]);
  56939. elTitle.html(annotation.title);
  56940. elDescription.html(annotation.description);
  56941. }
  56942. }
  56943. ;
  56944. class CameraAnimationPanel {
  56945. constructor(viewer, propertiesPanel, animation) {
  56946. this.viewer = viewer;
  56947. this.propertiesPanel = propertiesPanel;
  56948. this.animation = animation;
  56949. this.elContent = $("\n\t\t\t<div class=\"propertypanel_content\">\n\t\t\t\t<span id=\"animation_keyframes\"></span>\n\n\t\t\t\t<span>\n\n\t\t\t\t\t<span style=\"display:flex\">\n\t\t\t\t\t\t<span style=\"display:flex; align-items: center; padding-right: 10px\">Duration: </span>\n\t\t\t\t\t\t<input name=\"spnDuration\" value=\"5.0\" style=\"flex-grow: 1; width:100%\">\n\t\t\t\t\t</span>\n\n\t\t\t\t\t<span>Time: </span><span id=\"lblTime\"></span> <div id=\"sldTime\"></div>\n\n\t\t\t\t\t<input name=\"play\" type=\"button\" value=\"play\"/>\n\t\t\t\t\t<input name=\"pause\" type=\"button\" value=\"pause\"/>\n\t\t\t\t</span>\n\t\t\t</div>\n\t\t");
  56950. var elPlay = this.elContent.find("input[name=play]");
  56951. elPlay.click(() => {
  56952. animation.play();
  56953. });
  56954. var elPause = this.elContent.find("input[name=pause]");
  56955. elPause.click(() => {
  56956. animation.pause();
  56957. });
  56958. var elSlider = this.elContent.find('#sldTime');
  56959. elSlider.slider({
  56960. value: 0,
  56961. min: 0,
  56962. max: 1,
  56963. step: 0.001,
  56964. slide: (event, ui) => {
  56965. animation.set(ui.value);
  56966. animation.updateFrustum();
  56967. }
  56968. });
  56969. var elDuration = this.elContent.find("input[name=spnDuration]");
  56970. elDuration.spinner({
  56971. min: 0,
  56972. max: 300,
  56973. step: 0.01,
  56974. numberFormat: 'n',
  56975. start: () => {},
  56976. spin: (event, ui) => {
  56977. var value = elDuration.spinner('value');
  56978. animation.setDuration(value);
  56979. },
  56980. change: (event, ui) => {
  56981. var value = elDuration.spinner('value');
  56982. animation.setDuration(value);
  56983. },
  56984. stop: (event, ui) => {
  56985. var value = elDuration.spinner('value');
  56986. animation.setDuration(value);
  56987. },
  56988. incremental: count => {
  56989. var value = elDuration.spinner('value');
  56990. var step = elDuration.spinner('option', 'step');
  56991. var delta = value * 0.05;
  56992. var increments = Math.max(1, parseInt(delta / step));
  56993. return increments;
  56994. }
  56995. });
  56996. elDuration.spinner('value', animation.getDuration());
  56997. elDuration.spinner('widget').css('width', '100%');
  56998. var elKeyframes = this.elContent.find("#animation_keyframes");
  56999. var updateKeyframes = () => {
  57000. elKeyframes.empty();
  57001. //let index = 0;
  57002. // <span style="flex-grow: 0;">
  57003. // <img name="add" src="${Potree.resourcePath}/icons/add.svg" style="width: 1.5em; height: 1.5em"/>
  57004. // </span>
  57005. var addNewKeyframeItem = index => {
  57006. var elNewKeyframe = $("\n\t\t\t\t\t<div style=\"display: flex; margin: 0.2em 0em\">\n\t\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t\t<input type=\"button\" name=\"add\" value=\"insert control point\" />\n\t\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t</div>\n\t\t\t\t");
  57007. var elAdd = elNewKeyframe.find("input[name=add]");
  57008. elAdd.click(() => {
  57009. animation.createControlPoint(index, {
  57010. position: viewer.scene.view.position,
  57011. target: viewer.scene.view.getPivot()
  57012. });
  57013. animation.changeCallback();
  57014. });
  57015. elKeyframes.append(elNewKeyframe);
  57016. };
  57017. var addKeyframeItem = index => {
  57018. var elKeyframe = $("\n\t\t\t\t\t<div style=\"display: flex; margin: 0.2em 0em\">\n\t\t\t\t\t\t<span style=\"flex-grow: 0;\">\n\t\t\t\t\t\t\t<img name=\"assign\" src=\"".concat(Potree.resourcePath, "/icons/assign.svg\" style=\"width: 1.5em; height: 1.5em\"/>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span style=\"flex-grow: 0;\">\n\t\t\t\t\t\t\t<img name=\"move\" src=\"").concat(Potree.resourcePath, "/icons/circled_dot.svg\" style=\"width: 1.5em; height: 1.5em\"/>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t\t<span style=\"flex-grow: 0; width: 1.5em; height: 1.5em\"></span>\n\t\t\t\t\t\t<span style=\"flex-grow: 0; font-size: 1.5em\">keyframe</span>\n\t\t\t\t\t\t<span style=\"flex-grow: 1\"></span>\n\t\t\t\t\t\t<span style=\"flex-grow: 0;\">\n\t\t\t\t\t\t\t<img name=\"delete\" src=\"").concat(Potree.resourcePath, "/icons/remove.svg\" style=\"width: 1.5em; height: 1.5em\"/>\n\t\t\t\t\t\t</span>\n\t\t\t\t\t</div>\n\t\t\t\t"));
  57019. var elAssign = elKeyframe.find("img[name=assign]");
  57020. var elMove = elKeyframe.find("img[name=move]");
  57021. var elDelete = elKeyframe.find("img[name=delete]");
  57022. elAssign.click(() => {
  57023. //修改
  57024. animation.posCurve.points[index].copy(viewer.scene.view.position);
  57025. animation.targets[index].position.copy(viewer.scene.view.getPivot());
  57026. animation.changeCallback(index);
  57027. });
  57028. elMove.click(() => {
  57029. viewer.scene.view.position.copy(animation.posCurve.points[index]);
  57030. viewer.scene.view.lookAt(animation.targets[index].position);
  57031. });
  57032. elDelete.click(() => {
  57033. animation.removeControlPoint(index);
  57034. animation.changeCallback();
  57035. });
  57036. elKeyframes.append(elKeyframe);
  57037. };
  57038. var index = 0;
  57039. addNewKeyframeItem(index);
  57040. animation.posCurve.points.forEach(e => {
  57041. addKeyframeItem(index);
  57042. index++;
  57043. addNewKeyframeItem(index);
  57044. });
  57045. };
  57046. updateKeyframes();
  57047. animation.addEventListener("controlpoint_added", updateKeyframes);
  57048. animation.addEventListener("controlpoint_removed", updateKeyframes);
  57049. // this._update = () => { this.update(); };
  57050. // this.update();
  57051. }
  57052. update() {}
  57053. }
  57054. ;
  57055. class PropertiesPanel {
  57056. constructor(container, viewer) {
  57057. this.container = container;
  57058. this.viewer = viewer;
  57059. this.object = null;
  57060. this.cleanupTasks = [];
  57061. this.scene = null;
  57062. }
  57063. setScene(scene) {
  57064. this.scene = scene;
  57065. }
  57066. set(object) {
  57067. if (this.object === object) {
  57068. return;
  57069. }
  57070. this.object = object;
  57071. for (var task of this.cleanupTasks) {
  57072. task();
  57073. }
  57074. this.cleanupTasks = [];
  57075. this.container.empty();
  57076. if (object instanceof PointCloudTree) {
  57077. this.setPointCloud(object);
  57078. } else if (object instanceof Measure || object instanceof Profile || object instanceof Volume) {
  57079. this.setMeasurement(object);
  57080. } else if (object instanceof Camera) {
  57081. this.setCamera(object);
  57082. } else if (object instanceof Annotation) {
  57083. this.setAnnotation(object);
  57084. } else if (object instanceof CameraAnimation$1) {
  57085. //改
  57086. this.setCameraAnimation(object);
  57087. }
  57088. }
  57089. //
  57090. // Used for events that should be removed when the property object changes.
  57091. // This is for listening to materials, scene, point clouds, etc.
  57092. // not required for DOM listeners, since they are automatically cleared by removing the DOM subtree.
  57093. //
  57094. addVolatileListener(target, type, callback) {
  57095. target.addEventListener(type, callback);
  57096. this.cleanupTasks.push(() => {
  57097. target.removeEventListener(type, callback);
  57098. });
  57099. }
  57100. setPointCloud(pointcloud) {
  57101. var material = pointcloud.material;
  57102. var panel = $("\n\t\t\t<div class=\"scene_content selectable\">\n\t\t\t\t<ul class=\"pv-menu-list\">\n\n\t\t\t\t<li>\n\t\t\t\t<span data-i18n=\"appearance.point_size\"></span>:&nbsp;<span id=\"lblPointSize\"></span> <div id=\"sldPointSize\"></div>\n\t\t\t\t</li>\n\t\t\t\t<li>\n\t\t\t\t<span data-i18n=\"appearance.min_point_size\"></span>:&nbsp;<span id=\"lblMinPointSize\"></span> <div id=\"sldMinPointSize\"></div>\n\t\t\t\t</li>\n\n\t\t\t\t<!-- SIZE TYPE -->\n\t\t\t\t<li>\n\t\t\t\t\t<label for=\"optPointSizing\" class=\"pv-select-label\" data-i18n=\"appearance.point_size_type\">Point Sizing </label>\n\t\t\t\t\t<select id=\"optPointSizing\" name=\"optPointSizing\">\n\t\t\t\t\t\t<option>FIXED</option>\n\t\t\t\t\t\t<option>ATTENUATED</option>\n\t\t\t\t\t\t<option>ADAPTIVE</option>\n\t\t\t\t\t</select>\n\t\t\t\t</li>\n\n\t\t\t\t<!-- SHAPE -->\n\t\t\t\t<li>\n\t\t\t\t\t<label for=\"optShape\" class=\"pv-select-label\" data-i18n=\"appearance.point_shape\"></label><br>\n\t\t\t\t\t<select id=\"optShape\" name=\"optShape\">\n\t\t\t\t\t\t<option>SQUARE</option>\n\t\t\t\t\t\t<option>CIRCLE</option>\n\t\t\t\t\t\t<option>PARABOLOID</option>\n\t\t\t\t\t</select>\n\t\t\t\t</li>\n\n\t\t\t\t<li id=\"materials_backface_container\">\n\t\t\t\t<label><input id=\"set_backface_culling\" type=\"checkbox\" /><span data-i18n=\"appearance.backface_culling\"></span></label>\n\t\t\t\t</li>\n\t\t\t\t\n\t\t\t\t<!-- OPACITY -->\n\t\t\t\t<li><span data-i18n=\"appearance.point_opacity\"></span>:<span id=\"lblOpacity\"></span><div id=\"sldOpacity\"></div></li>\n\n\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t<span>Attribute</span>\n\t\t\t\t</div>\n\n\t\t\t\t<li>\n\t\t\t\t\t<select id=\"optMaterial\" name=\"optMaterial\"></select>\n\t\t\t\t</li>\n\n\t\t\t\t<div id=\"materials.composite_weight_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Attribute Weights</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li>RGB: <span id=\"lblWeightRGB\"></span> <div id=\"sldWeightRGB\"></div>\t</li>\n\t\t\t\t\t<li>Intensity: <span id=\"lblWeightIntensity\"></span> <div id=\"sldWeightIntensity\"></div>\t</li>\n\t\t\t\t\t<li>Elevation: <span id=\"lblWeightElevation\"></span> <div id=\"sldWeightElevation\"></div>\t</li>\n\t\t\t\t\t<li>Classification: <span id=\"lblWeightClassification\"></span> <div id=\"sldWeightClassification\"></div>\t</li>\n\t\t\t\t\t<li>Return Number: <span id=\"lblWeightReturnNumber\"></span> <div id=\"sldWeightReturnNumber\"></div>\t</li>\n\t\t\t\t\t<li>Source ID: <span id=\"lblWeightSourceID\"></span> <div id=\"sldWeightSourceID\"></div>\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.rgb_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>RGB</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li>Gamma: <span id=\"lblRGBGamma\"></span> <div id=\"sldRGBGamma\"></div>\t</li>\n\t\t\t\t\t<li>Brightness: <span id=\"lblRGBBrightness\"></span> <div id=\"sldRGBBrightness\"></div>\t</li>\n\t\t\t\t\t<li>Contrast: <span id=\"lblRGBContrast\"></span> <div id=\"sldRGBContrast\"></div>\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.extra_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Extra Attribute</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li><span data-i18n=\"appearance.extra_range\"></span>: <span id=\"lblExtraRange\"></span> <div id=\"sldExtraRange\"></div></li>\n\n\t\t\t\t\t<li>Gamma: <span id=\"lblExtraGamma\"></span> <div id=\"sldExtraGamma\"></div></li>\n\t\t\t\t\t<li>Brightness: <span id=\"lblExtraBrightness\"></span> <div id=\"sldExtraBrightness\"></div></li>\n\t\t\t\t\t<li>Contrast: <span id=\"lblExtraContrast\"></span> <div id=\"sldExtraContrast\"></div></li>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<div id=\"materials.matcap_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>MATCAP</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<div id=\"matcap_scheme_selection\" style=\"display: flex; flex-wrap: wrap;\"> </div>\n\t\t\t\t\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.color_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Color</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<input id=\"materials.color.picker\" />\n\t\t\t\t</div>\n\n\n\t\t\t\t<div id=\"materials.elevation_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Elevation</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li><span data-i18n=\"appearance.elevation_range\"></span>: <span id=\"lblHeightRange\"></span> <div id=\"sldHeightRange\"></div>\t</li>\n\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<selectgroup id=\"gradient_repeat_option\">\n\t\t\t\t\t\t\t<option id=\"gradient_repeat_clamp\" value=\"CLAMP\">Clamp</option>\n\t\t\t\t\t\t\t<option id=\"gradient_repeat_repeat\" value=\"REPEAT\">Repeat</option>\n\t\t\t\t\t\t\t<option id=\"gradient_repeat_mirrored_repeat\" value=\"MIRRORED_REPEAT\">Mirrored Repeat</option>\n\t\t\t\t\t\t</selectgroup>\n\t\t\t\t\t</li>\n\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<span>Gradient Scheme:</span>\n\t\t\t\t\t\t<div id=\"elevation_gradient_scheme_selection\" style=\"display: flex; padding: 1em 0em\">\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.transition_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Transition</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li>transition: <span id=\"lblTransition\"></span> <div id=\"sldTransition\"></div>\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.intensity_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Intensity</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t\t<li>Range: <span id=\"lblIntensityRange\"></span> <div id=\"sldIntensityRange\"></div>\t</li>\n\t\t\t\t\t<li>Gamma: <span id=\"lblIntensityGamma\"></span> <div id=\"sldIntensityGamma\"></div>\t</li>\n\t\t\t\t\t<li>Brightness: <span id=\"lblIntensityBrightness\"></span> <div id=\"sldIntensityBrightness\"></div>\t</li>\n\t\t\t\t\t<li>Contrast: <span id=\"lblIntensityContrast\"></span> <div id=\"sldIntensityContrast\"></div>\t</li>\n\t\t\t\t</div>\n\n\t\t\t\t<div id=\"materials.gpstime_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>GPS Time</span>\n\t\t\t\t\t</div>\n\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<div id=\"materials.index_container\">\n\t\t\t\t\t<div class=\"divider\">\n\t\t\t\t\t\t<span>Indices</span>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\n\n\t\t\t\t</ul>\n\t\t\t</div>\n\t\t");
  57103. panel.i18n();
  57104. this.container.append(panel);
  57105. {
  57106. // POINT SIZE
  57107. var sldPointSize = panel.find("#sldPointSize");
  57108. var lblPointSize = panel.find("#lblPointSize");
  57109. sldPointSize.slider({
  57110. value: material.size,
  57111. min: 0,
  57112. max: 3,
  57113. step: 0.01,
  57114. slide: function slide(event, ui) {
  57115. material.size = ui.value;
  57116. }
  57117. });
  57118. var update = e => {
  57119. lblPointSize.html(material.size.toFixed(2));
  57120. sldPointSize.slider({
  57121. value: material.size
  57122. });
  57123. };
  57124. this.addVolatileListener(material, "point_size_changed", update);
  57125. update();
  57126. }
  57127. {
  57128. // MINIMUM POINT SIZE
  57129. var sldMinPointSize = panel.find("#sldMinPointSize");
  57130. var lblMinPointSize = panel.find("#lblMinPointSize");
  57131. sldMinPointSize.slider({
  57132. value: material.size,
  57133. min: 0,
  57134. max: 3,
  57135. step: 0.01,
  57136. slide: function slide(event, ui) {
  57137. material.minSize = ui.value;
  57138. }
  57139. });
  57140. var _update = e => {
  57141. lblMinPointSize.html(material.minSize.toFixed(2));
  57142. sldMinPointSize.slider({
  57143. value: material.minSize
  57144. });
  57145. };
  57146. this.addVolatileListener(material, "point_size_changed", _update);
  57147. _update();
  57148. }
  57149. {
  57150. // POINT SIZING
  57151. var strSizeType = Object.keys(PointSizeType)[material.pointSizeType];
  57152. var opt = panel.find("#optPointSizing");
  57153. opt.selectmenu();
  57154. opt.val(strSizeType).selectmenu('refresh');
  57155. opt.selectmenu({
  57156. change: (event, ui) => {
  57157. material.pointSizeType = PointSizeType[ui.item.value];
  57158. }
  57159. });
  57160. }
  57161. {
  57162. // SHAPE
  57163. var _opt = panel.find("#optShape");
  57164. _opt.selectmenu({
  57165. change: (event, ui) => {
  57166. var value = ui.item.value;
  57167. material.shape = PointShape$1[value];
  57168. }
  57169. });
  57170. var _update2 = () => {
  57171. var typename = Object.keys(PointShape$1)[material.shape];
  57172. _opt.selectmenu().val(typename).selectmenu('refresh');
  57173. };
  57174. this.addVolatileListener(material, "point_shape_changed", _update2);
  57175. _update2();
  57176. }
  57177. {
  57178. // BACKFACE CULLING
  57179. var _opt2 = panel.find("#set_backface_culling");
  57180. _opt2.click(() => {
  57181. material.backfaceCulling = _opt2.prop("checked");
  57182. });
  57183. var _update3 = () => {
  57184. var value = material.backfaceCulling;
  57185. _opt2.prop("checked", value);
  57186. };
  57187. this.addVolatileListener(material, "backface_changed", _update3);
  57188. _update3();
  57189. var blockBackface = $('#materials_backface_container');
  57190. blockBackface.css('display', 'none');
  57191. var pointAttributes = pointcloud.pcoGeometry.pointAttributes;
  57192. var hasNormals = pointAttributes.hasNormals ? pointAttributes.hasNormals() : false;
  57193. if (hasNormals) {
  57194. blockBackface.css('display', 'block');
  57195. }
  57196. /*
  57197. opt.checkboxradio({
  57198. clicked: (event, ui) => {
  57199. // let value = ui.item.value;
  57200. let value = ui.item.checked;
  57201. console.log(value);
  57202. material.backfaceCulling = value; // $('#set_freeze').prop("checked");
  57203. }
  57204. });
  57205. */
  57206. }
  57207. {
  57208. // OPACITY
  57209. var sldOpacity = panel.find("#sldOpacity");
  57210. var lblOpacity = panel.find("#lblOpacity");
  57211. sldOpacity.slider({
  57212. value: material.opacity,
  57213. min: 0,
  57214. max: 1,
  57215. step: 0.001,
  57216. slide: function slide(event, ui) {
  57217. material.opacity = ui.value;
  57218. }
  57219. });
  57220. var _update4 = e => {
  57221. lblOpacity.html(material.opacity.toFixed(2));
  57222. sldOpacity.slider({
  57223. value: material.opacity
  57224. });
  57225. };
  57226. this.addVolatileListener(material, "opacity_changed", _update4);
  57227. _update4();
  57228. }
  57229. {
  57230. var attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  57231. var options = [];
  57232. options.push(...attributes.map(a => a.name));
  57233. var intensityIndex = options.indexOf("intensity");
  57234. if (intensityIndex >= 0) {
  57235. options.splice(intensityIndex + 1, 0, "intensity gradient");
  57236. }
  57237. options.push("elevation", "color", 'matcap', 'indices', 'level of detail', 'composite');
  57238. var blacklist = ["POSITION_CARTESIAN", "position"];
  57239. options = options.filter(o => !blacklist.includes(o));
  57240. var attributeSelection = panel.find('#optMaterial');
  57241. for (var option of options) {
  57242. var elOption = $("<option>".concat(option, "</option>"));
  57243. attributeSelection.append(elOption);
  57244. }
  57245. var updateMaterialPanel = (event, ui) => {
  57246. var selectedValue = attributeSelection.selectmenu().val();
  57247. material.activeAttributeName = selectedValue;
  57248. var attribute = pointcloud.getAttribute(selectedValue);
  57249. if (selectedValue === "intensity gradient") {
  57250. attribute = pointcloud.getAttribute("intensity");
  57251. }
  57252. var isIntensity = attribute ? ["intensity", "intensity gradient"].includes(attribute.name) : false;
  57253. if (isIntensity) {
  57254. if (pointcloud.material.intensityRange[0] === Infinity) {
  57255. pointcloud.material.intensityRange = attribute.range;
  57256. }
  57257. var [min, max] = attribute.range;
  57258. panel.find('#sldIntensityRange').slider({
  57259. range: true,
  57260. min: min,
  57261. max: max,
  57262. step: 0.01,
  57263. values: [min, max],
  57264. slide: (event, ui) => {
  57265. var min = ui.values[0];
  57266. var max = ui.values[1];
  57267. material.intensityRange = [min, max];
  57268. }
  57269. });
  57270. } else if (attribute) {
  57271. var [_min, _max] = attribute.range;
  57272. var selectedRange = material.getRange(attribute.name);
  57273. if (!selectedRange) {
  57274. selectedRange = [...attribute.range];
  57275. }
  57276. var minMaxAreNumbers = typeof _min === "number" && typeof _max === "number";
  57277. if (minMaxAreNumbers) {
  57278. panel.find('#sldExtraRange').slider({
  57279. range: true,
  57280. min: _min,
  57281. max: _max,
  57282. step: 0.01,
  57283. values: selectedRange,
  57284. slide: (event, ui) => {
  57285. var [a, b] = ui.values;
  57286. material.setRange(attribute.name, [a, b]);
  57287. }
  57288. });
  57289. }
  57290. }
  57291. var blockWeights = $('#materials\\.composite_weight_container');
  57292. var blockElevation = $('#materials\\.elevation_container');
  57293. var blockRGB = $('#materials\\.rgb_container');
  57294. var blockExtra = $('#materials\\.extra_container');
  57295. var blockColor = $('#materials\\.color_container');
  57296. var blockIntensity = $('#materials\\.intensity_container');
  57297. var blockIndex = $('#materials\\.index_container');
  57298. var blockTransition = $('#materials\\.transition_container');
  57299. var blockGps = $('#materials\\.gpstime_container');
  57300. var blockMatcap = $('#materials\\.matcap_container');
  57301. blockIndex.css('display', 'none');
  57302. blockIntensity.css('display', 'none');
  57303. blockElevation.css('display', 'none');
  57304. blockRGB.css('display', 'none');
  57305. blockExtra.css('display', 'none');
  57306. blockColor.css('display', 'none');
  57307. blockWeights.css('display', 'none');
  57308. blockTransition.css('display', 'none');
  57309. blockMatcap.css('display', 'none');
  57310. blockGps.css('display', 'none');
  57311. if (selectedValue === 'composite') {
  57312. blockWeights.css('display', 'block');
  57313. blockElevation.css('display', 'block');
  57314. blockRGB.css('display', 'block');
  57315. blockIntensity.css('display', 'block');
  57316. } else if (selectedValue === 'elevation') {
  57317. blockElevation.css('display', 'block');
  57318. } else if (selectedValue === 'RGB and Elevation') {
  57319. blockRGB.css('display', 'block');
  57320. blockElevation.css('display', 'block');
  57321. } else if (selectedValue === 'rgba') {
  57322. blockRGB.css('display', 'block');
  57323. } else if (selectedValue === 'color') {
  57324. blockColor.css('display', 'block');
  57325. } else if (selectedValue === 'intensity') {
  57326. blockIntensity.css('display', 'block');
  57327. } else if (selectedValue === 'intensity gradient') {
  57328. blockIntensity.css('display', 'block');
  57329. } else if (selectedValue === "indices") {
  57330. blockIndex.css('display', 'block');
  57331. } else if (selectedValue === "matcap") {
  57332. blockMatcap.css('display', 'block');
  57333. } else if (selectedValue === "classification") {
  57334. // add classification color selctor?
  57335. } else if (selectedValue === "gps-time") {
  57336. blockGps.css('display', 'block');
  57337. } else if (selectedValue === "number of returns") {} else if (selectedValue === "return number") {} else if (["source id", "point source id"].includes(selectedValue)) {} else {
  57338. blockExtra.css('display', 'block');
  57339. }
  57340. };
  57341. attributeSelection.selectmenu({
  57342. change: updateMaterialPanel
  57343. });
  57344. var _update5 = () => {
  57345. attributeSelection.val(material.activeAttributeName).selectmenu('refresh');
  57346. };
  57347. this.addVolatileListener(material, "point_color_type_changed", _update5);
  57348. this.addVolatileListener(material, "active_attribute_changed", _update5);
  57349. _update5();
  57350. updateMaterialPanel();
  57351. }
  57352. {
  57353. var schemes = Object.keys(Potree.Gradients).map(name => ({
  57354. name: name,
  57355. values: Gradients[name]
  57356. }));
  57357. var elSchemeContainer = panel.find("#elevation_gradient_scheme_selection");
  57358. var _loop = function _loop(scheme) {
  57359. var elScheme = $("\n\t\t\t\t\t<span style=\"flex-grow: 1;\">\n\t\t\t\t\t</span>\n\t\t\t\t");
  57360. var svg = Potree.Utils.createSvgGradient(scheme.values);
  57361. svg.setAttributeNS(null, "class", "button-icon");
  57362. elScheme.append($(svg));
  57363. elScheme.click(() => {
  57364. material.gradient = Gradients[scheme.name];
  57365. });
  57366. elSchemeContainer.append(elScheme);
  57367. };
  57368. for (var scheme of schemes) {
  57369. _loop(scheme);
  57370. }
  57371. }
  57372. {
  57373. var matcaps = [{
  57374. name: "Normals",
  57375. icon: "".concat(Potree.resourcePath, "/icons/matcap/check_normal+y.jpg")
  57376. }, {
  57377. name: "Basic 1",
  57378. icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_1.jpg")
  57379. }, {
  57380. name: "Basic 2",
  57381. icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_2.jpg")
  57382. }, {
  57383. name: "Basic Dark",
  57384. icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_dark.jpg")
  57385. }, {
  57386. name: "Basic Side",
  57387. icon: "".concat(Potree.resourcePath, "/icons/matcap/basic_side.jpg")
  57388. }, {
  57389. name: "Ceramic Dark",
  57390. icon: "".concat(Potree.resourcePath, "/icons/matcap/ceramic_dark.jpg")
  57391. }, {
  57392. name: "Ceramic Lightbulb",
  57393. icon: "".concat(Potree.resourcePath, "/icons/matcap/ceramic_lightbulb.jpg")
  57394. }, {
  57395. name: "Clay Brown",
  57396. icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_brown.jpg")
  57397. }, {
  57398. name: "Clay Muddy",
  57399. icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_muddy.jpg")
  57400. }, {
  57401. name: "Clay Studio",
  57402. icon: "".concat(Potree.resourcePath, "/icons/matcap/clay_studio.jpg")
  57403. }, {
  57404. name: "Resin",
  57405. icon: "".concat(Potree.resourcePath, "/icons/matcap/resin.jpg")
  57406. }, {
  57407. name: "Skin",
  57408. icon: "".concat(Potree.resourcePath, "/icons/matcap/skin.jpg")
  57409. }, {
  57410. name: "Jade",
  57411. icon: "".concat(Potree.resourcePath, "/icons/matcap/jade.jpg")
  57412. }, {
  57413. name: "Metal_ Anisotropic",
  57414. icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_anisotropic.jpg")
  57415. }, {
  57416. name: "Metal Carpaint",
  57417. icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_carpaint.jpg")
  57418. }, {
  57419. name: "Metal Lead",
  57420. icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_lead.jpg")
  57421. }, {
  57422. name: "Metal Shiny",
  57423. icon: "".concat(Potree.resourcePath, "/icons/matcap/metal_shiny.jpg")
  57424. }, {
  57425. name: "Pearl",
  57426. icon: "".concat(Potree.resourcePath, "/icons/matcap/pearl.jpg")
  57427. }, {
  57428. name: "Toon",
  57429. icon: "".concat(Potree.resourcePath, "/icons/matcap/toon.jpg")
  57430. }, {
  57431. name: "Check Rim Light",
  57432. icon: "".concat(Potree.resourcePath, "/icons/matcap/check_rim_light.jpg")
  57433. }, {
  57434. name: "Check Rim Dark",
  57435. icon: "".concat(Potree.resourcePath, "/icons/matcap/check_rim_dark.jpg")
  57436. }, {
  57437. name: "Contours 1",
  57438. icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_1.jpg")
  57439. }, {
  57440. name: "Contours 2",
  57441. icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_2.jpg")
  57442. }, {
  57443. name: "Contours 3",
  57444. icon: "".concat(Potree.resourcePath, "/icons/matcap/contours_3.jpg")
  57445. }, {
  57446. name: "Reflection Check Horizontal",
  57447. icon: "".concat(Potree.resourcePath, "/icons/matcap/reflection_check_horizontal.jpg")
  57448. }, {
  57449. name: "Reflection Check Vertical",
  57450. icon: "".concat(Potree.resourcePath, "/icons/matcap/reflection_check_vertical.jpg")
  57451. }];
  57452. var elMatcapContainer = panel.find("#matcap_scheme_selection");
  57453. var _loop2 = function _loop2(matcap) {
  57454. var elMatcap = $("\n\t\t\t\t\t\t<img src=\"".concat(matcap.icon, "\" class=\"button-icon\" style=\"width: 25%;\" />\n\t\t\t\t"));
  57455. elMatcap.click(() => {
  57456. material.matcap = matcap.icon.substring(matcap.icon.lastIndexOf('/'));
  57457. });
  57458. elMatcapContainer.append(elMatcap);
  57459. };
  57460. for (var matcap of matcaps) {
  57461. _loop2(matcap);
  57462. }
  57463. }
  57464. {
  57465. panel.find('#sldRGBGamma').slider({
  57466. value: material.rgbGamma,
  57467. min: 0,
  57468. max: 4,
  57469. step: 0.01,
  57470. slide: (event, ui) => {
  57471. material.rgbGamma = ui.value;
  57472. }
  57473. });
  57474. panel.find('#sldRGBContrast').slider({
  57475. value: material.rgbContrast,
  57476. min: -1,
  57477. max: 1,
  57478. step: 0.01,
  57479. slide: (event, ui) => {
  57480. material.rgbContrast = ui.value;
  57481. }
  57482. });
  57483. panel.find('#sldRGBBrightness').slider({
  57484. value: material.rgbBrightness,
  57485. min: -1,
  57486. max: 1,
  57487. step: 0.01,
  57488. slide: (event, ui) => {
  57489. material.rgbBrightness = ui.value;
  57490. }
  57491. });
  57492. panel.find('#sldExtraGamma').slider({
  57493. value: material.extraGamma,
  57494. min: 0,
  57495. max: 4,
  57496. step: 0.01,
  57497. slide: (event, ui) => {
  57498. material.extraGamma = ui.value;
  57499. }
  57500. });
  57501. panel.find('#sldExtraBrightness').slider({
  57502. value: material.extraBrightness,
  57503. min: -1,
  57504. max: 1,
  57505. step: 0.01,
  57506. slide: (event, ui) => {
  57507. material.extraBrightness = ui.value;
  57508. }
  57509. });
  57510. panel.find('#sldExtraContrast').slider({
  57511. value: material.extraContrast,
  57512. min: -1,
  57513. max: 1,
  57514. step: 0.01,
  57515. slide: (event, ui) => {
  57516. material.extraContrast = ui.value;
  57517. }
  57518. });
  57519. panel.find('#sldHeightRange').slider({
  57520. range: true,
  57521. min: 0,
  57522. max: 1000,
  57523. step: 0.01,
  57524. values: [0, 1000],
  57525. slide: (event, ui) => {
  57526. material.heightMin = ui.values[0];
  57527. material.heightMax = ui.values[1];
  57528. }
  57529. });
  57530. panel.find('#sldIntensityGamma').slider({
  57531. value: material.intensityGamma,
  57532. min: 0,
  57533. max: 4,
  57534. step: 0.01,
  57535. slide: (event, ui) => {
  57536. material.intensityGamma = ui.value;
  57537. }
  57538. });
  57539. panel.find('#sldIntensityContrast').slider({
  57540. value: material.intensityContrast,
  57541. min: -1,
  57542. max: 1,
  57543. step: 0.01,
  57544. slide: (event, ui) => {
  57545. material.intensityContrast = ui.value;
  57546. }
  57547. });
  57548. panel.find('#sldIntensityBrightness').slider({
  57549. value: material.intensityBrightness,
  57550. min: -1,
  57551. max: 1,
  57552. step: 0.01,
  57553. slide: (event, ui) => {
  57554. material.intensityBrightness = ui.value;
  57555. }
  57556. });
  57557. panel.find('#sldWeightRGB').slider({
  57558. value: material.weightRGB,
  57559. min: 0,
  57560. max: 1,
  57561. step: 0.01,
  57562. slide: (event, ui) => {
  57563. material.weightRGB = ui.value;
  57564. }
  57565. });
  57566. panel.find('#sldWeightIntensity').slider({
  57567. value: material.weightIntensity,
  57568. min: 0,
  57569. max: 1,
  57570. step: 0.01,
  57571. slide: (event, ui) => {
  57572. material.weightIntensity = ui.value;
  57573. }
  57574. });
  57575. panel.find('#sldWeightElevation').slider({
  57576. value: material.weightElevation,
  57577. min: 0,
  57578. max: 1,
  57579. step: 0.01,
  57580. slide: (event, ui) => {
  57581. material.weightElevation = ui.value;
  57582. }
  57583. });
  57584. panel.find('#sldWeightClassification').slider({
  57585. value: material.weightClassification,
  57586. min: 0,
  57587. max: 1,
  57588. step: 0.01,
  57589. slide: (event, ui) => {
  57590. material.weightClassification = ui.value;
  57591. }
  57592. });
  57593. panel.find('#sldWeightReturnNumber').slider({
  57594. value: material.weightReturnNumber,
  57595. min: 0,
  57596. max: 1,
  57597. step: 0.01,
  57598. slide: (event, ui) => {
  57599. material.weightReturnNumber = ui.value;
  57600. }
  57601. });
  57602. panel.find('#sldWeightSourceID').slider({
  57603. value: material.weightSourceID,
  57604. min: 0,
  57605. max: 1,
  57606. step: 0.01,
  57607. slide: (event, ui) => {
  57608. material.weightSourceID = ui.value;
  57609. }
  57610. });
  57611. panel.find("#materials\\.color\\.picker").spectrum({
  57612. flat: true,
  57613. showInput: true,
  57614. preferredFormat: 'rgb',
  57615. cancelText: '',
  57616. chooseText: 'Apply',
  57617. color: "#".concat(material.color.getHexString()),
  57618. move: color => {
  57619. var cRGB = color.toRgb();
  57620. var tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  57621. material.color = tc;
  57622. },
  57623. change: color => {
  57624. var cRGB = color.toRgb();
  57625. var tc = new Color().setRGB(cRGB.r / 255, cRGB.g / 255, cRGB.b / 255);
  57626. material.color = tc;
  57627. }
  57628. });
  57629. this.addVolatileListener(material, "color_changed", () => {
  57630. panel.find("#materials\\.color\\.picker").spectrum('set', "#".concat(material.color.getHexString()));
  57631. });
  57632. var updateHeightRange = function updateHeightRange() {
  57633. var aPosition = pointcloud.getAttribute("position");
  57634. var bMin, bMax;
  57635. if (aPosition) {
  57636. // for new format 2.0 and loader that contain precomputed min/max of attributes
  57637. var min = aPosition.range[0][2];
  57638. var max = aPosition.range[1][2];
  57639. var width = max - min;
  57640. bMin = min - 0.2 * width;
  57641. bMax = max + 0.2 * width;
  57642. } else {
  57643. // for format up until exlusive 2.0
  57644. var box = [pointcloud.pcoGeometry.tightBoundingBox, pointcloud.getBoundingBoxWorld()].find(v => v !== undefined);
  57645. pointcloud.updateMatrixWorld(true);
  57646. box = Utils.computeTransformedBoundingBox(box, pointcloud.matrixWorld);
  57647. var bWidth = box.max.z - box.min.z;
  57648. bMin = box.min.z - 0.2 * bWidth;
  57649. bMax = box.max.z + 0.2 * bWidth;
  57650. }
  57651. var range = material.elevationRange;
  57652. panel.find('#lblHeightRange').html("".concat(range[0].toFixed(2), " to ").concat(range[1].toFixed(2)));
  57653. panel.find('#sldHeightRange').slider({
  57654. min: bMin,
  57655. max: bMax,
  57656. values: range
  57657. });
  57658. };
  57659. var updateExtraRange = function updateExtraRange() {
  57660. var attributeName = material.activeAttributeName;
  57661. var attribute = pointcloud.getAttribute(attributeName);
  57662. if (attribute == null) {
  57663. return;
  57664. }
  57665. var range = material.getRange(attributeName);
  57666. if (range == null) {
  57667. range = attribute.range;
  57668. }
  57669. // currently only supporting scalar ranges.
  57670. // rgba, normals, positions, etc have vector ranges, however
  57671. var isValidRange = typeof range[0] === "number" && typeof range[1] === "number";
  57672. if (!isValidRange) {
  57673. return;
  57674. }
  57675. if (range) {
  57676. var msg = "".concat(range[0].toFixed(2), " to ").concat(range[1].toFixed(2));
  57677. panel.find('#lblExtraRange').html(msg);
  57678. } else {
  57679. panel.find("could not deduce range");
  57680. }
  57681. };
  57682. var updateIntensityRange = function updateIntensityRange() {
  57683. var range = material.intensityRange;
  57684. panel.find('#lblIntensityRange').html("".concat(parseInt(range[0]), " to ").concat(parseInt(range[1])));
  57685. };
  57686. {
  57687. updateHeightRange();
  57688. panel.find("#sldHeightRange").slider('option', 'min');
  57689. panel.find("#sldHeightRange").slider('option', 'max');
  57690. }
  57691. {
  57692. var elGradientRepeat = panel.find("#gradient_repeat_option");
  57693. elGradientRepeat.selectgroup({
  57694. title: "Gradient"
  57695. });
  57696. elGradientRepeat.find("input").click(e => {
  57697. this.viewer.setElevationGradientRepeat(ElevationGradientRepeat[e.target.value]);
  57698. });
  57699. var current = Object.keys(ElevationGradientRepeat).filter(key => ElevationGradientRepeat[key] === this.viewer.elevationGradientRepeat);
  57700. elGradientRepeat.find("input[value=".concat(current, "]")).trigger("click");
  57701. }
  57702. var onIntensityChange = () => {
  57703. var gamma = material.intensityGamma;
  57704. var contrast = material.intensityContrast;
  57705. var brightness = material.intensityBrightness;
  57706. updateIntensityRange();
  57707. panel.find('#lblIntensityGamma').html(gamma.toFixed(2));
  57708. panel.find('#lblIntensityContrast').html(contrast.toFixed(2));
  57709. panel.find('#lblIntensityBrightness').html(brightness.toFixed(2));
  57710. panel.find('#sldIntensityGamma').slider({
  57711. value: gamma
  57712. });
  57713. panel.find('#sldIntensityContrast').slider({
  57714. value: contrast
  57715. });
  57716. panel.find('#sldIntensityBrightness').slider({
  57717. value: brightness
  57718. });
  57719. };
  57720. var onRGBChange = () => {
  57721. var gamma = material.rgbGamma;
  57722. var contrast = material.rgbContrast;
  57723. var brightness = material.rgbBrightness;
  57724. panel.find('#lblRGBGamma').html(gamma.toFixed(2));
  57725. panel.find('#lblRGBContrast').html(contrast.toFixed(2));
  57726. panel.find('#lblRGBBrightness').html(brightness.toFixed(2));
  57727. panel.find('#sldRGBGamma').slider({
  57728. value: gamma
  57729. });
  57730. panel.find('#sldRGBContrast').slider({
  57731. value: contrast
  57732. });
  57733. panel.find('#sldRGBBrightness').slider({
  57734. value: brightness
  57735. });
  57736. };
  57737. this.addVolatileListener(material, "material_property_changed", updateExtraRange);
  57738. this.addVolatileListener(material, "material_property_changed", updateHeightRange);
  57739. this.addVolatileListener(material, "material_property_changed", onIntensityChange);
  57740. this.addVolatileListener(material, "material_property_changed", onRGBChange);
  57741. updateExtraRange();
  57742. updateHeightRange();
  57743. onIntensityChange();
  57744. onRGBChange();
  57745. }
  57746. }
  57747. setMeasurement(object) {
  57748. var TYPE = {
  57749. DISTANCE: {
  57750. panel: DistancePanel
  57751. },
  57752. AREA: {
  57753. panel: AreaPanel
  57754. },
  57755. POINT: {
  57756. panel: PointPanel
  57757. },
  57758. ANGLE: {
  57759. panel: AnglePanel
  57760. },
  57761. HEIGHT: {
  57762. panel: HeightPanel
  57763. },
  57764. PROFILE: {
  57765. panel: ProfilePanel
  57766. },
  57767. VOLUME: {
  57768. panel: VolumePanel
  57769. },
  57770. CIRCLE: {
  57771. panel: CirclePanel
  57772. },
  57773. OTHER: {
  57774. panel: PointPanel
  57775. }
  57776. };
  57777. var getType = measurement => {
  57778. if (measurement instanceof Measure) {
  57779. if (measurement.showDistances && !measurement.showArea && !measurement.showAngles) {
  57780. return TYPE.DISTANCE;
  57781. } else if (measurement.showDistances && measurement.showArea && !measurement.showAngles) {
  57782. return TYPE.AREA;
  57783. } else if (measurement.maxMarkers === 1) {
  57784. return TYPE.POINT;
  57785. } else if (!measurement.showDistances && !measurement.showArea && measurement.showAngles) {
  57786. return TYPE.ANGLE;
  57787. } else if (measurement.showHeight) {
  57788. return TYPE.HEIGHT;
  57789. } else if (measurement.showCircle) {
  57790. return TYPE.CIRCLE;
  57791. } else {
  57792. return TYPE.OTHER;
  57793. }
  57794. } else if (measurement instanceof Profile) {
  57795. return TYPE.PROFILE;
  57796. } else if (measurement instanceof Volume) {
  57797. return TYPE.VOLUME;
  57798. }
  57799. };
  57800. //this.container.html("measurement");
  57801. var type = getType(object);
  57802. var Panel = type.panel;
  57803. var panel = new Panel(this.viewer, object, this);
  57804. this.container.append(panel.elContent);
  57805. }
  57806. setCamera(camera) {
  57807. var panel = new CameraPanel(this.viewer, this);
  57808. this.container.append(panel.elContent);
  57809. }
  57810. setAnnotation(annotation) {
  57811. var panel = new AnnotationPanel(this.viewer, this, annotation);
  57812. this.container.append(panel.elContent);
  57813. }
  57814. setCameraAnimation(animation) {
  57815. var panel = new CameraAnimationPanel(this.viewer, this, animation);
  57816. this.container.append(panel.elContent);
  57817. }
  57818. }
  57819. function addCommas(nStr) {
  57820. nStr += '';
  57821. var x = nStr.split('.');
  57822. var x1 = x[0];
  57823. var x2 = x.length > 1 ? '.' + x[1] : '';
  57824. var rgx = /(\d+)(\d{3})/;
  57825. while (rgx.test(x1)) {
  57826. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  57827. }
  57828. return x1 + x2;
  57829. }
  57830. ;
  57831. function format(value) {
  57832. return addCommas(value.toFixed(3));
  57833. }
  57834. ;
  57835. class HierarchicalSlider {
  57836. constructor() {
  57837. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  57838. this.element = document.createElement("div");
  57839. this.labels = [];
  57840. this.sliders = [];
  57841. this.range = params.range != null ? params.range : [0, 1];
  57842. this.slide = params.slide != null ? params.slide : null;
  57843. this.step = params.step != null ? params.step : 0.0001;
  57844. var levels = params.levels != null ? params.levels : 1;
  57845. for (var level = 0; level < levels; level++) {
  57846. this.addLevel();
  57847. }
  57848. }
  57849. setRange(range) {
  57850. this.range = [...range];
  57851. {
  57852. // root slider
  57853. var slider = this.sliders[0];
  57854. $(slider).slider({
  57855. min: range[0],
  57856. max: range[1]
  57857. });
  57858. }
  57859. for (var i = 1; i < this.sliders.length; i++) {
  57860. var parentSlider = this.sliders[i - 1];
  57861. var _slider = this.sliders[i];
  57862. var parentValues = $(parentSlider).slider("option", "values");
  57863. var childRange = [...parentValues];
  57864. $(_slider).slider({
  57865. min: childRange[0],
  57866. max: childRange[1]
  57867. });
  57868. }
  57869. this.updateLabels();
  57870. }
  57871. setValues(values) {
  57872. for (var slider of this.sliders) {
  57873. $(slider).slider({
  57874. values: [...values]
  57875. });
  57876. }
  57877. this.updateLabels();
  57878. }
  57879. addLevel() {
  57880. var elLevel = document.createElement("li");
  57881. var elRange = document.createTextNode("Range: ");
  57882. var label = document.createElement("span");
  57883. var slider = document.createElement("div");
  57884. var level = this.sliders.length;
  57885. var [min, max] = [0, 0];
  57886. if (this.sliders.length === 0) {
  57887. [min, max] = this.range;
  57888. } else {
  57889. var parentSlider = this.sliders[this.sliders.length - 1];
  57890. [min, max] = $(parentSlider).slider("option", "values");
  57891. }
  57892. $(slider).slider({
  57893. range: true,
  57894. min: min,
  57895. max: max,
  57896. step: this.step,
  57897. values: [min, max],
  57898. slide: (event, ui) => {
  57899. // set all descendants to same range
  57900. var levels = this.sliders.length;
  57901. for (var i = level + 1; i < levels; i++) {
  57902. var descendant = this.sliders[i];
  57903. $(descendant).slider({
  57904. range: true,
  57905. min: ui.values[0],
  57906. max: ui.values[1],
  57907. values: [...ui.values]
  57908. });
  57909. }
  57910. if (this.slide) {
  57911. var values = [...ui.values];
  57912. this.slide({
  57913. target: this,
  57914. range: this.range,
  57915. values: values
  57916. });
  57917. }
  57918. this.updateLabels();
  57919. }
  57920. });
  57921. elLevel.append(elRange, label, slider);
  57922. this.sliders.push(slider);
  57923. this.labels.push(label);
  57924. this.element.append(elLevel);
  57925. this.updateLabels();
  57926. }
  57927. removeLevel() {}
  57928. updateSliders() {}
  57929. updateLabels() {
  57930. var levels = this.sliders.length;
  57931. for (var i = 0; i < levels; i++) {
  57932. var slider = this.sliders[i];
  57933. var label = this.labels[i];
  57934. var [min, max] = $(slider).slider("option", "values");
  57935. var strMin = format(min);
  57936. var strMax = format(max);
  57937. var strLabel = "".concat(strMin, " to ").concat(strMax);
  57938. label.innerHTML = strLabel;
  57939. }
  57940. }
  57941. }
  57942. class OrientedImageControls extends EventDispatcher$1 {
  57943. constructor(viewer) {
  57944. super();
  57945. this.viewer = viewer;
  57946. this.renderer = viewer.renderer;
  57947. this.originalCam = viewer.scene.getActiveCamera();
  57948. this.shearCam = viewer.scene.getActiveCamera().clone();
  57949. this.shearCam.rotation.set(this.originalCam.rotation.toArray());
  57950. this.shearCam.updateProjectionMatrix();
  57951. this.shearCam.updateProjectionMatrix = () => {
  57952. return this.shearCam.projectionMatrix;
  57953. };
  57954. this.image = null;
  57955. this.fadeFactor = 20;
  57956. this.fovDelta = 0;
  57957. this.fovMin = 0.1;
  57958. this.fovMax = 120;
  57959. this.shear = [0, 0];
  57960. // const style = ``;
  57961. this.elUp = $("<input type=\"button\" value=\"\uD83E\uDC45\" style=\"position: absolute; top: 10px; left: calc(50%); z-index: 1000\" />");
  57962. this.elRight = $("<input type=\"button\" value=\"\uD83E\uDC46\" style=\"position: absolute; top: calc(50%); right: 10px; z-index: 1000\" />");
  57963. this.elDown = $("<input type=\"button\" value=\"\uD83E\uDC47\" style=\"position: absolute; bottom: 10px; left: calc(50%); z-index: 1000\" />");
  57964. this.elLeft = $("<input type=\"button\" value=\"\uD83E\uDC44\" style=\"position: absolute; top: calc(50%); left: 10px; z-index: 1000\" />");
  57965. this.elExit = $("<input type=\"button\" value=\"Back to 3D view\" style=\"position: absolute; bottom: 10px; right: 10px; z-index: 1000\" />");
  57966. this.elExit.click(() => {
  57967. this.release();
  57968. });
  57969. this.elUp.click(() => {
  57970. var fovY = viewer.getFOV();
  57971. var top = Math.tan(MathUtils.degToRad(fovY / 2));
  57972. this.shear[1] += 0.1 * top;
  57973. });
  57974. this.elRight.click(() => {
  57975. var fovY = viewer.getFOV();
  57976. var top = Math.tan(MathUtils.degToRad(fovY / 2));
  57977. this.shear[0] += 0.1 * top;
  57978. });
  57979. this.elDown.click(() => {
  57980. var fovY = viewer.getFOV();
  57981. var top = Math.tan(MathUtils.degToRad(fovY / 2));
  57982. this.shear[1] -= 0.1 * top;
  57983. });
  57984. this.elLeft.click(() => {
  57985. var fovY = viewer.getFOV();
  57986. var top = Math.tan(MathUtils.degToRad(fovY / 2));
  57987. this.shear[0] -= 0.1 * top;
  57988. });
  57989. this.scene = null;
  57990. this.sceneControls = new Scene();
  57991. var scroll = e => {
  57992. this.fovDelta += -e.delta * 1.0;
  57993. };
  57994. this.addEventListener('mousewheel', scroll);
  57995. //this.addEventListener("mousemove", onMove);
  57996. }
  57997. hasSomethingCaptured() {
  57998. return this.image !== null;
  57999. }
  58000. capture(image) {
  58001. if (this.hasSomethingCaptured()) {
  58002. return;
  58003. }
  58004. this.image = image;
  58005. this.originalFOV = this.viewer.getFOV();
  58006. this.originalControls = this.viewer.getControls();
  58007. this.viewer.setControls(this);
  58008. this.viewer.scene.overrideCamera = this.shearCam;
  58009. var elCanvas = this.viewer.renderer.domElement;
  58010. var elRoot = $(elCanvas.parentElement);
  58011. this.shear = [0, 0];
  58012. elRoot.append(this.elUp);
  58013. elRoot.append(this.elRight);
  58014. elRoot.append(this.elDown);
  58015. elRoot.append(this.elLeft);
  58016. elRoot.append(this.elExit);
  58017. }
  58018. release() {
  58019. this.image = null;
  58020. this.viewer.scene.overrideCamera = null;
  58021. this.elUp.detach();
  58022. this.elRight.detach();
  58023. this.elDown.detach();
  58024. this.elLeft.detach();
  58025. this.elExit.detach();
  58026. this.viewer.setFOV(this.originalFOV);
  58027. this.viewer.setControls(this.originalControls);
  58028. }
  58029. setScene(scene) {
  58030. this.scene = scene;
  58031. }
  58032. update(delta) {
  58033. // const view = this.scene.view;
  58034. // let prevTotal = this.shearCam.projectionMatrix.elements.reduce( (a, i) => a + i, 0);
  58035. //const progression = Math.min(1, this.fadeFactor * delta);
  58036. //const attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  58037. var progression = 1;
  58038. var attenuation = 0;
  58039. var oldFov = this.viewer.getFOV();
  58040. var fovProgression = progression * this.fovDelta;
  58041. var newFov = oldFov * (1 + fovProgression / 10);
  58042. newFov = Math.max(this.fovMin, newFov);
  58043. newFov = Math.min(this.fovMax, newFov);
  58044. var diff = newFov / oldFov;
  58045. var mouse = this.viewer.inputHandler.mouse;
  58046. var canvasSize = this.viewer.renderer.getSize(new Vector2());
  58047. var uv = [mouse.x / canvasSize.x, (canvasSize.y - mouse.y) / canvasSize.y];
  58048. var fovY = newFov;
  58049. var aspect = canvasSize.x / canvasSize.y;
  58050. var top = Math.tan(MathUtils.degToRad(fovY / 2));
  58051. var height = 2 * top;
  58052. var width = aspect * height;
  58053. var shearRangeX = [this.shear[0] - 0.5 * width, this.shear[0] + 0.5 * width];
  58054. var shearRangeY = [this.shear[1] - 0.5 * height, this.shear[1] + 0.5 * height];
  58055. var shx = (1 - uv[0]) * shearRangeX[0] + uv[0] * shearRangeX[1];
  58056. var shy = (1 - uv[1]) * shearRangeY[0] + uv[1] * shearRangeY[1];
  58057. var shu = 1 - diff;
  58058. var newShear = [(1 - shu) * this.shear[0] + shu * shx, (1 - shu) * this.shear[1] + shu * shy];
  58059. this.shear = newShear;
  58060. this.viewer.setFOV(newFov);
  58061. var {
  58062. originalCam,
  58063. shearCam
  58064. } = this;
  58065. originalCam.fov = newFov;
  58066. originalCam.updateMatrixWorld();
  58067. originalCam.updateProjectionMatrix();
  58068. shearCam.copy(originalCam);
  58069. shearCam.rotation.set(...originalCam.rotation.toArray());
  58070. shearCam.updateMatrixWorld();
  58071. shearCam.projectionMatrix.copy(originalCam.projectionMatrix);
  58072. var [sx, sy] = this.shear;
  58073. var mShear = new Matrix4().set(1, 0, sx, 0, 0, 1, sy, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  58074. var proj = shearCam.projectionMatrix;
  58075. proj.multiply(mShear);
  58076. shearCam.projectionMatrixInverse.copy(proj).invert();
  58077. var total = shearCam.projectionMatrix.elements.reduce((a, i) => a + i, 0);
  58078. this.fovDelta *= attenuation;
  58079. }
  58080. }
  58081. ;
  58082. // https://support.pix4d.com/hc/en-us/articles/205675256-How-are-yaw-pitch-roll-defined
  58083. // https://support.pix4d.com/hc/en-us/articles/202558969-How-are-omega-phi-kappa-defined
  58084. function createMaterial() {
  58085. var vertexShader = "\n\tuniform float uNear;\n\tvarying vec2 vUV;\n\tvarying vec4 vDebug;\n\t\n\tvoid main(){\n\t\tvDebug = vec4(0.0, 1.0, 0.0, 1.0);\n\t\tvec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);\n\t\t// make sure that this mesh is at least in front of the near plane\n\t\tmodelViewPosition.xyz += normalize(modelViewPosition.xyz) * uNear;\n\t\tgl_Position = projectionMatrix * modelViewPosition;\n\t\tvUV = uv;\n\t}\n\t";
  58086. var fragmentShader = "\n\tuniform sampler2D tColor;\n\tuniform float uOpacity;\n\tvarying vec2 vUV;\n\tvarying vec4 vDebug;\n\tvoid main(){\n\t\tvec4 color = texture2D(tColor, vUV);\n\t\tgl_FragColor = color;\n\t\tgl_FragColor.a = uOpacity;\n\t}\n\t";
  58087. var material = new ShaderMaterial({
  58088. uniforms: {
  58089. // time: { value: 1.0 },
  58090. // resolution: { value: new THREE.Vector2() }
  58091. tColor: {
  58092. value: new Texture()
  58093. },
  58094. uNear: {
  58095. value: 0.0
  58096. },
  58097. uOpacity: {
  58098. value: 1.0
  58099. }
  58100. },
  58101. vertexShader: vertexShader,
  58102. fragmentShader: fragmentShader,
  58103. side: DoubleSide
  58104. });
  58105. material.side = DoubleSide;
  58106. return material;
  58107. }
  58108. var planeGeometry = new PlaneGeometry(1, 1);
  58109. var lineGeometry = new Geometry();
  58110. lineGeometry.vertices.push(new Vector3(-0.5, -0.5, 0), new Vector3(0.5, -0.5, 0), new Vector3(0.5, 0.5, 0), new Vector3(-0.5, 0.5, 0), new Vector3(-0.5, -0.5, 0));
  58111. class OrientedImage {
  58112. constructor(id) {
  58113. this.id = id;
  58114. this.fov = 1.0;
  58115. this.position = new Vector3();
  58116. this.rotation = new Vector3();
  58117. this.width = 0;
  58118. this.height = 0;
  58119. this.fov = 1.0;
  58120. var material = createMaterial();
  58121. var lineMaterial = new LineBasicMaterial({
  58122. color: 0x00ff00
  58123. });
  58124. this.mesh = new Mesh(planeGeometry, material);
  58125. this.line = new Line(lineGeometry, lineMaterial);
  58126. this.texture = null;
  58127. this.mesh.orientedImage = this;
  58128. }
  58129. set(position, rotation, dimension, fov) {
  58130. var radians = rotation.map(MathUtils.degToRad);
  58131. this.position.set(...position);
  58132. this.mesh.position.set(...position);
  58133. this.rotation.set(...radians);
  58134. this.mesh.rotation.set(...radians);
  58135. [this.width, this.height] = dimension;
  58136. this.mesh.scale.set(this.width / this.height, 1, 1);
  58137. this.fov = fov;
  58138. this.updateTransform();
  58139. }
  58140. updateTransform() {
  58141. var {
  58142. mesh,
  58143. line,
  58144. fov
  58145. } = this;
  58146. mesh.updateMatrixWorld();
  58147. var dir = mesh.getWorldDirection();
  58148. var alpha = MathUtils.degToRad(fov / 2);
  58149. var d = -0.5 / Math.tan(alpha);
  58150. var move = dir.clone().multiplyScalar(d);
  58151. mesh.position.add(move);
  58152. line.position.copy(mesh.position);
  58153. line.scale.copy(mesh.scale);
  58154. line.rotation.copy(mesh.rotation);
  58155. }
  58156. }
  58157. ;
  58158. class OrientedImages extends EventDispatcher$1 {
  58159. constructor() {
  58160. super();
  58161. this.node = null;
  58162. this.cameraParams = null;
  58163. this.imageParams = null;
  58164. this.images = null;
  58165. this._visible = true;
  58166. }
  58167. set visible(visible) {
  58168. if (this._visible === visible) {
  58169. return;
  58170. }
  58171. for (var image of this.images) {
  58172. image.mesh.visible = visible;
  58173. image.line.visible = visible;
  58174. }
  58175. this._visible = visible;
  58176. this.dispatchEvent({
  58177. type: "visibility_changed",
  58178. images: this
  58179. });
  58180. }
  58181. get visible() {
  58182. return this._visible;
  58183. }
  58184. }
  58185. ;
  58186. class OrientedImageLoader {
  58187. static loadCameraParams(path) {
  58188. return _asyncToGenerator(function* () {
  58189. var res = yield fetch(path);
  58190. var text = yield res.text();
  58191. var parser = new DOMParser();
  58192. var doc = parser.parseFromString(text, "application/xml");
  58193. var width = parseInt(doc.getElementsByTagName("width")[0].textContent);
  58194. var height = parseInt(doc.getElementsByTagName("height")[0].textContent);
  58195. var f = parseFloat(doc.getElementsByTagName("f")[0].textContent);
  58196. var a = height / 2 / f;
  58197. var fov = 2 * MathUtils.radToDeg(Math.atan(a));
  58198. var params = {
  58199. path: path,
  58200. width: width,
  58201. height: height,
  58202. f: f,
  58203. fov: fov
  58204. };
  58205. return params;
  58206. })();
  58207. }
  58208. static loadImageParams(path) {
  58209. return _asyncToGenerator(function* () {
  58210. var response = yield fetch(path);
  58211. if (!response.ok) {
  58212. console.error("failed to load ".concat(path));
  58213. return;
  58214. }
  58215. var content = yield response.text();
  58216. var lines = content.split(/\r?\n/);
  58217. var imageParams = [];
  58218. for (var i = 1; i < lines.length; i++) {
  58219. var line = lines[i];
  58220. if (line.startsWith("#")) {
  58221. continue;
  58222. }
  58223. var tokens = line.split(/\s+/);
  58224. if (tokens.length < 6) {
  58225. continue;
  58226. }
  58227. var params = {
  58228. id: tokens[0],
  58229. x: Number.parseFloat(tokens[1]),
  58230. y: Number.parseFloat(tokens[2]),
  58231. z: Number.parseFloat(tokens[3]),
  58232. omega: Number.parseFloat(tokens[4]),
  58233. phi: Number.parseFloat(tokens[5]),
  58234. kappa: Number.parseFloat(tokens[6])
  58235. };
  58236. // const whitelist = ["47518.jpg"];
  58237. // if(whitelist.includes(params.id)){
  58238. // imageParams.push(params);
  58239. // }
  58240. imageParams.push(params);
  58241. }
  58242. // debug
  58243. //return [imageParams[50]];
  58244. return imageParams;
  58245. })();
  58246. }
  58247. static load(cameraParamsPath, imageParamsPath, viewer) {
  58248. return _asyncToGenerator(function* () {
  58249. var tStart = performance.now();
  58250. var [cameraParams, imageParams] = yield Promise.all([OrientedImageLoader.loadCameraParams(cameraParamsPath), OrientedImageLoader.loadImageParams(imageParamsPath)]);
  58251. var orientedImageControls = new OrientedImageControls(viewer);
  58252. var raycaster = new Raycaster();
  58253. var tEnd = performance.now();
  58254. console.log(tEnd - tStart);
  58255. // const sp = new THREE.PlaneGeometry(1, 1);
  58256. // const lg = new THREE.Geometry();
  58257. // lg.vertices.push(
  58258. // new THREE.Vector3(-0.5, -0.5, 0),
  58259. // new THREE.Vector3( 0.5, -0.5, 0),
  58260. // new THREE.Vector3( 0.5, 0.5, 0),
  58261. // new THREE.Vector3(-0.5, 0.5, 0),
  58262. // new THREE.Vector3(-0.5, -0.5, 0),
  58263. // );
  58264. var {
  58265. width,
  58266. height
  58267. } = cameraParams;
  58268. var orientedImages = [];
  58269. var sceneNode = new Object3D();
  58270. sceneNode.name = "oriented_images";
  58271. for (var params of imageParams) {
  58272. // const material = createMaterial();
  58273. // const lm = new THREE.LineBasicMaterial( { color: 0x00ff00 } );
  58274. // const mesh = new THREE.Mesh(sp, material);
  58275. var {
  58276. x,
  58277. y,
  58278. z,
  58279. omega,
  58280. phi,
  58281. kappa
  58282. } = params;
  58283. // const [rx, ry, rz] = [omega, phi, kappa]
  58284. // .map(THREE.Math.degToRad);
  58285. // mesh.position.set(x, y, z);
  58286. // mesh.scale.set(width / height, 1, 1);
  58287. // mesh.rotation.set(rx, ry, rz);
  58288. // {
  58289. // mesh.updateMatrixWorld();
  58290. // const dir = mesh.getWorldDirection();
  58291. // const alpha = THREE.Math.degToRad(cameraParams.fov / 2);
  58292. // const d = -0.5 / Math.tan(alpha);
  58293. // const move = dir.clone().multiplyScalar(d);
  58294. // mesh.position.add(move);
  58295. // }
  58296. // sceneNode.add(mesh);
  58297. // const line = new THREE.Line(lg, lm);
  58298. // line.position.copy(mesh.position);
  58299. // line.scale.copy(mesh.scale);
  58300. // line.rotation.copy(mesh.rotation);
  58301. // sceneNode.add(line);
  58302. var orientedImage = new OrientedImage(params.id);
  58303. // orientedImage.setPosition(x, y, z);
  58304. // orientedImage.setRotation(omega, phi, kappa);
  58305. // orientedImage.setDimension(width, height);
  58306. var position = [x, y, z];
  58307. var rotation = [omega, phi, kappa];
  58308. var dimension = [width, height];
  58309. orientedImage.set(position, rotation, dimension, cameraParams.fov);
  58310. sceneNode.add(orientedImage.mesh);
  58311. sceneNode.add(orientedImage.line);
  58312. orientedImages.push(orientedImage);
  58313. }
  58314. var hoveredElement = null;
  58315. var clipVolume = null;
  58316. var onMouseMove = evt => {
  58317. var tStart = performance.now();
  58318. if (hoveredElement) {
  58319. hoveredElement.line.material.color.setRGB(0, 1, 0);
  58320. }
  58321. evt.preventDefault();
  58322. //var array = getMousePosition( container, evt.clientX, evt.clientY );
  58323. var rect = viewer.renderer.domElement.getBoundingClientRect();
  58324. var [x, y] = [evt.clientX, evt.clientY];
  58325. var array = [(x - rect.left) / rect.width, (y - rect.top) / rect.height];
  58326. var onClickPosition = new Vector2(...array);
  58327. //const intersects = getIntersects(onClickPosition, scene.children);
  58328. var camera = viewer.scene.getActiveCamera();
  58329. var mouse = new Vector3(+(onClickPosition.x * 2) - 1, -(onClickPosition.y * 2) + 1);
  58330. var objects = orientedImages.map(i => i.mesh);
  58331. raycaster.setFromCamera(mouse, camera);
  58332. var intersects = raycaster.intersectObjects(objects);
  58333. var selectionChanged = false;
  58334. if (intersects.length > 0) {
  58335. //console.log(intersects);
  58336. var intersection = intersects[0];
  58337. var _orientedImage = intersection.object.orientedImage;
  58338. _orientedImage.line.material.color.setRGB(1, 0, 0);
  58339. selectionChanged = hoveredElement !== _orientedImage;
  58340. hoveredElement = _orientedImage;
  58341. } else {
  58342. hoveredElement = null;
  58343. }
  58344. var shouldRemoveClipVolume = clipVolume !== null && hoveredElement === null;
  58345. var shouldAddClipVolume = clipVolume === null && hoveredElement !== null;
  58346. if (clipVolume !== null && (hoveredElement === null || selectionChanged)) {
  58347. // remove existing
  58348. viewer.scene.removePolygonClipVolume(clipVolume);
  58349. clipVolume = null;
  58350. }
  58351. if (shouldAddClipVolume || selectionChanged) {
  58352. var img = hoveredElement;
  58353. var fov = cameraParams.fov;
  58354. var aspect = cameraParams.width / cameraParams.height;
  58355. var near = 1.0;
  58356. var far = 1000 * 1000;
  58357. var _camera = new PerspectiveCamera(fov, aspect, near, far);
  58358. _camera.rotation.order = viewer.scene.getActiveCamera().rotation.order;
  58359. _camera.rotation.copy(img.mesh.rotation);
  58360. {
  58361. var mesh = img.mesh;
  58362. var dir = mesh.getWorldDirection();
  58363. var pos = mesh.position;
  58364. var alpha = MathUtils.degToRad(fov / 2);
  58365. var d = 0.5 / Math.tan(alpha);
  58366. var newCamPos = pos.clone().add(dir.clone().multiplyScalar(d));
  58367. var newCamDir = pos.clone().sub(newCamPos);
  58368. var newCamTarget = new Vector3().addVectors(newCamPos, newCamDir.clone().multiplyScalar(viewer.getMoveSpeed()));
  58369. _camera.position.copy(newCamPos);
  58370. }
  58371. var volume = new Potree.PolygonClipVolume(_camera);
  58372. var m0 = new Mesh();
  58373. var m1 = new Mesh();
  58374. var m2 = new Mesh();
  58375. var m3 = new Mesh();
  58376. m0.position.set(-1, -1, 0);
  58377. m1.position.set(1, -1, 0);
  58378. m2.position.set(1, 1, 0);
  58379. m3.position.set(-1, 1, 0);
  58380. volume.markers.push(m0, m1, m2, m3);
  58381. volume.initialized = true;
  58382. viewer.scene.addPolygonClipVolume(volume);
  58383. clipVolume = volume;
  58384. }
  58385. var tEnd = performance.now();
  58386. //console.log(tEnd - tStart);
  58387. };
  58388. var moveToImage = image => {
  58389. console.log("move to image " + image.id);
  58390. var mesh = image.mesh;
  58391. var newCamPos = image.position.clone();
  58392. var newCamTarget = mesh.position.clone();
  58393. viewer.scene.view.setView(newCamPos, newCamTarget, 500, () => {
  58394. orientedImageControls.capture(image);
  58395. });
  58396. if (image.texture === null) {
  58397. var target = image;
  58398. var tmpImagePath = "".concat(Potree.resourcePath, "/images/loading.jpg");
  58399. new TextureLoader().load(tmpImagePath, texture => {
  58400. if (target.texture === null) {
  58401. target.texture = texture;
  58402. target.mesh.material.uniforms.tColor.value = texture;
  58403. mesh.material.needsUpdate = true;
  58404. }
  58405. });
  58406. var imagePath = "".concat(imageParamsPath, "/../").concat(target.id);
  58407. new TextureLoader().load(imagePath, texture => {
  58408. target.texture = texture;
  58409. target.mesh.material.uniforms.tColor.value = texture;
  58410. mesh.material.needsUpdate = true;
  58411. });
  58412. }
  58413. };
  58414. var onMouseClick = evt => {
  58415. if (orientedImageControls.hasSomethingCaptured()) {
  58416. return;
  58417. }
  58418. if (hoveredElement) {
  58419. moveToImage(hoveredElement);
  58420. }
  58421. };
  58422. viewer.renderer.domElement.addEventListener('mousemove', onMouseMove, false);
  58423. viewer.renderer.domElement.addEventListener('mousedown', onMouseClick, false);
  58424. viewer.addEventListener("update", () => {
  58425. for (var image of orientedImages) {
  58426. var world = image.mesh.matrixWorld;
  58427. var {
  58428. width: _width,
  58429. height: _height
  58430. } = image;
  58431. var aspect = _width / _height;
  58432. var camera = viewer.scene.getActiveCamera();
  58433. var imgPos = image.mesh.getWorldPosition(new Vector3());
  58434. var camPos = camera.position;
  58435. var d = camPos.distanceTo(imgPos);
  58436. var minSize = 1; // in degrees of fov
  58437. var a = MathUtils.degToRad(minSize);
  58438. var r = d * Math.tan(a);
  58439. r = Math.max(r, 1);
  58440. image.mesh.scale.set(r * aspect, r, 1);
  58441. image.line.scale.set(r * aspect, r, 1);
  58442. image.mesh.material.uniforms.uNear.value = camera.near;
  58443. }
  58444. });
  58445. var images = new OrientedImages();
  58446. images.node = sceneNode;
  58447. images.cameraParamsPath = cameraParamsPath;
  58448. images.imageParamsPath = imageParamsPath;
  58449. images.cameraParams = cameraParams;
  58450. images.imageParams = imageParams;
  58451. images.images = orientedImages;
  58452. Potree.debug.moveToImage = moveToImage;
  58453. return images;
  58454. })();
  58455. }
  58456. }
  58457. // This is a generated file. Do not edit.
  58458. var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/;
  58459. var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/;
  58460. var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/;
  58461. var unicode = {
  58462. Space_Separator: Space_Separator,
  58463. ID_Start: ID_Start,
  58464. ID_Continue: ID_Continue
  58465. };
  58466. var util = {
  58467. isSpaceSeparator(c) {
  58468. return typeof c === 'string' && unicode.Space_Separator.test(c);
  58469. },
  58470. isIdStartChar(c) {
  58471. return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '$' || c === '_' || unicode.ID_Start.test(c));
  58472. },
  58473. isIdContinueChar(c) {
  58474. return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c === '$' || c === '_' || c === '\u200C' || c === '\u200D' || unicode.ID_Continue.test(c));
  58475. },
  58476. isDigit(c) {
  58477. return typeof c === 'string' && /[0-9]/.test(c);
  58478. },
  58479. isHexDigit(c) {
  58480. return typeof c === 'string' && /[0-9A-Fa-f]/.test(c);
  58481. }
  58482. };
  58483. var source;
  58484. var parseState;
  58485. var stack$1;
  58486. var pos;
  58487. var line;
  58488. var column;
  58489. var token;
  58490. var key;
  58491. var root;
  58492. var parse = function parse(text, reviver) {
  58493. source = String(text);
  58494. parseState = 'start';
  58495. stack$1 = [];
  58496. pos = 0;
  58497. line = 1;
  58498. column = 0;
  58499. token = undefined;
  58500. key = undefined;
  58501. root = undefined;
  58502. do {
  58503. token = lex();
  58504. // This code is unreachable.
  58505. // if (!parseStates[parseState]) {
  58506. // throw invalidParseState()
  58507. // }
  58508. parseStates[parseState]();
  58509. } while (token.type !== 'eof');
  58510. if (typeof reviver === 'function') {
  58511. return internalize({
  58512. '': root
  58513. }, '', reviver);
  58514. }
  58515. return root;
  58516. };
  58517. function internalize(holder, name, reviver) {
  58518. var value = holder[name];
  58519. if (value != null && typeof value === 'object') {
  58520. for (var _key in value) {
  58521. var replacement = internalize(value, _key, reviver);
  58522. if (replacement === undefined) {
  58523. delete value[_key];
  58524. } else {
  58525. value[_key] = replacement;
  58526. }
  58527. }
  58528. }
  58529. return reviver.call(holder, name, value);
  58530. }
  58531. var lexState;
  58532. var buffer;
  58533. var doubleQuote;
  58534. var sign$1;
  58535. var c$1;
  58536. function lex() {
  58537. lexState = 'default';
  58538. buffer = '';
  58539. doubleQuote = false;
  58540. sign$1 = 1;
  58541. for (;;) {
  58542. c$1 = peek();
  58543. // This code is unreachable.
  58544. // if (!lexStates[lexState]) {
  58545. // throw invalidLexState(lexState)
  58546. // }
  58547. var _token = lexStates[lexState]();
  58548. if (_token) {
  58549. return _token;
  58550. }
  58551. }
  58552. }
  58553. function peek() {
  58554. if (source[pos]) {
  58555. return String.fromCodePoint(source.codePointAt(pos));
  58556. }
  58557. }
  58558. function read() {
  58559. var c = peek();
  58560. if (c === '\n') {
  58561. line++;
  58562. column = 0;
  58563. } else if (c) {
  58564. column += c.length;
  58565. } else {
  58566. column++;
  58567. }
  58568. if (c) {
  58569. pos += c.length;
  58570. }
  58571. return c;
  58572. }
  58573. var lexStates = {
  58574. default() {
  58575. switch (c$1) {
  58576. case '\t':
  58577. case '\v':
  58578. case '\f':
  58579. case ' ':
  58580. case '\u00A0':
  58581. case '\uFEFF':
  58582. case '\n':
  58583. case '\r':
  58584. case '\u2028':
  58585. case '\u2029':
  58586. read();
  58587. return;
  58588. case '/':
  58589. read();
  58590. lexState = 'comment';
  58591. return;
  58592. case undefined:
  58593. read();
  58594. return newToken('eof');
  58595. }
  58596. if (util.isSpaceSeparator(c$1)) {
  58597. read();
  58598. return;
  58599. }
  58600. // This code is unreachable.
  58601. // if (!lexStates[parseState]) {
  58602. // throw invalidLexState(parseState)
  58603. // }
  58604. return lexStates[parseState]();
  58605. },
  58606. comment() {
  58607. switch (c$1) {
  58608. case '*':
  58609. read();
  58610. lexState = 'multiLineComment';
  58611. return;
  58612. case '/':
  58613. read();
  58614. lexState = 'singleLineComment';
  58615. return;
  58616. }
  58617. throw invalidChar(read());
  58618. },
  58619. multiLineComment() {
  58620. switch (c$1) {
  58621. case '*':
  58622. read();
  58623. lexState = 'multiLineCommentAsterisk';
  58624. return;
  58625. case undefined:
  58626. throw invalidChar(read());
  58627. }
  58628. read();
  58629. },
  58630. multiLineCommentAsterisk() {
  58631. switch (c$1) {
  58632. case '*':
  58633. read();
  58634. return;
  58635. case '/':
  58636. read();
  58637. lexState = 'default';
  58638. return;
  58639. case undefined:
  58640. throw invalidChar(read());
  58641. }
  58642. read();
  58643. lexState = 'multiLineComment';
  58644. },
  58645. singleLineComment() {
  58646. switch (c$1) {
  58647. case '\n':
  58648. case '\r':
  58649. case '\u2028':
  58650. case '\u2029':
  58651. read();
  58652. lexState = 'default';
  58653. return;
  58654. case undefined:
  58655. read();
  58656. return newToken('eof');
  58657. }
  58658. read();
  58659. },
  58660. value() {
  58661. switch (c$1) {
  58662. case '{':
  58663. case '[':
  58664. return newToken('punctuator', read());
  58665. case 'n':
  58666. read();
  58667. literal('ull');
  58668. return newToken('null', null);
  58669. case 't':
  58670. read();
  58671. literal('rue');
  58672. return newToken('boolean', true);
  58673. case 'f':
  58674. read();
  58675. literal('alse');
  58676. return newToken('boolean', false);
  58677. case '-':
  58678. case '+':
  58679. if (read() === '-') {
  58680. sign$1 = -1;
  58681. }
  58682. lexState = 'sign';
  58683. return;
  58684. case '.':
  58685. buffer = read();
  58686. lexState = 'decimalPointLeading';
  58687. return;
  58688. case '0':
  58689. buffer = read();
  58690. lexState = 'zero';
  58691. return;
  58692. case '1':
  58693. case '2':
  58694. case '3':
  58695. case '4':
  58696. case '5':
  58697. case '6':
  58698. case '7':
  58699. case '8':
  58700. case '9':
  58701. buffer = read();
  58702. lexState = 'decimalInteger';
  58703. return;
  58704. case 'I':
  58705. read();
  58706. literal('nfinity');
  58707. return newToken('numeric', Infinity);
  58708. case 'N':
  58709. read();
  58710. literal('aN');
  58711. return newToken('numeric', NaN);
  58712. case '"':
  58713. case "'":
  58714. doubleQuote = read() === '"';
  58715. buffer = '';
  58716. lexState = 'string';
  58717. return;
  58718. }
  58719. throw invalidChar(read());
  58720. },
  58721. identifierNameStartEscape() {
  58722. if (c$1 !== 'u') {
  58723. throw invalidChar(read());
  58724. }
  58725. read();
  58726. var u = unicodeEscape();
  58727. switch (u) {
  58728. case '$':
  58729. case '_':
  58730. break;
  58731. default:
  58732. if (!util.isIdStartChar(u)) {
  58733. throw invalidIdentifier();
  58734. }
  58735. break;
  58736. }
  58737. buffer += u;
  58738. lexState = 'identifierName';
  58739. },
  58740. identifierName() {
  58741. switch (c$1) {
  58742. case '$':
  58743. case '_':
  58744. case '\u200C':
  58745. case '\u200D':
  58746. buffer += read();
  58747. return;
  58748. case '\\':
  58749. read();
  58750. lexState = 'identifierNameEscape';
  58751. return;
  58752. }
  58753. if (util.isIdContinueChar(c$1)) {
  58754. buffer += read();
  58755. return;
  58756. }
  58757. return newToken('identifier', buffer);
  58758. },
  58759. identifierNameEscape() {
  58760. if (c$1 !== 'u') {
  58761. throw invalidChar(read());
  58762. }
  58763. read();
  58764. var u = unicodeEscape();
  58765. switch (u) {
  58766. case '$':
  58767. case '_':
  58768. case '\u200C':
  58769. case '\u200D':
  58770. break;
  58771. default:
  58772. if (!util.isIdContinueChar(u)) {
  58773. throw invalidIdentifier();
  58774. }
  58775. break;
  58776. }
  58777. buffer += u;
  58778. lexState = 'identifierName';
  58779. },
  58780. sign() {
  58781. switch (c$1) {
  58782. case '.':
  58783. buffer = read();
  58784. lexState = 'decimalPointLeading';
  58785. return;
  58786. case '0':
  58787. buffer = read();
  58788. lexState = 'zero';
  58789. return;
  58790. case '1':
  58791. case '2':
  58792. case '3':
  58793. case '4':
  58794. case '5':
  58795. case '6':
  58796. case '7':
  58797. case '8':
  58798. case '9':
  58799. buffer = read();
  58800. lexState = 'decimalInteger';
  58801. return;
  58802. case 'I':
  58803. read();
  58804. literal('nfinity');
  58805. return newToken('numeric', sign$1 * Infinity);
  58806. case 'N':
  58807. read();
  58808. literal('aN');
  58809. return newToken('numeric', NaN);
  58810. }
  58811. throw invalidChar(read());
  58812. },
  58813. zero() {
  58814. switch (c$1) {
  58815. case '.':
  58816. buffer += read();
  58817. lexState = 'decimalPoint';
  58818. return;
  58819. case 'e':
  58820. case 'E':
  58821. buffer += read();
  58822. lexState = 'decimalExponent';
  58823. return;
  58824. case 'x':
  58825. case 'X':
  58826. buffer += read();
  58827. lexState = 'hexadecimal';
  58828. return;
  58829. }
  58830. return newToken('numeric', sign$1 * 0);
  58831. },
  58832. decimalInteger() {
  58833. switch (c$1) {
  58834. case '.':
  58835. buffer += read();
  58836. lexState = 'decimalPoint';
  58837. return;
  58838. case 'e':
  58839. case 'E':
  58840. buffer += read();
  58841. lexState = 'decimalExponent';
  58842. return;
  58843. }
  58844. if (util.isDigit(c$1)) {
  58845. buffer += read();
  58846. return;
  58847. }
  58848. return newToken('numeric', sign$1 * Number(buffer));
  58849. },
  58850. decimalPointLeading() {
  58851. if (util.isDigit(c$1)) {
  58852. buffer += read();
  58853. lexState = 'decimalFraction';
  58854. return;
  58855. }
  58856. throw invalidChar(read());
  58857. },
  58858. decimalPoint() {
  58859. switch (c$1) {
  58860. case 'e':
  58861. case 'E':
  58862. buffer += read();
  58863. lexState = 'decimalExponent';
  58864. return;
  58865. }
  58866. if (util.isDigit(c$1)) {
  58867. buffer += read();
  58868. lexState = 'decimalFraction';
  58869. return;
  58870. }
  58871. return newToken('numeric', sign$1 * Number(buffer));
  58872. },
  58873. decimalFraction() {
  58874. switch (c$1) {
  58875. case 'e':
  58876. case 'E':
  58877. buffer += read();
  58878. lexState = 'decimalExponent';
  58879. return;
  58880. }
  58881. if (util.isDigit(c$1)) {
  58882. buffer += read();
  58883. return;
  58884. }
  58885. return newToken('numeric', sign$1 * Number(buffer));
  58886. },
  58887. decimalExponent() {
  58888. switch (c$1) {
  58889. case '+':
  58890. case '-':
  58891. buffer += read();
  58892. lexState = 'decimalExponentSign';
  58893. return;
  58894. }
  58895. if (util.isDigit(c$1)) {
  58896. buffer += read();
  58897. lexState = 'decimalExponentInteger';
  58898. return;
  58899. }
  58900. throw invalidChar(read());
  58901. },
  58902. decimalExponentSign() {
  58903. if (util.isDigit(c$1)) {
  58904. buffer += read();
  58905. lexState = 'decimalExponentInteger';
  58906. return;
  58907. }
  58908. throw invalidChar(read());
  58909. },
  58910. decimalExponentInteger() {
  58911. if (util.isDigit(c$1)) {
  58912. buffer += read();
  58913. return;
  58914. }
  58915. return newToken('numeric', sign$1 * Number(buffer));
  58916. },
  58917. hexadecimal() {
  58918. if (util.isHexDigit(c$1)) {
  58919. buffer += read();
  58920. lexState = 'hexadecimalInteger';
  58921. return;
  58922. }
  58923. throw invalidChar(read());
  58924. },
  58925. hexadecimalInteger() {
  58926. if (util.isHexDigit(c$1)) {
  58927. buffer += read();
  58928. return;
  58929. }
  58930. return newToken('numeric', sign$1 * Number(buffer));
  58931. },
  58932. string() {
  58933. switch (c$1) {
  58934. case '\\':
  58935. read();
  58936. buffer += escape$1();
  58937. return;
  58938. case '"':
  58939. if (doubleQuote) {
  58940. read();
  58941. return newToken('string', buffer);
  58942. }
  58943. buffer += read();
  58944. return;
  58945. case "'":
  58946. if (!doubleQuote) {
  58947. read();
  58948. return newToken('string', buffer);
  58949. }
  58950. buffer += read();
  58951. return;
  58952. case '\n':
  58953. case '\r':
  58954. throw invalidChar(read());
  58955. case '\u2028':
  58956. case '\u2029':
  58957. separatorChar(c$1);
  58958. break;
  58959. case undefined:
  58960. throw invalidChar(read());
  58961. }
  58962. buffer += read();
  58963. },
  58964. start() {
  58965. switch (c$1) {
  58966. case '{':
  58967. case '[':
  58968. return newToken('punctuator', read());
  58969. // This code is unreachable since the default lexState handles eof.
  58970. // case undefined:
  58971. // return newToken('eof')
  58972. }
  58973. lexState = 'value';
  58974. },
  58975. beforePropertyName() {
  58976. switch (c$1) {
  58977. case '$':
  58978. case '_':
  58979. buffer = read();
  58980. lexState = 'identifierName';
  58981. return;
  58982. case '\\':
  58983. read();
  58984. lexState = 'identifierNameStartEscape';
  58985. return;
  58986. case '}':
  58987. return newToken('punctuator', read());
  58988. case '"':
  58989. case "'":
  58990. doubleQuote = read() === '"';
  58991. lexState = 'string';
  58992. return;
  58993. }
  58994. if (util.isIdStartChar(c$1)) {
  58995. buffer += read();
  58996. lexState = 'identifierName';
  58997. return;
  58998. }
  58999. throw invalidChar(read());
  59000. },
  59001. afterPropertyName() {
  59002. if (c$1 === ':') {
  59003. return newToken('punctuator', read());
  59004. }
  59005. throw invalidChar(read());
  59006. },
  59007. beforePropertyValue() {
  59008. lexState = 'value';
  59009. },
  59010. afterPropertyValue() {
  59011. switch (c$1) {
  59012. case ',':
  59013. case '}':
  59014. return newToken('punctuator', read());
  59015. }
  59016. throw invalidChar(read());
  59017. },
  59018. beforeArrayValue() {
  59019. if (c$1 === ']') {
  59020. return newToken('punctuator', read());
  59021. }
  59022. lexState = 'value';
  59023. },
  59024. afterArrayValue() {
  59025. switch (c$1) {
  59026. case ',':
  59027. case ']':
  59028. return newToken('punctuator', read());
  59029. }
  59030. throw invalidChar(read());
  59031. },
  59032. end() {
  59033. // This code is unreachable since it's handled by the default lexState.
  59034. // if (c === undefined) {
  59035. // read()
  59036. // return newToken('eof')
  59037. // }
  59038. throw invalidChar(read());
  59039. }
  59040. };
  59041. function newToken(type, value) {
  59042. return {
  59043. type,
  59044. value,
  59045. line,
  59046. column
  59047. };
  59048. }
  59049. function literal(s) {
  59050. for (var _c of s) {
  59051. var p = peek();
  59052. if (p !== _c) {
  59053. throw invalidChar(read());
  59054. }
  59055. read();
  59056. }
  59057. }
  59058. function escape$1() {
  59059. var c = peek();
  59060. switch (c) {
  59061. case 'b':
  59062. read();
  59063. return '\b';
  59064. case 'f':
  59065. read();
  59066. return '\f';
  59067. case 'n':
  59068. read();
  59069. return '\n';
  59070. case 'r':
  59071. read();
  59072. return '\r';
  59073. case 't':
  59074. read();
  59075. return '\t';
  59076. case 'v':
  59077. read();
  59078. return '\v';
  59079. case '0':
  59080. read();
  59081. if (util.isDigit(peek())) {
  59082. throw invalidChar(read());
  59083. }
  59084. return '\0';
  59085. case 'x':
  59086. read();
  59087. return hexEscape();
  59088. case 'u':
  59089. read();
  59090. return unicodeEscape();
  59091. case '\n':
  59092. case '\u2028':
  59093. case '\u2029':
  59094. read();
  59095. return '';
  59096. case '\r':
  59097. read();
  59098. if (peek() === '\n') {
  59099. read();
  59100. }
  59101. return '';
  59102. case '1':
  59103. case '2':
  59104. case '3':
  59105. case '4':
  59106. case '5':
  59107. case '6':
  59108. case '7':
  59109. case '8':
  59110. case '9':
  59111. throw invalidChar(read());
  59112. case undefined:
  59113. throw invalidChar(read());
  59114. }
  59115. return read();
  59116. }
  59117. function hexEscape() {
  59118. var buffer = '';
  59119. var c = peek();
  59120. if (!util.isHexDigit(c)) {
  59121. throw invalidChar(read());
  59122. }
  59123. buffer += read();
  59124. c = peek();
  59125. if (!util.isHexDigit(c)) {
  59126. throw invalidChar(read());
  59127. }
  59128. buffer += read();
  59129. return String.fromCodePoint(parseInt(buffer, 16));
  59130. }
  59131. function unicodeEscape() {
  59132. var buffer = '';
  59133. var count = 4;
  59134. while (count-- > 0) {
  59135. var _c2 = peek();
  59136. if (!util.isHexDigit(_c2)) {
  59137. throw invalidChar(read());
  59138. }
  59139. buffer += read();
  59140. }
  59141. return String.fromCodePoint(parseInt(buffer, 16));
  59142. }
  59143. var parseStates = {
  59144. start() {
  59145. if (token.type === 'eof') {
  59146. throw invalidEOF();
  59147. }
  59148. push();
  59149. },
  59150. beforePropertyName() {
  59151. switch (token.type) {
  59152. case 'identifier':
  59153. case 'string':
  59154. key = token.value;
  59155. parseState = 'afterPropertyName';
  59156. return;
  59157. case 'punctuator':
  59158. // This code is unreachable since it's handled by the lexState.
  59159. // if (token.value !== '}') {
  59160. // throw invalidToken()
  59161. // }
  59162. pop();
  59163. return;
  59164. case 'eof':
  59165. throw invalidEOF();
  59166. }
  59167. // This code is unreachable since it's handled by the lexState.
  59168. // throw invalidToken()
  59169. },
  59170. afterPropertyName() {
  59171. // This code is unreachable since it's handled by the lexState.
  59172. // if (token.type !== 'punctuator' || token.value !== ':') {
  59173. // throw invalidToken()
  59174. // }
  59175. if (token.type === 'eof') {
  59176. throw invalidEOF();
  59177. }
  59178. parseState = 'beforePropertyValue';
  59179. },
  59180. beforePropertyValue() {
  59181. if (token.type === 'eof') {
  59182. throw invalidEOF();
  59183. }
  59184. push();
  59185. },
  59186. beforeArrayValue() {
  59187. if (token.type === 'eof') {
  59188. throw invalidEOF();
  59189. }
  59190. if (token.type === 'punctuator' && token.value === ']') {
  59191. pop();
  59192. return;
  59193. }
  59194. push();
  59195. },
  59196. afterPropertyValue() {
  59197. // This code is unreachable since it's handled by the lexState.
  59198. // if (token.type !== 'punctuator') {
  59199. // throw invalidToken()
  59200. // }
  59201. if (token.type === 'eof') {
  59202. throw invalidEOF();
  59203. }
  59204. switch (token.value) {
  59205. case ',':
  59206. parseState = 'beforePropertyName';
  59207. return;
  59208. case '}':
  59209. pop();
  59210. }
  59211. // This code is unreachable since it's handled by the lexState.
  59212. // throw invalidToken()
  59213. },
  59214. afterArrayValue() {
  59215. // This code is unreachable since it's handled by the lexState.
  59216. // if (token.type !== 'punctuator') {
  59217. // throw invalidToken()
  59218. // }
  59219. if (token.type === 'eof') {
  59220. throw invalidEOF();
  59221. }
  59222. switch (token.value) {
  59223. case ',':
  59224. parseState = 'beforeArrayValue';
  59225. return;
  59226. case ']':
  59227. pop();
  59228. }
  59229. // This code is unreachable since it's handled by the lexState.
  59230. // throw invalidToken()
  59231. },
  59232. end() {
  59233. // This code is unreachable since it's handled by the lexState.
  59234. // if (token.type !== 'eof') {
  59235. // throw invalidToken()
  59236. // }
  59237. }
  59238. };
  59239. function push() {
  59240. var value;
  59241. switch (token.type) {
  59242. case 'punctuator':
  59243. switch (token.value) {
  59244. case '{':
  59245. value = {};
  59246. break;
  59247. case '[':
  59248. value = [];
  59249. break;
  59250. }
  59251. break;
  59252. case 'null':
  59253. case 'boolean':
  59254. case 'numeric':
  59255. case 'string':
  59256. value = token.value;
  59257. break;
  59258. // This code is unreachable.
  59259. // default:
  59260. // throw invalidToken()
  59261. }
  59262. if (root === undefined) {
  59263. root = value;
  59264. } else {
  59265. var parent = stack$1[stack$1.length - 1];
  59266. if (Array.isArray(parent)) {
  59267. parent.push(value);
  59268. } else {
  59269. parent[key] = value;
  59270. }
  59271. }
  59272. if (value !== null && typeof value === 'object') {
  59273. stack$1.push(value);
  59274. if (Array.isArray(value)) {
  59275. parseState = 'beforeArrayValue';
  59276. } else {
  59277. parseState = 'beforePropertyName';
  59278. }
  59279. } else {
  59280. var current = stack$1[stack$1.length - 1];
  59281. if (current == null) {
  59282. parseState = 'end';
  59283. } else if (Array.isArray(current)) {
  59284. parseState = 'afterArrayValue';
  59285. } else {
  59286. parseState = 'afterPropertyValue';
  59287. }
  59288. }
  59289. }
  59290. function pop() {
  59291. stack$1.pop();
  59292. var current = stack$1[stack$1.length - 1];
  59293. if (current == null) {
  59294. parseState = 'end';
  59295. } else if (Array.isArray(current)) {
  59296. parseState = 'afterArrayValue';
  59297. } else {
  59298. parseState = 'afterPropertyValue';
  59299. }
  59300. }
  59301. // This code is unreachable.
  59302. // function invalidParseState () {
  59303. // return new Error(`JSON5: invalid parse state '${parseState}'`)
  59304. // }
  59305. // This code is unreachable.
  59306. // function invalidLexState (state) {
  59307. // return new Error(`JSON5: invalid lex state '${state}'`)
  59308. // }
  59309. function invalidChar(c) {
  59310. if (c === undefined) {
  59311. return syntaxError("JSON5: invalid end of input at ".concat(line, ":").concat(column));
  59312. }
  59313. return syntaxError("JSON5: invalid character '".concat(formatChar(c), "' at ").concat(line, ":").concat(column));
  59314. }
  59315. function invalidEOF() {
  59316. return syntaxError("JSON5: invalid end of input at ".concat(line, ":").concat(column));
  59317. }
  59318. // This code is unreachable.
  59319. // function invalidToken () {
  59320. // if (token.type === 'eof') {
  59321. // return syntaxError(`JSON5: invalid end of input at ${line}:${column}`)
  59322. // }
  59323. // const c = String.fromCodePoint(token.value.codePointAt(0))
  59324. // return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`)
  59325. // }
  59326. function invalidIdentifier() {
  59327. column -= 5;
  59328. return syntaxError("JSON5: invalid identifier character at ".concat(line, ":").concat(column));
  59329. }
  59330. function separatorChar(c) {
  59331. console.warn("JSON5: '".concat(formatChar(c), "' in strings is not valid ECMAScript; consider escaping"));
  59332. }
  59333. function formatChar(c) {
  59334. var replacements = {
  59335. "'": "\\'",
  59336. '"': '\\"',
  59337. '\\': '\\\\',
  59338. '\b': '\\b',
  59339. '\f': '\\f',
  59340. '\n': '\\n',
  59341. '\r': '\\r',
  59342. '\t': '\\t',
  59343. '\v': '\\v',
  59344. '\0': '\\0',
  59345. '\u2028': '\\u2028',
  59346. '\u2029': '\\u2029'
  59347. };
  59348. if (replacements[c]) {
  59349. return replacements[c];
  59350. }
  59351. if (c < ' ') {
  59352. var hexString = c.charCodeAt(0).toString(16);
  59353. return '\\x' + ('00' + hexString).substring(hexString.length);
  59354. }
  59355. return c;
  59356. }
  59357. function syntaxError(message) {
  59358. var err = new SyntaxError(message);
  59359. err.lineNumber = line;
  59360. err.columnNumber = column;
  59361. return err;
  59362. }
  59363. var stringify = function stringify(value, replacer, space) {
  59364. var stack = [];
  59365. var indent = '';
  59366. var propertyList;
  59367. var replacerFunc;
  59368. var gap = '';
  59369. var quote;
  59370. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  59371. space = replacer.space;
  59372. quote = replacer.quote;
  59373. replacer = replacer.replacer;
  59374. }
  59375. if (typeof replacer === 'function') {
  59376. replacerFunc = replacer;
  59377. } else if (Array.isArray(replacer)) {
  59378. propertyList = [];
  59379. for (var v of replacer) {
  59380. var item = void 0;
  59381. if (typeof v === 'string') {
  59382. item = v;
  59383. } else if (typeof v === 'number' || v instanceof String || v instanceof Number) {
  59384. item = String(v);
  59385. }
  59386. if (item !== undefined && propertyList.indexOf(item) < 0) {
  59387. propertyList.push(item);
  59388. }
  59389. }
  59390. }
  59391. if (space instanceof Number) {
  59392. space = Number(space);
  59393. } else if (space instanceof String) {
  59394. space = String(space);
  59395. }
  59396. if (typeof space === 'number') {
  59397. if (space > 0) {
  59398. space = Math.min(10, Math.floor(space));
  59399. gap = ' '.substr(0, space);
  59400. }
  59401. } else if (typeof space === 'string') {
  59402. gap = space.substr(0, 10);
  59403. }
  59404. return serializeProperty('', {
  59405. '': value
  59406. });
  59407. function serializeProperty(key, holder) {
  59408. var value = holder[key];
  59409. if (value != null) {
  59410. if (typeof value.toJSON5 === 'function') {
  59411. value = value.toJSON5(key);
  59412. } else if (typeof value.toJSON === 'function') {
  59413. value = value.toJSON(key);
  59414. }
  59415. }
  59416. if (replacerFunc) {
  59417. value = replacerFunc.call(holder, key, value);
  59418. }
  59419. if (value instanceof Number) {
  59420. value = Number(value);
  59421. } else if (value instanceof String) {
  59422. value = String(value);
  59423. } else if (value instanceof Boolean) {
  59424. value = value.valueOf();
  59425. }
  59426. switch (value) {
  59427. case null:
  59428. return 'null';
  59429. case true:
  59430. return 'true';
  59431. case false:
  59432. return 'false';
  59433. }
  59434. if (typeof value === 'string') {
  59435. return quoteString(value, false);
  59436. }
  59437. if (typeof value === 'number') {
  59438. return String(value);
  59439. }
  59440. if (typeof value === 'object') {
  59441. return Array.isArray(value) ? serializeArray(value) : serializeObject(value);
  59442. }
  59443. return undefined;
  59444. }
  59445. function quoteString(value) {
  59446. var quotes = {
  59447. "'": 0.1,
  59448. '"': 0.2
  59449. };
  59450. var replacements = {
  59451. "'": "\\'",
  59452. '"': '\\"',
  59453. '\\': '\\\\',
  59454. '\b': '\\b',
  59455. '\f': '\\f',
  59456. '\n': '\\n',
  59457. '\r': '\\r',
  59458. '\t': '\\t',
  59459. '\v': '\\v',
  59460. '\0': '\\0',
  59461. '\u2028': '\\u2028',
  59462. '\u2029': '\\u2029'
  59463. };
  59464. var product = '';
  59465. for (var i = 0; i < value.length; i++) {
  59466. var _c3 = value[i];
  59467. switch (_c3) {
  59468. case "'":
  59469. case '"':
  59470. quotes[_c3]++;
  59471. product += _c3;
  59472. continue;
  59473. case '\0':
  59474. if (util.isDigit(value[i + 1])) {
  59475. product += '\\x00';
  59476. continue;
  59477. }
  59478. }
  59479. if (replacements[_c3]) {
  59480. product += replacements[_c3];
  59481. continue;
  59482. }
  59483. if (_c3 < ' ') {
  59484. var hexString = _c3.charCodeAt(0).toString(16);
  59485. product += '\\x' + ('00' + hexString).substring(hexString.length);
  59486. continue;
  59487. }
  59488. product += _c3;
  59489. }
  59490. var quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b);
  59491. product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]);
  59492. return quoteChar + product + quoteChar;
  59493. }
  59494. function serializeObject(value) {
  59495. if (stack.indexOf(value) >= 0) {
  59496. throw TypeError('Converting circular structure to JSON5');
  59497. }
  59498. stack.push(value);
  59499. var stepback = indent;
  59500. indent = indent + gap;
  59501. var keys = propertyList || Object.keys(value);
  59502. var partial = [];
  59503. for (var _key2 of keys) {
  59504. var propertyString = serializeProperty(_key2, value);
  59505. if (propertyString !== undefined) {
  59506. var member = serializeKey(_key2) + ':';
  59507. if (gap !== '') {
  59508. member += ' ';
  59509. }
  59510. member += propertyString;
  59511. partial.push(member);
  59512. }
  59513. }
  59514. var final;
  59515. if (partial.length === 0) {
  59516. final = '{}';
  59517. } else {
  59518. var properties;
  59519. if (gap === '') {
  59520. properties = partial.join(',');
  59521. final = '{' + properties + '}';
  59522. } else {
  59523. var separator = ',\n' + indent;
  59524. properties = partial.join(separator);
  59525. final = '{\n' + indent + properties + ',\n' + stepback + '}';
  59526. }
  59527. }
  59528. stack.pop();
  59529. indent = stepback;
  59530. return final;
  59531. }
  59532. function serializeKey(key) {
  59533. if (key.length === 0) {
  59534. return quoteString(key, true);
  59535. }
  59536. var firstChar = String.fromCodePoint(key.codePointAt(0));
  59537. if (!util.isIdStartChar(firstChar)) {
  59538. return quoteString(key, true);
  59539. }
  59540. for (var i = firstChar.length; i < key.length; i++) {
  59541. if (!util.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) {
  59542. return quoteString(key, true);
  59543. }
  59544. }
  59545. return key;
  59546. }
  59547. function serializeArray(value) {
  59548. if (stack.indexOf(value) >= 0) {
  59549. throw TypeError('Converting circular structure to JSON5');
  59550. }
  59551. stack.push(value);
  59552. var stepback = indent;
  59553. indent = indent + gap;
  59554. var partial = [];
  59555. for (var i = 0; i < value.length; i++) {
  59556. var propertyString = serializeProperty(String(i), value);
  59557. partial.push(propertyString !== undefined ? propertyString : 'null');
  59558. }
  59559. var final;
  59560. if (partial.length === 0) {
  59561. final = '[]';
  59562. } else {
  59563. if (gap === '') {
  59564. var properties = partial.join(',');
  59565. final = '[' + properties + ']';
  59566. } else {
  59567. var separator = ',\n' + indent;
  59568. var _properties = partial.join(separator);
  59569. final = '[\n' + indent + _properties + ',\n' + stepback + ']';
  59570. }
  59571. }
  59572. stack.pop();
  59573. indent = stepback;
  59574. return final;
  59575. }
  59576. };
  59577. var JSON5$1 = {
  59578. parse,
  59579. stringify
  59580. };
  59581. var lib = JSON5$1;
  59582. class Sidebar {
  59583. constructor(viewer) {
  59584. this.viewer = viewer;
  59585. this.measuringTool = viewer.measuringTool;
  59586. this.profileTool = viewer.profileTool;
  59587. this.volumeTool = viewer.volumeTool;
  59588. this.dom = $("#sidebar_root");
  59589. }
  59590. createToolIcon(icon, title, callback) {
  59591. var element = $("\n\t\t\t<img src=\"".concat(icon, "\"\n\t\t\t\tstyle=\"width: 32px; height: 32px\"\n\t\t\t\tclass=\"button-icon\"\n\t\t\t\tdata-i18n=\"").concat(title, "\" />\n\t\t"));
  59592. element.click(callback);
  59593. return element;
  59594. }
  59595. init() {
  59596. if (Potree.settings.editType == 'merge') {
  59597. this.initMergeBar();
  59598. this.initToolbar();
  59599. this.initScene();
  59600. this.initNavigation();
  59601. } else {
  59602. this.initAccordion();
  59603. this.initAppearance();
  59604. this.initToolbar();
  59605. this.initScene();
  59606. this.initNavigation();
  59607. this.initFilters();
  59608. //this.initClippingTool(); //因为修改了clipping,所以这项有bug不能使用
  59609. this.initSettings();
  59610. if (Potree.settings.editType != 'pano') {
  59611. this.initAlignment();
  59612. this.initClipModel();
  59613. this.initSiteModel();
  59614. this.initParitcle();
  59615. this.initClippingModel();
  59616. } else {
  59617. this.initPanosEdit();
  59618. }
  59619. }
  59620. $('#potree_version_number').html(Potree.version.major + "." + Potree.version.minor + Potree.version.suffix);
  59621. }
  59622. initAlignment() {
  59623. var Alignment = viewer.modules.Alignment;
  59624. var pannel = $('#alignment');
  59625. var buttons = pannel.find('[name="transform"] button');
  59626. var applyToPointcloud = (fun, value) => {
  59627. return function () {
  59628. var selected = $('#alignment li[name="selectPointCloud"] input:checked');
  59629. Array.from(selected).forEach(e => {
  59630. var pointcloud = viewer.scene.pointclouds.find(p => p.name == e.name);
  59631. fun(pointcloud, value);
  59632. });
  59633. };
  59634. };
  59635. //逆时针是正数
  59636. buttons.eq(0).on('click', applyToPointcloud(Alignment.rotate, 10));
  59637. //viewer.scene.pointclouds[0].rotation.z += THREE.Math.degToRad(10)
  59638. buttons.eq(1).on('click', applyToPointcloud(Alignment.rotate, 1));
  59639. buttons.eq(2).on('click', applyToPointcloud(Alignment.rotate, 0.1));
  59640. buttons.eq(3).on('click', applyToPointcloud(Alignment.rotate, -10));
  59641. buttons.eq(4).on('click', applyToPointcloud(Alignment.rotate, -1));
  59642. buttons.eq(5).on('click', applyToPointcloud(Alignment.rotate, -0.1));
  59643. buttons.eq(6).on('click', applyToPointcloud(Alignment.translate, new Vector3(-1, 0, 0)));
  59644. buttons.eq(7).on('click', applyToPointcloud(Alignment.translate, new Vector3(1, 0, 0)));
  59645. buttons.eq(8).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, -1, 0)));
  59646. buttons.eq(9).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 1, 0)));
  59647. buttons.eq(10).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 0, -1)));
  59648. buttons.eq(11).on('click', applyToPointcloud(Alignment.translate, new Vector3(0, 0, 1)));
  59649. pannel.find('#startAlignment').on('click', () => {
  59650. Alignment.enter();
  59651. });
  59652. pannel.find('#exitAlignment').on('click', () => {
  59653. Alignment.save();
  59654. Alignment.leave();
  59655. });
  59656. pannel.find('#rotTool').on('click', () => {
  59657. Alignment.switchHandle('rotate');
  59658. });
  59659. pannel.find('#moveTool').on('click', () => {
  59660. Alignment.switchHandle('translate');
  59661. });
  59662. }
  59663. initMergeBar() {
  59664. //多元融合模块
  59665. var pannel = $('#mergeModel');
  59666. var buttons = pannel.find('button');
  59667. var MergeEditor = viewer.modules.MergeEditor;
  59668. var loading = false;
  59669. pannel.find('ul[name="model"] li button').on('click', e => {
  59670. if (loading) return console.log('还在加载', loading);
  59671. var $elem = $(e.target);
  59672. var parent = $elem.parent();
  59673. var name = parent.attr('name');
  59674. if ($elem.attr('name') == 'select') {
  59675. return Potree.selectModel(name);
  59676. }
  59677. if ($elem.text() == '添加') {
  59678. var startTime = Date.now();
  59679. Potree.addModel(name, () => {
  59680. loading = false;
  59681. //$elem.text('删除')
  59682. var now = Date.now();
  59683. console.log('加载完毕', name, '用时', (now - startTime) / 1000, 's');
  59684. });
  59685. loading = name;
  59686. } else {
  59687. Potree.removeModel(name);
  59688. $elem.text('添加');
  59689. }
  59690. });
  59691. pannel.find('li button[name="splitScreen"]').on('click', e => {
  59692. var $elem = $(e.target);
  59693. if ($elem.text() == '分屏') {
  59694. $elem.text('恢复');
  59695. MergeEditor.enterSplit();
  59696. } else {
  59697. $elem.text('分屏');
  59698. MergeEditor.leaveSplit();
  59699. }
  59700. });
  59701. var addingTag = false;
  59702. pannel.find('li button[name="tag"]').on('click', e => {
  59703. var $elem = $(e.target);
  59704. viewer.tagTool.startInsertion();
  59705. });
  59706. }
  59707. initClippingModel() {
  59708. //实时裁剪
  59709. /* 总共两种box : 可见和不可见(都是并集)
  59710. 当有可见box时,需要在任一可见box内才可见
  59711. 当有不可见box时,不在所有不可见box内才可见 */
  59712. var clipping = viewer.modules.clipping;
  59713. var pannel = $('#clipping');
  59714. var addBtn = pannel.find('[name="operation"] button[name="add"] ');
  59715. var switchBtn = pannel.find('[name="operation"] button[name="switchView"] ');
  59716. var enterBtn = pannel.find(' button[name="enter"] ');
  59717. var exitBtn = pannel.find(' button[name="exit"] ');
  59718. var list = pannel.find('[name="list"] ul ');
  59719. enterBtn.on('click', () => {
  59720. clipping.enter();
  59721. pannel.find('li[name=operation]').css('display', 'block');
  59722. pannel.find('li[name=list]').css('display', 'block');
  59723. });
  59724. exitBtn.on('click', () => {
  59725. clipping.leave();
  59726. pannel.find('li[name=operation]').css('display', 'none');
  59727. pannel.find('li[name=list]').css('display', 'none');
  59728. });
  59729. switchBtn.on('click', () => {
  59730. clipping.switchView(clipping.activeViewName == 'top' ? 'mainView' : 'top');
  59731. });
  59732. pannel.find('[name="operation"] button[name="translation"] ').on('click', () => {
  59733. clipping.setTranMode('translation');
  59734. });
  59735. pannel.find('[name="operation"] button[name="rotation"] ').on('click', () => {
  59736. clipping.setTranMode('rotation');
  59737. });
  59738. pannel.find('[name="operation"] button[name="scale"] ').on('click', () => {
  59739. clipping.setTranMode('scale');
  59740. });
  59741. addBtn.on('click', () => {
  59742. var volumeBox = this.volumeTool.startInsertion({
  59743. clip: true,
  59744. clipTask: Potree.ClipTask.SHOW_OUTSIDE
  59745. });
  59746. var li = $("<li><button name='changeTask'>不可见</button><button name='chose'>选择</button><button name='delete'>删除</button></li>");
  59747. list.append(li);
  59748. li.find('button[name=changeTask]').on('click', e => {
  59749. if (e.target.innerText == '不可见') {
  59750. volumeBox.clipTask = Potree.ClipTask.SHOW_INSIDE;
  59751. e.target.innerText = '可见';
  59752. } else {
  59753. volumeBox.clipTask = Potree.ClipTask.SHOW_OUTSIDE;
  59754. e.target.innerText = '不可见';
  59755. }
  59756. volumeBox.update();
  59757. });
  59758. li.find('button[name=chose]').on('click', e => {
  59759. viewer.transformObject(volumeBox); //viewer.inputHandler.toggleSelection(volumeBox)
  59760. });
  59761. li.find('button[name=delete]').on('click', e => {
  59762. li.remove();
  59763. viewer.scene.removeVolume(volumeBox);
  59764. });
  59765. });
  59766. pannel.find('button[name=save]').on('click', e => {
  59767. var data = clipping.saveClipData();
  59768. });
  59769. }
  59770. addAlignmentButton(pointcloud) {
  59771. var pannel = $('#alignment li[name="selectPointCloud"]>div');
  59772. var option = $(" <input name=\"".concat(pointcloud.name, "\" class=\"editCheckbox\" type=\"checkbox\" >\n \n <label for=\"showingLabels\">").concat(pointcloud.name, "</label>"));
  59773. pannel.append(option);
  59774. /* option.find("input").on('change',function(){
  59775. })
  59776. */
  59777. }
  59778. initClipModel() {
  59779. var Clip = viewer.modules.Clip;
  59780. var pannel = $('#clipModel');
  59781. var buttons = pannel.find('button');
  59782. buttons.eq(0).on('click', Clip.enter.bind(Clip));
  59783. buttons.eq(1).on('click', Clip.download.bind(Clip));
  59784. buttons.eq(2).on('click', Clip.leave.bind(Clip));
  59785. }
  59786. initSiteModel() {
  59787. var SiteModel = viewer.modules.SiteModel;
  59788. var pannel = $('#siteModel');
  59789. pannel.find('button[name="start"] ').on('click', SiteModel.enter.bind(SiteModel));
  59790. pannel.find('button[name="exit"] ').on('click', SiteModel.leave.bind(SiteModel));
  59791. pannel.find('button[name="building"] ').on('click', SiteModel.startInsertion.bind(SiteModel, 'building'));
  59792. pannel.find('button[name="floor"] ').on('click', () => {
  59793. SiteModel.addFloor(SiteModel.buildings[0], 'top');
  59794. });
  59795. pannel.find('button[name="room"] ').on('click', () => {
  59796. SiteModel.startInsertion('room', SiteModel.buildings[0].buildChildren[0]);
  59797. });
  59798. pannel.find('button[name="digHole"] ').on('click', () => {
  59799. SiteModel.selected && SiteModel.startInsertion('hole', SiteModel.selected);
  59800. });
  59801. pannel.find('button[name="selectBuilding"] ').on('click', () => {
  59802. SiteModel.selectEntity(SiteModel.buildings[0]);
  59803. });
  59804. pannel.find('button[name="selectFloor"] ').on('click', () => {
  59805. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0]);
  59806. });
  59807. pannel.find('button[name="selectRoom"] ').on('click', () => {
  59808. SiteModel.selectEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  59809. });
  59810. pannel.find('button[name="removeFirstBuilding"] ').on('click', () => {
  59811. SiteModel.removeEntity(SiteModel.buildings[0]);
  59812. });
  59813. pannel.find('button[name="removeFirstFloor"] ').on('click', () => {
  59814. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0]);
  59815. });
  59816. pannel.find('button[name="removeFirstRoom"] ').on('click', () => {
  59817. SiteModel.removeEntity(SiteModel.buildings[0].buildChildren[0].buildChildren[0]);
  59818. });
  59819. pannel.find('button[name="removeFirstHole"] ').on('click', () => {
  59820. SiteModel.selected.removeHole(SiteModel.selected.holes[0]);
  59821. });
  59822. pannel.find('button[name="removeFirstMarker"] ').on('click', () => {
  59823. //SiteModel.removeMarker(SiteModel.selected.markers[0])
  59824. SiteModel.selected.removeMarker(0);
  59825. });
  59826. }
  59827. initParitcle() {
  59828. var ParticleEditor = viewer.modules.ParticleEditor;
  59829. var pannel = $('#particle');
  59830. pannel.find('button[name="addFire"] ').on('click', () => {
  59831. ParticleEditor.startInsertion('fire+smoke');
  59832. });
  59833. pannel.find('button[name="addExplode"] ').on('click', () => {
  59834. ParticleEditor.startInsertion('explode');
  59835. });
  59836. }
  59837. initPanosEdit() {
  59838. var PanoEditor = viewer.modules.PanoEditor;
  59839. var Alignment = viewer.modules.Alignment;
  59840. var pannel = $('#panos');
  59841. pannel.find('button[name="save"] ').on('click', () => {
  59842. console.log('saveData', PanoEditor.exportSavingData());
  59843. });
  59844. pannel.find('button[name="translate"] ').on('click', () => {
  59845. Alignment.switchHandle('translate');
  59846. });
  59847. pannel.find('button[name="rotate"] ').on('click', () => {
  59848. Alignment.switchHandle('rotate');
  59849. });
  59850. pannel.find('button[name="topView"] ').on('click', () => {
  59851. PanoEditor.switchView('top');
  59852. });
  59853. pannel.find('button[name="sideView"] ').on('click', () => {
  59854. PanoEditor.switchView('right');
  59855. });
  59856. pannel.find('button[name="3DView"] ').on('click', () => {
  59857. PanoEditor.switchView('mainView');
  59858. });
  59859. pannel.find('button[name="addLink"] ').on('click', () => {
  59860. PanoEditor.setLinkOperateState('addLink', true);
  59861. });
  59862. pannel.find('button[name="removeLink"] ').on('click', () => {
  59863. PanoEditor.setLinkOperateState('removeLink', true);
  59864. });
  59865. pannel.find('button[name="getCloser"] ').on('click', () => {
  59866. PanoEditor.setZoomInState(true);
  59867. });
  59868. }
  59869. initToolbar() {
  59870. // ANGLE
  59871. var elToolbar = $('#tools');
  59872. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/angle.png', '[title]tt.angle_measurement', () => {
  59873. $('#menu_measurements').next().slideDown();
  59874. var measurement = this.measuringTool.startInsertion({
  59875. showDistances: false,
  59876. showAngles: true,
  59877. showArea: false,
  59878. closed: true,
  59879. maxMarkers: 3,
  59880. minMarkers: 3,
  59881. measureType: 'Angle'
  59882. });
  59883. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59884. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59885. $.jstree.reference(jsonNode.id).deselect_all();
  59886. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59887. }));
  59888. // POINT
  59889. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/point.svg', '[title]tt.point_measurement', () => {
  59890. $('#menu_measurements').next().slideDown();
  59891. var measurement = this.measuringTool.startInsertion({
  59892. showDistances: false,
  59893. showAngles: false,
  59894. showCoordinates: true,
  59895. showEdges: false,
  59896. showArea: false,
  59897. closed: true,
  59898. maxMarkers: 1,
  59899. minMarkers: 1,
  59900. measureType: 'Point'
  59901. });
  59902. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59903. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59904. $.jstree.reference(jsonNode.id).deselect_all();
  59905. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59906. }));
  59907. // DISTANCE
  59908. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]tt.distance_measurement', () => {
  59909. $('#menu_measurements').next().slideDown();
  59910. var measurement = this.measuringTool.startInsertion({
  59911. showDistances: true,
  59912. showArea: false,
  59913. closed: false,
  59914. minMarkers: 2,
  59915. maxMarkers: 2,
  59916. measureType: 'Distance'
  59917. });
  59918. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59919. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59920. $.jstree.reference(jsonNode.id).deselect_all();
  59921. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59922. }));
  59923. // DISTANCE2
  59924. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]MulDistance', () => {
  59925. $('#menu_measurements').next().slideDown();
  59926. var measurement = this.measuringTool.startInsertion({
  59927. showDistances: true,
  59928. showArea: false,
  59929. closed: false,
  59930. minMarkers: 2,
  59931. measureType: 'MulDistance'
  59932. });
  59933. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59934. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59935. $.jstree.reference(jsonNode.id).deselect_all();
  59936. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59937. }));
  59938. // DISTANCE2
  59939. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]MulDistance Ring', () => {
  59940. $('#menu_measurements').next().slideDown();
  59941. var measurement = this.measuringTool.startInsertion({
  59942. //showArea: false,
  59943. closed: true,
  59944. minMarkers: 3,
  59945. measureType: 'MulDistance Ring'
  59946. });
  59947. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59948. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59949. $.jstree.reference(jsonNode.id).deselect_all();
  59950. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59951. }));
  59952. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]Ver MulDistance', () => {
  59953. $('#menu_measurements').next().slideDown();
  59954. var measurement = this.measuringTool.startInsertion({
  59955. measureType: 'Ver MulDistance'
  59956. });
  59957. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59958. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59959. $.jstree.reference(jsonNode.id).deselect_all();
  59960. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59961. }));
  59962. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/distance.svg', '[title]Hor MulDistance', () => {
  59963. $('#menu_measurements').next().slideDown();
  59964. var measurement = this.measuringTool.startInsertion({
  59965. measureType: 'Hor MulDistance'
  59966. });
  59967. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59968. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59969. $.jstree.reference(jsonNode.id).deselect_all();
  59970. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59971. }));
  59972. // HEIGHT
  59973. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/height.svg', '[title]tt.height_measurement', () => {
  59974. $('#menu_measurements').next().slideDown();
  59975. var measurement = this.measuringTool.startInsertion({
  59976. showDistances: true,
  59977. //false,
  59978. showHeight: true,
  59979. showArea: false,
  59980. closed: false,
  59981. maxMarkers: 2,
  59982. minMarkers: 2,
  59983. //showGuideLine: true: true
  59984. measureType: 'Ver Distance'
  59985. });
  59986. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  59987. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  59988. $.jstree.reference(jsonNode.id).deselect_all();
  59989. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  59990. }));
  59991. // CIRCLE
  59992. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/circle.svg', '[title]tt.circle_measurement', () => {
  59993. $('#menu_measurements').next().slideDown();
  59994. var measurement = this.measuringTool.startInsertion({
  59995. showDistances: false,
  59996. showHeight: false,
  59997. showArea: false,
  59998. showCircle: true,
  59999. showEdges: false,
  60000. closed: false,
  60001. maxMarkers: 3,
  60002. minMarkers: 3,
  60003. measureType: 'Circle'
  60004. });
  60005. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60006. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60007. $.jstree.reference(jsonNode.id).deselect_all();
  60008. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60009. }));
  60010. // AZIMUTH
  60011. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/azimuth.svg', 'Azimuth', () => {
  60012. $('#menu_measurements').next().slideDown();
  60013. var measurement = this.measuringTool.startInsertion({
  60014. showDistances: false,
  60015. showHeight: false,
  60016. showArea: false,
  60017. showCircle: false,
  60018. showEdges: false,
  60019. showAzimuth: true,
  60020. closed: false,
  60021. maxMarkers: 2,
  60022. minMarkers: 2,
  60023. measureType: 'Azimuth'
  60024. });
  60025. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60026. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60027. $.jstree.reference(jsonNode.id).deselect_all();
  60028. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60029. }));
  60030. // AREA
  60031. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]tt.area_measurement', () => {
  60032. $('#menu_measurements').next().slideDown();
  60033. var measurement = this.measuringTool.startInsertion({
  60034. showDistances: true,
  60035. showArea: true,
  60036. closed: true,
  60037. minMarkers: 3,
  60038. //showGuideLine: true: true,
  60039. measureType: 'Area'
  60040. });
  60041. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60042. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60043. $.jstree.reference(jsonNode.id).deselect_all();
  60044. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60045. }));
  60046. //Hor AREA
  60047. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]Hor Area', () => {
  60048. $('#menu_measurements').next().slideDown();
  60049. var measurement = this.measuringTool.startInsertion({
  60050. showDistances: true,
  60051. showArea: true,
  60052. closed: true,
  60053. minMarkers: 3,
  60054. measureType: 'Hor Area'
  60055. });
  60056. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60057. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60058. $.jstree.reference(jsonNode.id).deselect_all();
  60059. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60060. }));
  60061. // Ver Area
  60062. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]Ver Area', () => {
  60063. $('#menu_measurements').next().slideDown();
  60064. var measurement = this.measuringTool.startInsertion({
  60065. showDistances: true,
  60066. showArea: true,
  60067. closed: true,
  60068. minMarkers: 3,
  60069. measureType: 'Ver Area'
  60070. });
  60071. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60072. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60073. $.jstree.reference(jsonNode.id).deselect_all();
  60074. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60075. }));
  60076. // rect area freedom direction
  60077. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_freedom_rect', () => {
  60078. $('#menu_measurements').next().slideDown();
  60079. var measurement = this.measuringTool.startInsertion({
  60080. showDistances: true,
  60081. showArea: true,
  60082. closed: true,
  60083. minMarkers: 4,
  60084. maxMarkers: 4,
  60085. //showGuideLine: true: true,
  60086. isRect: true,
  60087. measureType: 'Rect Area'
  60088. });
  60089. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60090. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60091. $.jstree.reference(jsonNode.id).deselect_all();
  60092. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60093. }));
  60094. // rect area horizontal
  60095. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_horizontal_rect', () => {
  60096. $('#menu_measurements').next().slideDown();
  60097. var measurement = this.measuringTool.startInsertion({
  60098. showDistances: true,
  60099. showArea: true,
  60100. closed: true,
  60101. minMarkers: 4,
  60102. maxMarkers: 4,
  60103. //showGuideLine: true: true,
  60104. isRect: true,
  60105. faceDirection: "horizontal",
  60106. measureType: 'Hor Rect Area'
  60107. });
  60108. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60109. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60110. $.jstree.reference(jsonNode.id).deselect_all();
  60111. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60112. }));
  60113. // rect area vertical
  60114. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]area_vertical_rect', () => {
  60115. $('#menu_measurements').next().slideDown();
  60116. var measurement = this.measuringTool.startInsertion({
  60117. showDistances: true,
  60118. showArea: true,
  60119. closed: true,
  60120. minMarkers: 4,
  60121. maxMarkers: 4,
  60122. //showGuideLine: true: true,
  60123. isRect: true,
  60124. faceDirection: "vertical",
  60125. measureType: 'Ver Rect Area'
  60126. });
  60127. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60128. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60129. $.jstree.reference(jsonNode.id).deselect_all();
  60130. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60131. }));
  60132. // AREA
  60133. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/area.svg', '[title]prism', () => {
  60134. $('#menu_measurements').next().slideDown();
  60135. var measurement = this.measuringTool.startInsertion({
  60136. measureType: 'MulDistance Ring',
  60137. unit: 'metric'
  60138. });
  60139. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60140. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === measurement.uuid);
  60141. $.jstree.reference(jsonNode.id).deselect_all();
  60142. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60143. }));
  60144. // VOLUME
  60145. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/volume.svg', '[title]tt.volume_measurement', () => {
  60146. var volume = this.volumeTool.startInsertion();
  60147. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60148. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  60149. $.jstree.reference(jsonNode.id).deselect_all();
  60150. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60151. }));
  60152. // SPHERE VOLUME
  60153. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/sphere_distances.svg', '[title]tt.volume_measurement', () => {
  60154. var volume = this.volumeTool.startInsertion({
  60155. type: SphereVolume$2
  60156. });
  60157. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60158. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === volume.uuid);
  60159. $.jstree.reference(jsonNode.id).deselect_all();
  60160. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60161. }));
  60162. // PROFILE
  60163. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/profile.svg', '[title]tt.height_profile', () => {
  60164. $('#menu_measurements').next().slideDown();
  60165. ;
  60166. var profile = this.profileTool.startInsertion();
  60167. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60168. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === profile.uuid);
  60169. $.jstree.reference(jsonNode.id).deselect_all();
  60170. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60171. }));
  60172. // ANNOTATION
  60173. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/annotation.svg', '[title]tt.annotation', () => {
  60174. $('#menu_measurements').next().slideDown();
  60175. ;
  60176. var annotation = this.viewer.annotationTool.startInsertion();
  60177. var annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  60178. var jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  60179. $.jstree.reference(jsonNode.id).deselect_all();
  60180. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60181. }));
  60182. // REMOVE ALL
  60183. elToolbar.append(this.createToolIcon(Potree.resourcePath + '/icons/reset_tools.svg', '[title]tt.remove_all_measurement', () => {
  60184. this.viewer.scene.removeAllMeasurements();
  60185. }));
  60186. {
  60187. // SHOW / HIDE Measurements
  60188. var elShow = $("#measurement_options_show");
  60189. elShow.selectgroup({
  60190. title: "Show/Hide labels"
  60191. });
  60192. elShow.find("input").click(e => {
  60193. var show = e.target.value === "SHOW";
  60194. this.measuringTool.showLabels = show;
  60195. });
  60196. var currentShow = this.measuringTool.showLabels ? "SHOW" : "HIDE";
  60197. elShow.find("input[value=".concat(currentShow, "]")).trigger("click");
  60198. }
  60199. }
  60200. initScene() {
  60201. var elScene = $("#menu_scene");
  60202. var elObjects = elScene.next().find("#scene_objects");
  60203. var elProperties = elScene.next().find("#scene_object_properties");
  60204. {
  60205. var elExport = elScene.next().find("#scene_export");
  60206. var geoJSONIcon = "".concat(Potree.resourcePath, "/icons/file_geojson.svg");
  60207. var dxfIcon = "".concat(Potree.resourcePath, "/icons/file_dxf.svg");
  60208. var potreeIcon = "".concat(Potree.resourcePath, "/icons/file_potree.svg");
  60209. elExport.append("\n\t\t\t\tExport: <br>\n\t\t\t\t<a href=\"#\" download=\"measure.json\"><img name=\"geojson_export_button\" src=\"".concat(geoJSONIcon, "\" class=\"button-icon\" style=\"height: 24px\" /></a>\n\t\t\t\t<a href=\"#\" download=\"measure.dxf\"><img name=\"dxf_export_button\" src=\"").concat(dxfIcon, "\" class=\"button-icon\" style=\"height: 24px\" /></a>\n\t\t\t\t<a href=\"#\" download=\"potree.json5\"><img name=\"potree_export_button\" src=\"").concat(potreeIcon, "\" class=\"button-icon\" style=\"height: 24px\" /></a>\n\t\t\t"));
  60210. var elDownloadJSON = elExport.find("img[name=geojson_export_button]").parent();
  60211. elDownloadJSON.click(event => {
  60212. var scene = this.viewer.scene;
  60213. var measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  60214. if (measurements.length > 0) {
  60215. var geoJson = GeoJSONExporter.toString(measurements);
  60216. var url = window.URL.createObjectURL(new Blob([geoJson], {
  60217. type: 'data:application/octet-stream'
  60218. }));
  60219. elDownloadJSON.attr('href', url);
  60220. } else {
  60221. this.viewer.postError("nothing to export");
  60222. event.preventDefault();
  60223. }
  60224. });
  60225. var elDownloadDXF = elExport.find("img[name=dxf_export_button]").parent();
  60226. elDownloadDXF.click(event => {
  60227. var scene = this.viewer.scene;
  60228. var measurements = [...scene.measurements, ...scene.profiles, ...scene.volumes];
  60229. if (measurements.length > 0) {
  60230. var dxf = DXFExporter.toString(measurements);
  60231. var url = window.URL.createObjectURL(new Blob([dxf], {
  60232. type: 'data:application/octet-stream'
  60233. }));
  60234. elDownloadDXF.attr('href', url);
  60235. } else {
  60236. this.viewer.postError("no measurements to export");
  60237. event.preventDefault();
  60238. }
  60239. });
  60240. var elDownloadPotree = elExport.find("img[name=potree_export_button]").parent();
  60241. elDownloadPotree.click(event => {
  60242. var data = Potree.saveProject(this.viewer);
  60243. var dataString = lib.stringify(data, null, "\t");
  60244. var url = window.URL.createObjectURL(new Blob([dataString], {
  60245. type: 'data:application/octet-stream'
  60246. }));
  60247. elDownloadPotree.attr('href', url);
  60248. });
  60249. }
  60250. var propertiesPanel = new PropertiesPanel(elProperties, this.viewer);
  60251. propertiesPanel.setScene(this.viewer.scene);
  60252. localStorage.removeItem('jstree');
  60253. var tree = $("<div id=\"jstree_scene\"></div>");
  60254. elObjects.append(tree);
  60255. tree.jstree({
  60256. 'plugins': ["checkbox", "state"],
  60257. 'core': {
  60258. "dblclick_toggle": false,
  60259. "state": {
  60260. "checked": true
  60261. },
  60262. 'check_callback': true,
  60263. "expand_selected_onload": true
  60264. },
  60265. "checkbox": {
  60266. "keep_selected_style": true,
  60267. "three_state": false,
  60268. "whole_node": false,
  60269. "tie_selection": false
  60270. }
  60271. });
  60272. var createNode = (parent, text, icon, object) => {
  60273. var nodeID = tree.jstree('create_node', parent, {
  60274. "text": text,
  60275. "icon": icon,
  60276. "data": object
  60277. }, "last", false, false);
  60278. if (object.visible) {
  60279. tree.jstree('check_node', nodeID);
  60280. } else {
  60281. tree.jstree('uncheck_node', nodeID);
  60282. }
  60283. return nodeID;
  60284. };
  60285. var pcID = tree.jstree('create_node', "#", {
  60286. "text": "<b>Point Clouds</b>",
  60287. "id": "pointclouds"
  60288. }, "last", false, false);
  60289. var measurementID = tree.jstree('create_node', "#", {
  60290. "text": "<b>Measurements</b>",
  60291. "id": "measurements"
  60292. }, "last", false, false);
  60293. var annotationsID = tree.jstree('create_node', "#", {
  60294. "text": "<b>Annotations</b>",
  60295. "id": "annotations"
  60296. }, "last", false, false);
  60297. var otherID = tree.jstree('create_node', "#", {
  60298. "text": "<b>Other</b>",
  60299. "id": "other"
  60300. }, "last", false, false);
  60301. var vectorsID = tree.jstree('create_node', "#", {
  60302. "text": "<b>Vectors</b>",
  60303. "id": "vectors"
  60304. }, "last", false, false);
  60305. var imagesID = tree.jstree('create_node', "#", {
  60306. "text": "<b> Images</b>",
  60307. "id": "images"
  60308. }, "last", false, false);
  60309. tree.jstree("check_node", pcID);
  60310. tree.jstree("check_node", measurementID);
  60311. tree.jstree("check_node", annotationsID);
  60312. tree.jstree("check_node", otherID);
  60313. tree.jstree("check_node", vectorsID);
  60314. tree.jstree("check_node", imagesID);
  60315. tree.on('create_node.jstree', (e, data) => {
  60316. tree.jstree("open_all");
  60317. });
  60318. tree.on("select_node.jstree", (e, data) => {
  60319. var object = data.node.data;
  60320. propertiesPanel.set(object);
  60321. this.viewer.inputHandler.deselectAll();
  60322. if (object instanceof Volume$1) {
  60323. this.viewer.inputHandler.toggleSelection(object);
  60324. }
  60325. $(this.viewer.renderer.domElement).focus();
  60326. });
  60327. tree.on("deselect_node.jstree", (e, data) => {
  60328. propertiesPanel.set(null);
  60329. });
  60330. tree.on("delete_node.jstree", (e, data) => {
  60331. propertiesPanel.set(null);
  60332. });
  60333. tree.on('dblclick', '.jstree-anchor', e => {
  60334. var instance = $.jstree.reference(e.target);
  60335. var node = instance.get_node(e.target);
  60336. var object = node.data;
  60337. // ignore double click on checkbox
  60338. if (e.target.classList.contains("jstree-checkbox")) {
  60339. return;
  60340. }
  60341. if (object instanceof PointCloudTree) {
  60342. var box = this.viewer.getBoundingBox([object]);
  60343. var _node = new Object3D();
  60344. _node.boundingBox = box;
  60345. this.viewer.zoomTo(_node, 1, 500);
  60346. } else if (object instanceof Measure$1) {
  60347. var points = object.points.map(p => p.position);
  60348. var _box = new Box3().setFromPoints(points);
  60349. if (_box.getSize(new Vector3()).length() == 0) {
  60350. _box.min = _box.max.clone(); //禁止相同
  60351. _box.expandByVector(new Vector3(1, 1, 1));
  60352. }
  60353. var _node2 = new Object3D();
  60354. _node2.boundingBox = _box;
  60355. this.viewer.zoomTo(_node2, 2, 500);
  60356. } else if (object instanceof Profile) {
  60357. var _points = object.points;
  60358. var _box2 = new Box3().setFromPoints(_points);
  60359. if (_box2.getSize(new Vector3()).length() > 0) {
  60360. var _node3 = new Object3D();
  60361. _node3.boundingBox = _box2;
  60362. this.viewer.zoomTo(_node3, 1, 500);
  60363. }
  60364. } else if (object instanceof Volume$1) {
  60365. var _box3 = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  60366. if (_box3.getSize(new Vector3()).length() > 0) {
  60367. var _node4 = new Object3D();
  60368. _node4.boundingBox = _box3;
  60369. this.viewer.zoomTo(_node4, 1, 500);
  60370. }
  60371. } else if (object instanceof Annotation) {
  60372. object.moveHere(this.viewer.scene.getActiveCamera());
  60373. } else if (object instanceof PolygonClipVolume) {
  60374. var dir = object.camera.getWorldDirection(new Vector3());
  60375. var target;
  60376. if (object.camera instanceof OrthographicCamera) {
  60377. dir.multiplyScalar(object.camera.right);
  60378. target = new Vector3().addVectors(object.camera.position, dir);
  60379. this.viewer.setCameraMode(CameraMode.ORTHOGRAPHIC);
  60380. } else if (object.camera instanceof PerspectiveCamera) {
  60381. dir.multiplyScalar(this.viewer.scene.view.radius);
  60382. target = new Vector3().addVectors(object.camera.position, dir);
  60383. this.viewer.setCameraMode(CameraMode.PERSPECTIVE);
  60384. }
  60385. this.viewer.scene.view.position.copy(object.camera.position);
  60386. this.viewer.scene.view.lookAt(target);
  60387. } else if (object.type === "SpotLight") {
  60388. var distance = object.distance > 0 ? object.distance / 4 : 5 * 1000;
  60389. var position = object.position;
  60390. var _target = new Vector3().addVectors(position, object.getWorldDirection(new Vector3()).multiplyScalar(distance));
  60391. this.viewer.scene.view.position.copy(object.position);
  60392. this.viewer.scene.view.lookAt(_target);
  60393. } else if (object instanceof Object3D) {
  60394. var _box4 = new Box3().setFromObject(object);
  60395. if (_box4.getSize(new Vector3()).length() > 0) {
  60396. var _node5 = new Object3D();
  60397. _node5.boundingBox = _box4;
  60398. this.viewer.zoomTo(_node5, 1, 500);
  60399. }
  60400. } else if (object instanceof OrientedImage) {
  60401. // TODO zoom to images
  60402. // let box = new THREE.Box3().setFromObject(object);
  60403. // if(box.getSize(new THREE.Vector3()).length() > 0){
  60404. // let node = new THREE.Object3D();
  60405. // node.boundingBox = box;
  60406. // this.viewer.zoomTo(node, 1, 500);
  60407. // }
  60408. } else if (object instanceof Images360) {
  60409. // TODO
  60410. } else if (object instanceof Geopackage) {
  60411. // TODO
  60412. }
  60413. });
  60414. tree.on("uncheck_node.jstree", (e, data) => {
  60415. var object = data.node.data;
  60416. if (object) {
  60417. object.visible = false;
  60418. }
  60419. });
  60420. tree.on("check_node.jstree", (e, data) => {
  60421. var object = data.node.data;
  60422. if (object) {
  60423. object.visible = true;
  60424. }
  60425. });
  60426. var onPointCloudAdded = e => {
  60427. var pointcloud = e.pointcloud;
  60428. var cloudIcon = "".concat(Potree.resourcePath, "/icons/cloud.svg");
  60429. var node = createNode(pcID, pointcloud.name, cloudIcon, pointcloud);
  60430. pointcloud.addEventListener("visibility_changed", () => {
  60431. if (pointcloud.visible) {
  60432. tree.jstree('check_node', node);
  60433. } else {
  60434. tree.jstree('uncheck_node', node);
  60435. }
  60436. });
  60437. };
  60438. var onMeasurementAdded = e => {
  60439. var measurement = e.measurement;
  60440. var icon = Utils.getMeasurementIcon(measurement);
  60441. createNode(measurementID, measurement.name, icon, measurement);
  60442. };
  60443. var onVolumeAdded = e => {
  60444. var volume = e.volume;
  60445. var icon = Utils.getMeasurementIcon(volume);
  60446. var node = createNode(measurementID, volume.name, icon, volume);
  60447. volume.addEventListener("visibility_changed", () => {
  60448. if (volume.visible) {
  60449. tree.jstree('check_node', node);
  60450. } else {
  60451. tree.jstree('uncheck_node', node);
  60452. }
  60453. });
  60454. };
  60455. var onProfileAdded = e => {
  60456. var profile = e.profile;
  60457. var icon = Utils.getMeasurementIcon(profile);
  60458. createNode(measurementID, profile.name, icon, profile);
  60459. };
  60460. var onAnnotationAdded = e => {
  60461. var annotation = e.annotation;
  60462. var annotationIcon = "".concat(Potree.resourcePath, "/icons/annotation.svg");
  60463. var parentID = this.annotationMapping.get(annotation.parent);
  60464. var annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  60465. this.annotationMapping.set(annotation, annotationID);
  60466. annotation.addEventListener("annotation_changed", e => {
  60467. var annotationsRoot = $("#jstree_scene").jstree().get_json("annotations");
  60468. var jsonNode = annotationsRoot.children.find(child => child.data.uuid === annotation.uuid);
  60469. $.jstree.reference(jsonNode.id).rename_node(jsonNode.id, annotation.title);
  60470. });
  60471. };
  60472. var onCameraAnimationAdded = e => {
  60473. var animation = e.animation;
  60474. var animationIcon = "".concat(Potree.resourcePath, "/icons/camera_animation.svg");
  60475. createNode(otherID, "animation", animationIcon, animation);
  60476. };
  60477. var onOrientedImagesAdded = e => {
  60478. var images = e.images;
  60479. var imagesIcon = "".concat(Potree.resourcePath, "/icons/picture.svg");
  60480. var node = createNode(imagesID, "images", imagesIcon, images);
  60481. images.addEventListener("visibility_changed", () => {
  60482. if (images.visible) {
  60483. tree.jstree('check_node', node);
  60484. } else {
  60485. tree.jstree('uncheck_node', node);
  60486. }
  60487. });
  60488. };
  60489. var onImages360Added = e => {
  60490. var images = e.images;
  60491. var imagesIcon = "".concat(Potree.resourcePath, "/icons/picture.svg");
  60492. var node = createNode(imagesID, "360° images", imagesIcon, images);
  60493. images.addEventListener("visibility_changed", () => {
  60494. if (images.visible) {
  60495. tree.jstree('check_node', node);
  60496. } else {
  60497. tree.jstree('uncheck_node', node);
  60498. }
  60499. });
  60500. };
  60501. var onGeopackageAdded = e => {
  60502. var geopackage = e.geopackage;
  60503. var geopackageIcon = "".concat(Potree.resourcePath, "/icons/triangle.svg");
  60504. var tree = $("#jstree_scene");
  60505. var parentNode = "vectors";
  60506. for (var layer of geopackage.node.children) {
  60507. var name = layer.name;
  60508. var shpPointsID = tree.jstree('create_node', parentNode, {
  60509. "text": name,
  60510. "icon": geopackageIcon,
  60511. "object": layer,
  60512. "data": layer
  60513. }, "last", false, false);
  60514. tree.jstree(layer.visible ? "check_node" : "uncheck_node", shpPointsID);
  60515. }
  60516. };
  60517. this.viewer.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  60518. this.viewer.scene.addEventListener("measurement_added", onMeasurementAdded);
  60519. this.viewer.scene.addEventListener("profile_added", onProfileAdded);
  60520. this.viewer.scene.addEventListener("volume_added", onVolumeAdded);
  60521. this.viewer.scene.addEventListener("camera_animation_added", onCameraAnimationAdded);
  60522. this.viewer.scene.addEventListener("oriented_images_added", onOrientedImagesAdded);
  60523. this.viewer.scene.addEventListener("360_images_added", onImages360Added);
  60524. this.viewer.scene.addEventListener("geopackage_added", onGeopackageAdded);
  60525. this.viewer.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  60526. this.viewer.scene.annotations.addEventListener("annotation_added", onAnnotationAdded);
  60527. var onMeasurementRemoved = e => {
  60528. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60529. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.measurement.uuid);
  60530. tree.jstree("delete_node", jsonNode.id);
  60531. };
  60532. var onVolumeRemoved = e => {
  60533. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60534. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  60535. tree.jstree("delete_node", jsonNode.id);
  60536. };
  60537. var onPolygonClipVolumeRemoved = e => {
  60538. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60539. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.volume.uuid);
  60540. tree.jstree("delete_node", jsonNode.id);
  60541. };
  60542. var onProfileRemoved = e => {
  60543. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60544. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === e.profile.uuid);
  60545. tree.jstree("delete_node", jsonNode.id);
  60546. };
  60547. this.viewer.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  60548. this.viewer.scene.addEventListener("volume_removed", onVolumeRemoved);
  60549. this.viewer.scene.addEventListener("polygon_clip_volume_removed", onPolygonClipVolumeRemoved);
  60550. this.viewer.scene.addEventListener("profile_removed", onProfileRemoved);
  60551. {
  60552. var annotationIcon = "".concat(Potree.resourcePath, "/icons/annotation.svg");
  60553. this.annotationMapping = new Map();
  60554. this.annotationMapping.set(this.viewer.scene.annotations, annotationsID);
  60555. this.viewer.scene.annotations.traverseDescendants(annotation => {
  60556. var parentID = this.annotationMapping.get(annotation.parent);
  60557. var annotationID = createNode(parentID, annotation.title, annotationIcon, annotation);
  60558. this.annotationMapping.set(annotation, annotationID);
  60559. });
  60560. }
  60561. var scene = this.viewer.scene;
  60562. for (var pointcloud of scene.pointclouds) {
  60563. onPointCloudAdded({
  60564. pointcloud: pointcloud
  60565. });
  60566. }
  60567. for (var measurement of scene.measurements) {
  60568. onMeasurementAdded({
  60569. measurement: measurement
  60570. });
  60571. }
  60572. for (var volume of [...scene.volumes, ...scene.polygonClipVolumes]) {
  60573. onVolumeAdded({
  60574. volume: volume
  60575. });
  60576. }
  60577. for (var animation of scene.cameraAnimations) {
  60578. onCameraAnimationAdded({
  60579. animation: animation
  60580. });
  60581. }
  60582. for (var images of scene.orientedImages) {
  60583. onOrientedImagesAdded({
  60584. images: images
  60585. });
  60586. }
  60587. for (var _images of scene.images360) {
  60588. onImages360Added({
  60589. images: _images
  60590. });
  60591. }
  60592. for (var geopackage of scene.geopackages) {
  60593. onGeopackageAdded({
  60594. geopackage: geopackage
  60595. });
  60596. }
  60597. for (var profile of scene.profiles) {
  60598. onProfileAdded({
  60599. profile: profile
  60600. });
  60601. }
  60602. {
  60603. createNode(otherID, "Camera", null, new Camera());
  60604. }
  60605. this.viewer.addEventListener("scene_changed", e => {
  60606. propertiesPanel.setScene(e.scene);
  60607. e.oldScene.removeEventListener("pointcloud_added", onPointCloudAdded);
  60608. e.oldScene.removeEventListener("measurement_added", onMeasurementAdded);
  60609. e.oldScene.removeEventListener("profile_added", onProfileAdded);
  60610. e.oldScene.removeEventListener("volume_added", onVolumeAdded);
  60611. e.oldScene.removeEventListener("polygon_clip_volume_added", onVolumeAdded);
  60612. e.oldScene.removeEventListener("measurement_removed", onMeasurementRemoved);
  60613. e.scene.addEventListener("pointcloud_added", onPointCloudAdded);
  60614. e.scene.addEventListener("measurement_added", onMeasurementAdded);
  60615. e.scene.addEventListener("profile_added", onProfileAdded);
  60616. e.scene.addEventListener("volume_added", onVolumeAdded);
  60617. e.scene.addEventListener("polygon_clip_volume_added", onVolumeAdded);
  60618. e.scene.addEventListener("measurement_removed", onMeasurementRemoved);
  60619. });
  60620. }
  60621. initClippingTool() {
  60622. this.viewer.addEventListener("cliptask_changed", event => {
  60623. console.log("TODO");
  60624. });
  60625. this.viewer.addEventListener("clipmethod_changed", event => {
  60626. console.log("TODO");
  60627. });
  60628. {
  60629. var elClipTask = $("#cliptask_options");
  60630. elClipTask.selectgroup({
  60631. title: "Clip Task"
  60632. });
  60633. elClipTask.find("input").click(e => {
  60634. this.viewer.setClipTask(ClipTask[e.target.value]);
  60635. });
  60636. var currentClipTask = Object.keys(ClipTask).filter(key => ClipTask[key] === this.viewer.clipTask);
  60637. elClipTask.find("input[value=".concat(currentClipTask, "]")).trigger("click");
  60638. }
  60639. {
  60640. var elClipMethod = $("#clipmethod_options");
  60641. elClipMethod.selectgroup({
  60642. title: "Clip Method"
  60643. });
  60644. elClipMethod.find("input").click(e => {
  60645. this.viewer.setClipMethod(ClipMethod[e.target.value]);
  60646. });
  60647. var currentClipMethod = Object.keys(ClipMethod).filter(key => ClipMethod[key] === this.viewer.clipMethod);
  60648. elClipMethod.find("input[value=".concat(currentClipMethod, "]")).trigger("click");
  60649. }
  60650. var clippingToolBar = $("#clipping_tools");
  60651. // CLIP VOLUME
  60652. clippingToolBar.append(this.createToolIcon(Potree.resourcePath + '/icons/clip_volume.svg', '[title]tt.clip_volume', () => {
  60653. var item = this.volumeTool.startInsertion({
  60654. clip: true
  60655. });
  60656. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60657. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  60658. $.jstree.reference(jsonNode.id).deselect_all();
  60659. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60660. }));
  60661. // CLIP POLYGON
  60662. clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/clip-polygon.svg", "[title]tt.clip_polygon", () => {
  60663. var item = this.viewer.clippingTool.startInsertion({
  60664. type: "polygon"
  60665. });
  60666. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60667. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  60668. $.jstree.reference(jsonNode.id).deselect_all();
  60669. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60670. }));
  60671. {
  60672. // SCREEN BOX SELECT
  60673. var boxSelectTool = new ScreenBoxSelectTool(this.viewer);
  60674. clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/clip-screen.svg", "[title]tt.screen_clip_box", () => {
  60675. if (!(this.viewer.scene.getActiveCamera() instanceof OrthographicCamera)) {
  60676. this.viewer.postMessage("Switch to Orthographic Camera Mode before using the Screen-Box-Select tool.", {
  60677. duration: 2000
  60678. });
  60679. return;
  60680. }
  60681. var item = boxSelectTool.startInsertion();
  60682. var measurementsRoot = $("#jstree_scene").jstree().get_json("measurements");
  60683. var jsonNode = measurementsRoot.children.find(child => child.data.uuid === item.uuid);
  60684. $.jstree.reference(jsonNode.id).deselect_all();
  60685. $.jstree.reference(jsonNode.id).select_node(jsonNode.id);
  60686. }));
  60687. }
  60688. {
  60689. // REMOVE CLIPPING TOOLS
  60690. clippingToolBar.append(this.createToolIcon(Potree.resourcePath + "/icons/remove.svg", "[title]tt.remove_all_clipping_volumes", () => {
  60691. this.viewer.scene.removeAllClipVolumes();
  60692. }));
  60693. }
  60694. }
  60695. initFilters() {
  60696. this.initClassificationList();
  60697. this.initReturnFilters();
  60698. this.initGPSTimeFilters();
  60699. this.initPointSourceIDFilters();
  60700. }
  60701. initReturnFilters() {
  60702. var elReturnFilterPanel = $('#return_filter_panel');
  60703. {
  60704. // RETURN NUMBER
  60705. var sldReturnNumber = elReturnFilterPanel.find('#sldReturnNumber');
  60706. var lblReturnNumber = elReturnFilterPanel.find('#lblReturnNumber');
  60707. sldReturnNumber.slider({
  60708. range: true,
  60709. min: 0,
  60710. max: 7,
  60711. step: 1,
  60712. values: [0, 7],
  60713. slide: (event, ui) => {
  60714. this.viewer.setFilterReturnNumberRange(ui.values[0], ui.values[1]);
  60715. }
  60716. });
  60717. var onReturnNumberChanged = event => {
  60718. var [from, to] = this.viewer.filterReturnNumberRange;
  60719. lblReturnNumber[0].innerHTML = "".concat(from, " to ").concat(to);
  60720. sldReturnNumber.slider({
  60721. values: [from, to]
  60722. });
  60723. };
  60724. this.viewer.addEventListener('filter_return_number_range_changed', onReturnNumberChanged);
  60725. onReturnNumberChanged();
  60726. }
  60727. {
  60728. // NUMBER OF RETURNS
  60729. var sldNumberOfReturns = elReturnFilterPanel.find('#sldNumberOfReturns');
  60730. var lblNumberOfReturns = elReturnFilterPanel.find('#lblNumberOfReturns');
  60731. sldNumberOfReturns.slider({
  60732. range: true,
  60733. min: 0,
  60734. max: 7,
  60735. step: 1,
  60736. values: [0, 7],
  60737. slide: (event, ui) => {
  60738. this.viewer.setFilterNumberOfReturnsRange(ui.values[0], ui.values[1]);
  60739. }
  60740. });
  60741. var onNumberOfReturnsChanged = event => {
  60742. var [from, to] = this.viewer.filterNumberOfReturnsRange;
  60743. lblNumberOfReturns[0].innerHTML = "".concat(from, " to ").concat(to);
  60744. sldNumberOfReturns.slider({
  60745. values: [from, to]
  60746. });
  60747. };
  60748. this.viewer.addEventListener('filter_number_of_returns_range_changed', onNumberOfReturnsChanged);
  60749. onNumberOfReturnsChanged();
  60750. }
  60751. }
  60752. initGPSTimeFilters() {
  60753. var elGPSTimeFilterPanel = $('#gpstime_filter_panel');
  60754. {
  60755. var slider = new HierarchicalSlider({
  60756. levels: 4,
  60757. slide: event => {
  60758. this.viewer.setFilterGPSTimeRange(...event.values);
  60759. }
  60760. });
  60761. var initialized = false;
  60762. var initialize = () => {
  60763. var elRangeContainer = $("#gpstime_multilevel_range_container");
  60764. elRangeContainer[0].prepend(slider.element);
  60765. var extent = this.viewer.getGpsTimeExtent();
  60766. slider.setRange(extent);
  60767. slider.setValues(extent);
  60768. initialized = true;
  60769. };
  60770. this.viewer.addEventListener("update", e => {
  60771. var extent = this.viewer.getGpsTimeExtent();
  60772. var gpsTimeAvailable = extent[0] !== Infinity;
  60773. if (!initialized && gpsTimeAvailable) {
  60774. initialize();
  60775. }
  60776. slider.setRange(extent); //高耗cpu
  60777. });
  60778. }
  60779. {
  60780. var txtGpsTime = elGPSTimeFilterPanel.find("#txtGpsTime");
  60781. var btnFindGpsTime = elGPSTimeFilterPanel.find("#btnFindGpsTime");
  60782. var targetTime = null;
  60783. txtGpsTime.on("input", e => {
  60784. var str = txtGpsTime.val();
  60785. if (!isNaN(str)) {
  60786. var value = parseFloat(str);
  60787. targetTime = value;
  60788. txtGpsTime.css("background-color", "");
  60789. } else {
  60790. targetTime = null;
  60791. txtGpsTime.css("background-color", "#ff9999");
  60792. }
  60793. });
  60794. btnFindGpsTime.click(() => {
  60795. if (targetTime !== null) {
  60796. viewer.moveToGpsTimeVicinity(targetTime);
  60797. }
  60798. });
  60799. }
  60800. }
  60801. initPointSourceIDFilters() {
  60802. var elPointSourceIDFilterPanel = $('#pointsourceid_filter_panel');
  60803. {
  60804. var slider = new HierarchicalSlider({
  60805. levels: 4,
  60806. range: [0, 65535],
  60807. precision: 1,
  60808. slide: event => {
  60809. var values = event.values;
  60810. this.viewer.setFilterPointSourceIDRange(values[0], values[1]);
  60811. }
  60812. });
  60813. var initialized = false;
  60814. var initialize = () => {
  60815. elPointSourceIDFilterPanel[0].prepend(slider.element);
  60816. initialized = true;
  60817. };
  60818. this.viewer.addEventListener("update", e => {
  60819. var extent = this.viewer.filterPointSourceIDRange;
  60820. if (!initialized) {
  60821. initialize();
  60822. slider.setValues(extent);
  60823. }
  60824. });
  60825. }
  60826. // let lblPointSourceID = elPointSourceIDFilterPanel.find("#lblPointSourceID");
  60827. // let elPointSourceID = elPointSourceIDFilterPanel.find("#spnPointSourceID");
  60828. // let slider = new ZoomableSlider();
  60829. // elPointSourceID[0].appendChild(slider.element);
  60830. // slider.update();
  60831. // slider.change( () => {
  60832. // let range = slider.chosenRange;
  60833. // this.viewer.setFilterPointSourceIDRange(range[0], range[1]);
  60834. // });
  60835. // let onPointSourceIDExtentChanged = (event) => {
  60836. // let range = this.viewer.filterPointSourceIDExtent;
  60837. // slider.setVisibleRange(range);
  60838. // };
  60839. // let onPointSourceIDChanged = (event) => {
  60840. // let range = this.viewer.filterPointSourceIDRange;
  60841. // let precision = 1;
  60842. // let from = `${Utils.addCommas(range[0].toFixed(precision))}`;
  60843. // let to = `${Utils.addCommas(range[1].toFixed(precision))}`;
  60844. // lblPointSourceID[0].innerHTML = `${from} to ${to}`;
  60845. // slider.setRange(range);
  60846. // };
  60847. // this.viewer.addEventListener('filter_point_source_id_range_changed', onPointSourceIDChanged);
  60848. // this.viewer.addEventListener('filter_point_source_id_extent_changed', onPointSourceIDExtentChanged);
  60849. }
  60850. initClassificationList() {
  60851. var elClassificationList = $('#classificationList');
  60852. var addClassificationItem = (code, name) => {
  60853. var classification = this.viewer.classifications[code];
  60854. var inputID = 'chkClassification_' + code;
  60855. var colorPickerID = 'colorPickerClassification_' + code;
  60856. var checked = classification.visible ? "checked" : "";
  60857. var element = $("\n\t\t\t\t<li>\n\t\t\t\t\t<label style=\"whitespace: nowrap; display: flex\">\n\t\t\t\t\t\t<input id=\"".concat(inputID, "\" type=\"checkbox\" ").concat(checked, "/>\n\t\t\t\t\t\t<span style=\"flex-grow: 1\">").concat(name, "</span>\n\t\t\t\t\t\t<input id=\"").concat(colorPickerID, "\" style=\"zoom: 0.5\" />\n\t\t\t\t\t</label>\n\t\t\t\t</li>\n\t\t\t"));
  60858. var elInput = element.find('input');
  60859. var elColorPicker = element.find("#".concat(colorPickerID));
  60860. elInput.click(event => {
  60861. this.viewer.setClassificationVisibility(code, event.target.checked);
  60862. });
  60863. var defaultColor = classification.color.map(c => c * 255).join(", ");
  60864. defaultColor = "rgb(".concat(defaultColor, ")");
  60865. elColorPicker.spectrum({
  60866. // flat: true,
  60867. color: defaultColor,
  60868. showInput: true,
  60869. preferredFormat: 'rgb',
  60870. cancelText: '',
  60871. chooseText: 'Apply',
  60872. move: color => {
  60873. var rgb = color.toRgb();
  60874. var c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  60875. classification.color = c;
  60876. },
  60877. change: color => {
  60878. var rgb = color.toRgb();
  60879. var c = [rgb.r / 255, rgb.g / 255, rgb.b / 255, 1];
  60880. classification.color = c;
  60881. }
  60882. });
  60883. elClassificationList.append(element);
  60884. };
  60885. var addToggleAllButton = () => {
  60886. // toggle all button
  60887. var element = $("\n\t\t\t\t<li>\n\t\t\t\t\t<label style=\"whitespace: nowrap\">\n\t\t\t\t\t\t<input id=\"toggleClassificationFilters\" type=\"checkbox\" checked/>\n\t\t\t\t\t\t<span>show/hide all</span>\n\t\t\t\t\t</label>\n\t\t\t\t</li>\n\t\t\t");
  60888. var elInput = element.find('input');
  60889. elInput.click(event => {
  60890. this.viewer.toggleAllClassificationsVisibility();
  60891. });
  60892. elClassificationList.append(element);
  60893. };
  60894. var addInvertButton = () => {
  60895. var element = $("\n\t\t\t\t<li>\n\t\t\t\t\t<input type=\"button\" value=\"invert\" />\n\t\t\t\t</li>\n\t\t\t");
  60896. var elInput = element.find('input');
  60897. elInput.click(() => {
  60898. var classifications = this.viewer.classifications;
  60899. for (var key of Object.keys(classifications)) {
  60900. var value = classifications[key];
  60901. this.viewer.setClassificationVisibility(key, !value.visible);
  60902. }
  60903. });
  60904. elClassificationList.append(element);
  60905. };
  60906. var populate = () => {
  60907. addToggleAllButton();
  60908. for (var classID in this.viewer.classifications) {
  60909. addClassificationItem(classID, this.viewer.classifications[classID].name);
  60910. }
  60911. addInvertButton();
  60912. };
  60913. populate();
  60914. this.viewer.addEventListener("classifications_changed", () => {
  60915. elClassificationList.empty();
  60916. populate();
  60917. });
  60918. this.viewer.addEventListener("classification_visibility_changed", () => {
  60919. {
  60920. // set checked state of classification buttons
  60921. for (var classID of Object.keys(this.viewer.classifications)) {
  60922. var classValue = this.viewer.classifications[classID];
  60923. var elItem = elClassificationList.find("#chkClassification_".concat(classID));
  60924. elItem.prop("checked", classValue.visible);
  60925. }
  60926. }
  60927. {
  60928. // set checked state of toggle button based on state of all other buttons
  60929. var numVisible = 0;
  60930. var numItems = 0;
  60931. for (var key of Object.keys(this.viewer.classifications)) {
  60932. if (this.viewer.classifications[key].visible) {
  60933. numVisible++;
  60934. }
  60935. numItems++;
  60936. }
  60937. var allVisible = numVisible === numItems;
  60938. var elToggle = elClassificationList.find("#toggleClassificationFilters");
  60939. elToggle.prop("checked", allVisible);
  60940. }
  60941. });
  60942. }
  60943. initAccordion() {
  60944. var _this = this;
  60945. $('.accordion > h3').each(function () {
  60946. var header = $(this);
  60947. var content = $(this).next();
  60948. //header.addClass('accordion-header ui-widget');
  60949. //content.addClass('accordion-content ui-widget');
  60950. content.hide();
  60951. header.click(() => {
  60952. content.slideToggle();
  60953. });
  60954. });
  60955. var languages = [["EN", "en"], ["FR", "fr"], ["DE", "de"], ["JP", "jp"], ["ES", "es"], ["SE", "se"], ["ZH", "zh"]];
  60956. var elLanguages = $('#potree_languages');
  60957. var _loop = function _loop() {
  60958. var [key, value] = languages[i];
  60959. var element = $("<a>".concat(key, "</a>"));
  60960. element.click(() => _this.viewer.setLanguage(value));
  60961. if (i === 0) {
  60962. element.css("margin-left", "30px");
  60963. }
  60964. elLanguages.append(element);
  60965. if (i < languages.length - 1) {
  60966. elLanguages.append($(document.createTextNode(' - ')));
  60967. }
  60968. };
  60969. for (var i = 0; i < languages.length; i++) {
  60970. _loop();
  60971. }
  60972. // to close all, call
  60973. // $(".accordion > div").hide()
  60974. // to open the, for example, tool menu, call:
  60975. // $("#menu_tools").next().show()
  60976. }
  60977. initAppearance() {
  60978. var sldPointBudget = this.dom.find('#sldPointBudget');
  60979. sldPointBudget.slider({
  60980. value: this.viewer.getPointBudget(),
  60981. min: 100 * 1000,
  60982. max: 10 * 1000 * 1000,
  60983. step: 1000,
  60984. slide: (event, ui) => {
  60985. this.viewer.setPointBudget(ui.value);
  60986. }
  60987. });
  60988. this.dom.find('#sldFOV').slider({
  60989. value: this.viewer.getFOV(),
  60990. min: 20,
  60991. max: 100,
  60992. step: 1,
  60993. slide: (event, ui) => {
  60994. this.viewer.setFOV(ui.value);
  60995. }
  60996. });
  60997. $('#sldEDLRadius').slider({
  60998. value: this.viewer.getEDLRadius(),
  60999. min: 1,
  61000. max: 4,
  61001. step: 0.01,
  61002. slide: (event, ui) => {
  61003. this.viewer.setEDLRadius(ui.value);
  61004. }
  61005. });
  61006. $('#sldEDLStrength').slider({
  61007. value: this.viewer.getEDLStrength(),
  61008. min: 0,
  61009. max: 5,
  61010. step: 0.01,
  61011. slide: (event, ui) => {
  61012. this.viewer.setEDLStrength(ui.value);
  61013. }
  61014. });
  61015. $('#sldEDLOpacity').slider({
  61016. value: this.viewer.getEDLOpacity(),
  61017. min: 0,
  61018. max: 1,
  61019. step: 0.01,
  61020. slide: (event, ui) => {
  61021. this.viewer.setEDLOpacity(ui.value);
  61022. }
  61023. });
  61024. this.viewer.addEventListener('point_budget_changed', event => {
  61025. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  61026. sldPointBudget.slider({
  61027. value: this.viewer.getPointBudget()
  61028. });
  61029. });
  61030. this.viewer.addEventListener('fov_changed', event => {
  61031. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  61032. $('#sldFOV').slider({
  61033. value: this.viewer.getFOV()
  61034. });
  61035. });
  61036. this.viewer.addEventListener('use_edl_changed', event => {
  61037. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  61038. });
  61039. this.viewer.addEventListener('edl_radius_changed', event => {
  61040. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  61041. $('#sldEDLRadius').slider({
  61042. value: this.viewer.getEDLRadius()
  61043. });
  61044. });
  61045. this.viewer.addEventListener('edl_strength_changed', event => {
  61046. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  61047. $('#sldEDLStrength').slider({
  61048. value: this.viewer.getEDLStrength()
  61049. });
  61050. });
  61051. this.viewer.addEventListener('background_changed', event => {
  61052. $("input[name=background][value='" + this.viewer.getBackground() + "']").prop('checked', true);
  61053. });
  61054. $('#lblPointBudget')[0].innerHTML = Utils.addCommas(this.viewer.getPointBudget());
  61055. $('#lblFOV')[0].innerHTML = parseInt(this.viewer.getFOV());
  61056. $('#lblEDLRadius')[0].innerHTML = this.viewer.getEDLRadius().toFixed(1);
  61057. $('#lblEDLStrength')[0].innerHTML = this.viewer.getEDLStrength().toFixed(1);
  61058. $('#chkEDLEnabled')[0].checked = this.viewer.getEDLEnabled();
  61059. {
  61060. var elBackground = $("#background_options");
  61061. elBackground.selectgroup();
  61062. elBackground.find("input").click(e => {
  61063. this.viewer.setBackground(e.target.value);
  61064. });
  61065. var currentBackground = this.viewer.getBackground();
  61066. try {
  61067. $("input[name=background_options][value=".concat(currentBackground, "]")).trigger("click");
  61068. } catch (e) {}
  61069. }
  61070. $('#chkEDLEnabled').click(() => {
  61071. this.viewer.setEDLEnabled($('#chkEDLEnabled').prop("checked"));
  61072. });
  61073. }
  61074. initNavigation() {
  61075. var elNavigation = $('#navigation');
  61076. var sldMoveSpeed = $('#sldMoveSpeed');
  61077. var lblMoveSpeed = $('#lblMoveSpeed');
  61078. elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/earth_controls_1.png', '[title]tt.earth_control', () => {
  61079. this.viewer.setControls(this.viewer.earthControls);
  61080. }));
  61081. elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/fps_controls.svg', '[title]tt.flight_control', () => {
  61082. this.viewer.setControls(this.viewer.fpControls);
  61083. this.viewer.fpControls.lockElevation = false;
  61084. }));
  61085. elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/helicopter_controls.svg', '[title]tt.heli_control', () => {
  61086. this.viewer.setControls(this.viewer.fpControls);
  61087. this.viewer.fpControls.lockElevation = true;
  61088. }));
  61089. elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/orbit_controls.svg', '[title]tt.orbit_control', () => {
  61090. this.viewer.setControls(this.viewer.orbitControls);
  61091. }));
  61092. elNavigation.append(this.createToolIcon(Potree.resourcePath + '/icons/focus.svg', '[title]tt.focus_control', () => {
  61093. this.viewer.fitToScreen();
  61094. }));
  61095. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/navigation_cube.svg", "[title]tt.navigation_cube_control", () => {
  61096. this.viewer.toggleNavigationCube();
  61097. }));
  61098. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/images/compas.svg", "[title]tt.compass", () => {
  61099. var visible = !this.viewer.compass.isVisible();
  61100. this.viewer.compass.setVisible(visible);
  61101. }));
  61102. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/camera_animation.svg", "[title]tt.camera_animation", () => {
  61103. var animation = CameraAnimation$1.defaultFromView(this.viewer);
  61104. viewer.scene.addCameraAnimation(animation);
  61105. }));
  61106. elNavigation.append("<br>");
  61107. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/left.svg", "[title]tt.left_view_control", () => {
  61108. this.viewer.setLeftView();
  61109. }));
  61110. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/right.svg", "[title]tt.right_view_control", () => {
  61111. this.viewer.setRightView();
  61112. }));
  61113. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/front.svg", "[title]tt.front_view_control", () => {
  61114. this.viewer.setFrontView();
  61115. }));
  61116. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/back.svg", "[title]tt.back_view_control", () => {
  61117. this.viewer.setBackView();
  61118. }));
  61119. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/top.svg", "[title]tt.top_view_control", () => {
  61120. this.viewer.setTopView();
  61121. }));
  61122. elNavigation.append(this.createToolIcon(Potree.resourcePath + "/icons/bottom.svg", "[title]tt.bottom_view_control", () => {
  61123. this.viewer.setBottomView();
  61124. }));
  61125. var elCameraProjection = $("\n\t\t\t<selectgroup id=\"camera_projection_options\">\n\t\t\t\t<option id=\"camera_projection_options_perspective\" value=\"PERSPECTIVE\">Perspective</option>\n\t\t\t\t<option id=\"camera_projection_options_orthigraphic\" value=\"ORTHOGRAPHIC\">Orthographic</option>\n\t\t\t</selectgroup>\n\t\t");
  61126. elNavigation.append(elCameraProjection);
  61127. elCameraProjection.selectgroup({
  61128. title: "Camera Projection"
  61129. });
  61130. elCameraProjection.find("input").click(e => {
  61131. this.viewer.setCameraMode(CameraMode[e.target.value]);
  61132. });
  61133. var cameraMode = Object.keys(CameraMode).filter(key => CameraMode[key] === this.viewer.scene.cameraMode);
  61134. elCameraProjection.find("input[value=".concat(cameraMode, "]")).trigger("click");
  61135. var speedRange = new Vector2(1, 10 * 1000);
  61136. var toLinearSpeed = value => {
  61137. return Math.pow(value, 4) * speedRange.y + speedRange.x;
  61138. };
  61139. var toExpSpeed = value => {
  61140. return Math.pow((value - speedRange.x) / speedRange.y, 1 / 4);
  61141. };
  61142. sldMoveSpeed.slider({
  61143. value: toExpSpeed(this.viewer.getMoveSpeed()),
  61144. min: 0,
  61145. max: 1,
  61146. step: 0.01,
  61147. slide: (event, ui) => {
  61148. this.viewer.setMoveSpeed(toLinearSpeed(ui.value));
  61149. }
  61150. });
  61151. this.viewer.addEventListener('move_speed_changed', event => {
  61152. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  61153. sldMoveSpeed.slider({
  61154. value: toExpSpeed(this.viewer.getMoveSpeed())
  61155. });
  61156. });
  61157. lblMoveSpeed.html(this.viewer.getMoveSpeed().toFixed(1));
  61158. }
  61159. initSettings() {
  61160. {
  61161. $('#sldMinNodeSize').slider({
  61162. value: this.viewer.getMinNodeSize(),
  61163. min: 0,
  61164. max: 1000,
  61165. step: 0.01,
  61166. slide: (event, ui) => {
  61167. this.viewer.setMinNodeSize(ui.value);
  61168. }
  61169. });
  61170. this.viewer.addEventListener('minnodesize_changed', event => {
  61171. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  61172. $('#sldMinNodeSize').slider({
  61173. value: this.viewer.getMinNodeSize()
  61174. });
  61175. });
  61176. $('#lblMinNodeSize').html(parseInt(this.viewer.getMinNodeSize()));
  61177. }
  61178. {
  61179. var elSplatQuality = $("#splat_quality_options");
  61180. elSplatQuality.selectgroup({
  61181. title: "Splat Quality"
  61182. });
  61183. elSplatQuality.find("input").click(e => {
  61184. if (e.target.value === "standard") {
  61185. this.viewer.useHQ = false;
  61186. } else if (e.target.value === "hq") {
  61187. this.viewer.useHQ = true;
  61188. }
  61189. });
  61190. var currentQuality = this.viewer.useHQ ? "hq" : "standard";
  61191. elSplatQuality.find("input[value=".concat(currentQuality, "]")).trigger("click");
  61192. }
  61193. $('#show_bounding_box').click(() => {
  61194. this.viewer.setShowBoundingBox($('#show_bounding_box').prop("checked"));
  61195. });
  61196. $('#set_freeze').click(() => {
  61197. this.viewer.setFreeze($('#set_freeze').prop("checked"));
  61198. });
  61199. }
  61200. }
  61201. class AnnotationTool extends EventDispatcher$1 {
  61202. constructor(viewer) {
  61203. super();
  61204. this.viewer = viewer;
  61205. this.renderer = viewer.renderer;
  61206. this.sg = new SphereGeometry(0.1);
  61207. this.sm = new MeshNormalMaterial();
  61208. this.s = new Mesh(this.sg, this.sm);
  61209. }
  61210. startInsertion() {
  61211. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  61212. var domElement = this.viewer.renderer.domElement;
  61213. var annotation = new Annotation({
  61214. position: [589748.270, 231444.540, 753.675],
  61215. title: "Annotation Title",
  61216. description: "Annotation Description"
  61217. });
  61218. this.dispatchEvent({
  61219. type: 'start_inserting_annotation',
  61220. annotation: annotation
  61221. });
  61222. var annotations = this.viewer.scene.annotations;
  61223. annotations.add(annotation);
  61224. var callbacks = {
  61225. cancel: null,
  61226. finish: null
  61227. };
  61228. var insertionCallback = e => {
  61229. if (e.button === MOUSE.LEFT) {
  61230. callbacks.finish();
  61231. } else if (e.button === MOUSE.RIGHT) {
  61232. callbacks.cancel();
  61233. }
  61234. };
  61235. callbacks.cancel = e => {
  61236. annotations.remove(annotation);
  61237. domElement.removeEventListener('mouseup', insertionCallback, true);
  61238. };
  61239. callbacks.finish = e => {
  61240. domElement.removeEventListener('mouseup', insertionCallback, true);
  61241. };
  61242. domElement.addEventListener('mouseup', insertionCallback, true);
  61243. var drag = e => {
  61244. var I = Utils.getMousePointCloudIntersection(e.drag.end, e.viewer.scene.getActiveCamera(), e.viewer, e.viewer.scene.pointclouds, {
  61245. pickClipped: true
  61246. });
  61247. if (I) {
  61248. this.s.position.copy(I.location);
  61249. annotation.position.copy(I.location);
  61250. }
  61251. };
  61252. var drop = e => {
  61253. viewer.scene.scene.remove(this.s);
  61254. this.s.removeEventListener("drag", drag);
  61255. this.s.removeEventListener("drop", drop);
  61256. };
  61257. this.s.addEventListener('drag', drag);
  61258. this.s.addEventListener('drop', drop);
  61259. this.viewer.scene.scene.add(this.s);
  61260. this.viewer.inputHandler.startDragging(this.s);
  61261. return annotation;
  61262. }
  61263. update() {
  61264. // let camera = this.viewer.scene.getActiveCamera();
  61265. // let domElement = this.renderer.domElement;
  61266. // let measurements = this.viewer.scene.measurements;
  61267. // const renderAreaSize = this.renderer.getSize(new THREE.Vector2());
  61268. // let clientWidth = renderAreaSize.width;
  61269. // let clientHeight = renderAreaSize.height;
  61270. }
  61271. render() {
  61272. //this.viewer.renderer.render(this.scene, this.viewer.scene.getActiveCamera());
  61273. }
  61274. }
  61275. ;
  61276. //处理cursor优先级
  61277. var CursorDeal = {
  61278. priorityEvent: [
  61279. //在前面的优先级高
  61280. {
  61281. 'zoomInCloud': 'zoom-in'
  61282. }, {
  61283. 'hoverPano': 'pointer'
  61284. }, {
  61285. 'connectPano': "url({Potree.resourcePath}/images/connect.png),auto"
  61286. }, {
  61287. 'disconnectPano': "url({Potree.resourcePath}/images/connect-dis.png),auto"
  61288. }, {
  61289. 'hoverLine': 'pointer'
  61290. }, {
  61291. 'hoverTranHandle': 'grab'
  61292. }, {
  61293. "movePointcloud": 'move'
  61294. }, {
  61295. "polygon_isIntersectSelf": 'not-allowed'
  61296. }, {
  61297. "polygon_AtWrongPlace": 'not-allowed'
  61298. }, {
  61299. 'delPoint': 'url("https://4dkk.4dage.com/v4-test/www/sdk/images/polygon_mark/pic_pen_sub.png"), auto'
  61300. }, {
  61301. "markerMove": 'grab'
  61302. }, {
  61303. 'addPoint': 'url("https://4dkk.4dage.com/v4-test/www/sdk/images/polygon_mark/pic_pen_add.png"), auto'
  61304. }, {
  61305. 'mapClipMove': 'move'
  61306. }, {
  61307. 'mapClipRotate': "url({Potree.resourcePath}/images/rotate-cursor.png),auto"
  61308. }, {
  61309. 'rotatePointcloud': "url({Potree.resourcePath}/images/rotate-cursor.png),auto"
  61310. }, {
  61311. 'siteModelFloorDrag': 'row-resize'
  61312. }, {
  61313. 'addSth': 'cell'
  61314. } //or crosshair
  61315. ],
  61316. list: [],
  61317. //当前存在的cursor状态
  61318. currentCursorIndex: null,
  61319. init: function init(viewer, viewers) {
  61320. this.priorityEvent.forEach(e => {
  61321. //刚开始Potree.resourcePath没值,现在换
  61322. for (var i in e) {
  61323. e[i] = Common.replaceAll(e[i], '{Potree.resourcePath}', Potree.resourcePath);
  61324. }
  61325. });
  61326. this.domElements = viewers.map(e => e.renderArea);
  61327. viewer.addEventListener("CursorChange", e => {
  61328. if (e.action == 'add') {
  61329. this.add(e.name);
  61330. } else {
  61331. this.remove(e.name);
  61332. }
  61333. });
  61334. },
  61335. add: function add(name) {
  61336. var priorityItem = this.priorityEvent.find(e => e[name]);
  61337. if (!priorityItem) {
  61338. console.error('CursorDeal 未定义优先级 name:' + name);
  61339. return;
  61340. }
  61341. if (!this.list.includes(name)) {
  61342. this.judge({
  61343. addItem: priorityItem,
  61344. name
  61345. });
  61346. this.list.push(name);
  61347. }
  61348. },
  61349. remove: function remove(name) {
  61350. var index = this.list.indexOf(name);
  61351. if (index > -1) {
  61352. this.list.splice(index, 1);
  61353. this.judge();
  61354. }
  61355. },
  61356. judge: function judge() {
  61357. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  61358. //console.log(o,this.list)
  61359. if (o.addItem) {
  61360. var addIndex = this.priorityEvent.indexOf(o.addItem);
  61361. if (addIndex < this.currentCursorIndex || this.currentCursorIndex == void 0) {
  61362. this.domElements.forEach(e => e.style.cursor = o.addItem[o.name]);
  61363. this.currentCursorIndex = addIndex;
  61364. }
  61365. } else {
  61366. var levelMax = {
  61367. index: Infinity,
  61368. cursor: null
  61369. };
  61370. this.list.forEach(name => {
  61371. var priorityItem = this.priorityEvent.find(e => e[name]);
  61372. var index = this.priorityEvent.indexOf(priorityItem);
  61373. if (index < levelMax.index) {
  61374. levelMax.index = index;
  61375. levelMax.cursor = priorityItem[name];
  61376. }
  61377. });
  61378. this.currentCursorIndex = levelMax.index;
  61379. this.domElements.forEach(e => e.style.cursor = levelMax.cursor || '');
  61380. }
  61381. }
  61382. };
  61383. class SplitScreen extends EventDispatcher {
  61384. constructor() {
  61385. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  61386. super();
  61387. }
  61388. /*
  61389. viewport.targetPlane // bound中心点处的plane,方向和view一致
  61390. viewport.shiftTarget // camera的位置project在targetPlane上的位置
  61391. 这两个参数的主要目的是为了getPosOutOfModel,以及rotateSideCamera时保持相对位置
  61392. */
  61393. splitStart(cameraProps) {
  61394. var _this = this;
  61395. this.splited = true;
  61396. var viewports = [];
  61397. var subViewports = [viewer.mainViewport];
  61398. if (viewer.mapViewer) {
  61399. subViewports.push(viewer.mapViewer.viewports[0]);
  61400. }
  61401. var length = cameraProps.length;
  61402. var _loop = function _loop() {
  61403. var prop = cameraProps[i];
  61404. var viewport;
  61405. var v = subViewports.find(e => e.name == (prop.name2 || prop.name));
  61406. if (v) {
  61407. viewport = v;
  61408. viewport.left = prop.left;
  61409. viewport.bottom = prop.bottom;
  61410. viewport.width = prop.width;
  61411. viewport.height = prop.height;
  61412. }
  61413. if (!viewport) {
  61414. var view = new ExtendView();
  61415. if (prop.limitBound) view.limitBound = prop.limitBound;
  61416. prop.direction && (view.direction = prop.direction);
  61417. viewport = new Viewport(view, _this.getOrthoCamera(), prop);
  61418. if (prop.viewContainsPoints) viewport.viewContainsPoints = prop.viewContainsPoints;
  61419. //viewport.unableDepth = true //depthBasicMaterial等在此viewport中不开启depth
  61420. }
  61421. if (viewport.camera.type == 'OrthographicCamera') {
  61422. viewport.targetPlane = new Plane();
  61423. viewport.shiftTarget = new Vector3(); //project在targetPlane上的位置
  61424. }
  61425. viewport.fitMargin = prop.margin;
  61426. viewports.push(viewport);
  61427. };
  61428. for (var i = 0; i < length; i++) {
  61429. _loop();
  61430. }
  61431. viewer.viewports = viewports;
  61432. viewer.updateScreenSize({
  61433. forceUpdateSize: true
  61434. });
  61435. viewports.forEach(viewport => {
  61436. if (viewport.name == 'MainView') return;
  61437. this.viewportFitBound(viewport, viewer.bound.boundingBox, viewer.bound.center, 0, viewport.fitMargin);
  61438. });
  61439. return viewports;
  61440. }
  61441. unSplit() {
  61442. this.splited = false;
  61443. this.unfocusViewport();
  61444. viewer.inputHandler.hoverViewport = null; //清空
  61445. viewer.viewports = [viewer.mainViewport];
  61446. viewer.mainViewport.width = 1;
  61447. viewer.mainViewport.height = 1;
  61448. viewer.mainViewport.left = 0;
  61449. viewer.mainViewport.bottom = 0;
  61450. viewer.updateScreenSize({
  61451. forceUpdateSize: true
  61452. });
  61453. }
  61454. viewportFitBound(viewport, bound, center) {
  61455. var duration = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  61456. var margin = arguments.length > 4 ? arguments[4] : undefined;
  61457. var view = viewport.view;
  61458. var info = {
  61459. bound
  61460. };
  61461. var {
  61462. boundSize,
  61463. boundCenter
  61464. } = this.getViewBound(viewport, bound);
  61465. //this.setShiftTarget(viewport, boundCenter)
  61466. viewport.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), boundCenter);
  61467. viewport.targetPlane.projectPoint(center, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  61468. info.endPosition = this.getPosOutOfModel(viewport, boundSize);
  61469. //if(viewport.name == 'mapViewport')info.endPosition.z = Math.max(Potree.config.map.cameraHeight, info.endPosition.z)
  61470. info.margin = margin || {
  61471. x: 30,
  61472. y: 30
  61473. };
  61474. view.moveOrthoCamera(viewport, info, duration);
  61475. }
  61476. getViewBound(viewport, boundingBox) {
  61477. if (boundingBox) {
  61478. boundSize = boundingBox.getSize(new Vector3());
  61479. center = boundingBox.getCenter(new Vector3());
  61480. } else {
  61481. var {
  61482. boundSize,
  61483. center,
  61484. boundingBox
  61485. } = viewer.bound;
  61486. }
  61487. var containsPoints = [];
  61488. this.focusCenter && containsPoints.push(this.focusCenter);
  61489. viewport.viewContainsPoints && containsPoints.push(...viewport.viewContainsPoints);
  61490. if (containsPoints.length) {
  61491. //视野范围内必须要包含的点,直接算入模型区域。这时候得到的boundCenter和模型中心不重合
  61492. boundingBox = boundingBox.clone();
  61493. containsPoints.forEach(point => {
  61494. boundingBox.expandByPoint(point);
  61495. });
  61496. boundSize = boundingBox.getSize(new Vector3());
  61497. center = boundingBox.getCenter(new Vector3());
  61498. }
  61499. return {
  61500. boundSize,
  61501. boundCenter: center
  61502. };
  61503. }
  61504. getPosOutOfModel(viewport, boundSize) {
  61505. //let {boundSize, center} = viewer.bound
  61506. boundSize = boundSize || this.getViewBound(viewport).boundSize;
  61507. var expand = 10;
  61508. var radius = boundSize.length() * 2;
  61509. var position = viewport.shiftTarget.clone().sub(viewport.view.direction.clone().multiplyScalar(radius + expand));
  61510. return position;
  61511. }
  61512. updateCameraOutOfModel() {
  61513. //因为移动模型导致模型超出相机外,所以更新位置
  61514. viewer.viewports.forEach((viewport, i) => {
  61515. if (viewport.camera.isOrthographicCamera) {
  61516. //or if(viewport.targetPlane)
  61517. var {
  61518. boundSize,
  61519. boundCenter
  61520. } = this.getViewBound(viewport);
  61521. /* viewport.targetPlane.setFromNormalAndCoplanarPoint( viewport.view.direction.clone(), boundCenter)
  61522. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget) //target转换到过模型中心的平面,以保证镜头一定在模型外 this.shiftTarget是得到的
  61523. */
  61524. this.setShiftTarget(viewport, boundCenter);
  61525. var endPosition = this.getPosOutOfModel(viewport, boundSize);
  61526. //if(viewport.name == 'mapViewport')endPosition.z = Math.max(Potree.config.map.cameraHeight, endPosition.z)
  61527. viewport.view.position.copy(endPosition);
  61528. }
  61529. });
  61530. }
  61531. setShiftTarget(viewport, center) {
  61532. if (!viewport.targetPlane) {
  61533. viewport.targetPlane = new Plane();
  61534. viewport.shiftTarget = new Vector3(); //project在targetPlane上的位置
  61535. }
  61536. viewport.targetPlane.setFromNormalAndCoplanarPoint(viewport.view.direction, center);
  61537. viewport.targetPlane.projectPoint(viewport.view.position, viewport.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外
  61538. }
  61539. rotateSideCamera(viewport, angle) {
  61540. //侧视图或俯视图绕模型中心水平旋转
  61541. //let {boundSize, center} = viewer.bound
  61542. var {
  61543. boundSize,
  61544. boundCenter
  61545. } = this.getViewBound(viewport);
  61546. var center = this.focusCenter || boundCenter; //旋转中心,一般是所有模型的中心,除非想指定中心点
  61547. this.setShiftTarget(viewport, center);
  61548. //找到平移向量
  61549. var vec = new Vector3().subVectors(center, viewport.shiftTarget); //相对于中心的偏移值,旋转后偏移值也旋转
  61550. //旋转
  61551. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle);
  61552. viewport.view.direction = viewport.view.direction.applyMatrix4(rotMatrix);
  61553. vec.applyMatrix4(rotMatrix);
  61554. viewport.shiftTarget.subVectors(center, vec); //新的
  61555. viewport.view.position = this.getPosOutOfModel(viewport, boundSize);
  61556. }
  61557. getOrthoCamera() {
  61558. var camera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  61559. camera.up.set(0, 0, 1);
  61560. return camera;
  61561. }
  61562. focusOnViewport(name) {
  61563. //全屏
  61564. viewer.viewports.forEach((viewport, i) => {
  61565. if (viewport.name == name) {
  61566. this.focusInfo = {
  61567. name,
  61568. left: viewport.left,
  61569. bottom: viewport.bottom,
  61570. height: viewport.height,
  61571. width: viewport.width
  61572. };
  61573. viewport.left = 0;
  61574. viewport.bottom = 0;
  61575. viewport.height = 1;
  61576. viewport.width = 1;
  61577. } else {
  61578. viewport.active = false;
  61579. }
  61580. });
  61581. viewer.updateScreenSize({
  61582. forceUpdateSize: true
  61583. });
  61584. }
  61585. unfocusViewport() {
  61586. if (!this.focusInfo) return;
  61587. viewer.viewports.forEach((viewport, i) => {
  61588. if (this.focusInfo.name == viewport.name) {
  61589. //全屏的恢复
  61590. viewport.left = this.focusInfo.left;
  61591. viewport.bottom = this.focusInfo.bottom;
  61592. viewport.height = this.focusInfo.height;
  61593. viewport.width = this.focusInfo.width;
  61594. }
  61595. viewport.active = true;
  61596. });
  61597. viewer.updateScreenSize({
  61598. forceUpdateSize: true
  61599. });
  61600. this.focusInfo = null;
  61601. }
  61602. }
  61603. var FEET_TO_INCHES_FACTOR = 12;
  61604. var EIGHTHS_SYMBOLS = ["", "⅛", "¼", "⅜", "½", "⅝", "¾", "⅞"]; //eighths 八分之……
  61605. class UnitOfMeasurement {
  61606. //转化单位工具
  61607. constructor(t, e, n, i) {
  61608. this.name = t, this.symbol = e, this.base = n, this.factor = i;
  61609. }
  61610. toBase(t) {
  61611. //换算到base
  61612. return t * this.factor;
  61613. }
  61614. fromBase(t) {
  61615. //换算到当前
  61616. return t / this.factor;
  61617. }
  61618. }
  61619. /* var o = function t(e) {
  61620. this.gettext = e,
  61621. t.METRIC = this.gettext("metric", void 0, "measurement system"),
  61622. t.IMPERIAL = this.gettext("imperial", void 0, "measurement system")
  61623. };
  61624. e.UoMSystem = o;
  61625. let UoMSystem = {
  61626. } */
  61627. /* var MeasurementDomain = {
  61628. DISTANCE : "DISTANCE",
  61629. t.AREA = "AREA",
  61630. t.VOLUME = "VOLUME",
  61631. t.DATA = "DATA",
  61632. t
  61633. }
  61634. */
  61635. var UnitsOfMeasurement = {
  61636. MILLIMETER: ["Millimeter", "mm"],
  61637. CENTIMETER: ["Centimeter", "cm"],
  61638. METER: ["Meter", "m"],
  61639. KILOMETER: ["Kilometer", "km"],
  61640. INCH: ["Inch", "in"],
  61641. FOOT: ["Foot", "ft"],
  61642. MILE: ["Mile", "mi"],
  61643. SQUAREMETER: ["SquareMeter", "m²"],
  61644. SQUAREFOOT: ["SquareFoot", "ft²"],
  61645. CUBICMETER: ["CubicMeter", "m³"],
  61646. CUBICFOOT: ["CubicFoot", "ft³"],
  61647. BYTE: ["Byte", "B"],
  61648. KILOBYTE: ["Kilobyte", "kB"],
  61649. MEGABYTE: ["Megabyte", "MB"],
  61650. GIGABYTE: ["Gigabyte", "GB"],
  61651. TERABYTE: ["Terabyte", "TB"],
  61652. PETABYTE: ["Petabyte", "PB"],
  61653. init: function init() {
  61654. var e,
  61655. n,
  61656. i,
  61657. a,
  61658. s,
  61659. c,
  61660. l,
  61661. u,
  61662. d,
  61663. p,
  61664. h,
  61665. f = new UnitOfMeasurement(UnitsOfMeasurement.METER[0], UnitsOfMeasurement.METER[1], void 0, 1),
  61666. g = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREMETER[0], UnitsOfMeasurement.SQUAREMETER[1], void 0, 1),
  61667. m = new UnitOfMeasurement(UnitsOfMeasurement.CUBICMETER[0], UnitsOfMeasurement.CUBICMETER[1], void 0, 1),
  61668. v = new UnitOfMeasurement(UnitsOfMeasurement.BYTE[0], UnitsOfMeasurement.BYTE[1], void 0, 1);
  61669. UnitsOfMeasurement.DISTANCE = ((e = {})['metric'] = ((n = {})[UnitsOfMeasurement.MILLIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILLIMETER[0], UnitsOfMeasurement.MILLIMETER[1], f, .001), n[UnitsOfMeasurement.CENTIMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CENTIMETER[0], UnitsOfMeasurement.CENTIMETER[1], f, .01), n[UnitsOfMeasurement.METER[0]] = f, n[UnitsOfMeasurement.KILOMETER[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOMETER[0], UnitsOfMeasurement.KILOMETER[1], f, 1e3), n), e['imperial'] = ((i = {})[UnitsOfMeasurement.INCH[0]] = new UnitOfMeasurement(UnitsOfMeasurement.INCH[0], UnitsOfMeasurement.INCH[1], f, .0254), i[UnitsOfMeasurement.FOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.FOOT[0], UnitsOfMeasurement.FOOT[1], f, .3048), i[UnitsOfMeasurement.MILE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MILE[0], UnitsOfMeasurement.MILE[1], f, 1609.344), i), e);
  61670. UnitsOfMeasurement.AREA = ((a = {})['metric'] = ((s = {})[UnitsOfMeasurement.SQUAREMETER[0]] = g, s), a['imperial'] = ((c = {})[UnitsOfMeasurement.SQUAREFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.SQUAREFOOT[0], UnitsOfMeasurement.SQUAREFOOT[1], g, .092903), c), a);
  61671. UnitsOfMeasurement.VOLUME = ((l = {})['metric'] = ((u = {})[UnitsOfMeasurement.CUBICMETER[0]] = m, u), l['imperial'] = ((d = {})[UnitsOfMeasurement.CUBICFOOT[0]] = new UnitOfMeasurement(UnitsOfMeasurement.CUBICFOOT[0], UnitsOfMeasurement.CUBICFOOT[1], m, .0283168), d), l);
  61672. //数据大小
  61673. var y = ((p = {})[UnitsOfMeasurement.BYTE[0]] = v, p[UnitsOfMeasurement.KILOBYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.KILOBYTE[0], UnitsOfMeasurement.KILOBYTE[1], v, 1e3), p[UnitsOfMeasurement.MEGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.MEGABYTE[0], UnitsOfMeasurement.MEGABYTE[1], v, 1e6), p[UnitsOfMeasurement.GIGABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.GIGABYTE[0], UnitsOfMeasurement.GIGABYTE[1], v, 1e9), p[UnitsOfMeasurement.TERABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.TERABYTE[0], UnitsOfMeasurement.TERABYTE[1], v, 1e12), p[UnitsOfMeasurement.PETABYTE[0]] = new UnitOfMeasurement(UnitsOfMeasurement.PETABYTE[0], UnitsOfMeasurement.PETABYTE[1], v, 1e15), p);
  61674. UnitsOfMeasurement.DATA = ((h = {})['metric'] = y, h['imperial'] = y, h);
  61675. },
  61676. getUnitsOfMeasurementByDomain: function getUnitsOfMeasurementByDomain(e) {
  61677. return this[e.toUpperCase()];
  61678. /* switch (e.toUpperCase()) {
  61679. case a.DISTANCE:
  61680. return t.DISTANCE;
  61681. case a.AREA:
  61682. return t.AREA;
  61683. case a.VOLUME:
  61684. return t.VOLUME;
  61685. case a.DATA:
  61686. return t.DATA;
  61687. default:
  61688. console.error(e + " measurement domain is not supported.")
  61689. } */
  61690. },
  61691. getUnitsOfMeasurementByDomainAndSystem: function getUnitsOfMeasurementByDomainAndSystem(domain, system) {
  61692. var r = this.getUnitsOfMeasurementByDomain(domain);
  61693. if (r.hasOwnProperty(system.toLowerCase())) return r[system.toLowerCase()];
  61694. console.error(n + " measurement system is not supported.");
  61695. },
  61696. getDefaultUnitByDomainAndSystem: function getDefaultUnitByDomainAndSystem(e, n) {
  61697. switch (e.toUpperCase()) {
  61698. case 'DISTANCE':
  61699. switch (n.toLowerCase()) {
  61700. case 'metric':
  61701. return this.DISTANCE['metric'][this.METER[0]];
  61702. case 'imperial':
  61703. return this.DISTANCE['imperial'][this.FOOT[0]];
  61704. default:
  61705. console.error(n + " measurement system is not supported.");
  61706. }
  61707. case 'AREA':
  61708. switch (n.toLowerCase()) {
  61709. case 'metric':
  61710. return this.AREA['metric'][this.SQUAREMETER[0]];
  61711. case 'imperial':
  61712. return this.AREA['imperial'][this.SQUAREFOOT[0]];
  61713. default:
  61714. console.error(n + " measurement system is not supported.");
  61715. }
  61716. case 'VOLUME':
  61717. switch (n.toLowerCase()) {
  61718. case 'metric':
  61719. return this.VOLUME['metric'][this.CUBICMETER[0]];
  61720. case 'imperial':
  61721. return this.VOLUME['imperial'][this.CUBICFOOT[0]];
  61722. default:
  61723. console.error(n + " measurement system is not supported.");
  61724. }
  61725. case 'DATA':
  61726. switch (n.toLowerCase()) {
  61727. case 'metric':
  61728. return this.DATA['metric'][this.BYTE[0]];
  61729. case 'imperial':
  61730. return this.DATA['imperial'][this.BYTE[0]];
  61731. default:
  61732. console.error(n + " measurement system is not supported.");
  61733. }
  61734. default:
  61735. console.error(e + " measurement domain is not supported.");
  61736. }
  61737. }
  61738. };
  61739. class UnitService {
  61740. constructor( /* e, n, i */
  61741. ) {
  61742. //this.LanguageService = e,
  61743. //this.localStorageService = n,
  61744. //this.gettext = i,
  61745. //this.unitChanged = new r.Signal,
  61746. this.LOCAL_STORAGE_KEY = "iv_unit_key"; //?
  61747. UnitsOfMeasurement.init();
  61748. this.unitSystems = ['metric', 'imperial']; //[o.UoMSystem.METRIC, o.UoMSystem.IMPERIAL],
  61749. this.defaultSystem = 'metric'; //'imperial'
  61750. //var a = this.LanguageService.getBrowserLocaleString().toLowerCase();
  61751. //this.defaultSystem = t.isLocaleImperial(a) ? o.UoMSystem.IMPERIAL : o.UoMSystem.METRIC,
  61752. //this.initUnit()
  61753. }
  61754. /* initUnit() {
  61755. var t = this.localStorageService.get(this.LOCAL_STORAGE_KEY);
  61756. if (t)
  61757. for (var e = 0, n = this.unitSystems; e < n.length; e++) {
  61758. var i = n[e];
  61759. if (i === t)
  61760. return void this.setUnit(i, !0)
  61761. }
  61762. this.setUnit(this.defaultSystem, !1)
  61763. }
  61764. setUnit(t, e) {
  61765. this.currentSystem !== t && (this.currentSystem = t,
  61766. this.unitChanged.emit()),
  61767. e && this.localStorageService.set(this.LOCAL_STORAGE_KEY, t)
  61768. } */
  61769. /*isLocaleImperial(e) {
  61770. return t.IMPERIAL_LOCALES.indexOf(e.toLowerCase()) >= 0
  61771. }
  61772. ,
  61773. t.IMPERIAL_LOCALES = ["en_us"],
  61774. t.ɵfac(e) {
  61775. return new (e || t)(c.ɵɵinject(l.LanguageService),
  61776. c.ɵɵinject("localStorageService"),c.ɵɵinject("gettext"))
  61777. }
  61778. ,
  61779. t.ɵprov = c.ɵɵdefineInjectable({
  61780. token: t,
  61781. factory: t.ɵfac,
  61782. providedIn: "root"
  61783. }), */
  61784. }
  61785. class UoMService {
  61786. constructor( /* UnitService */
  61787. ) {
  61788. this.UnitService = new UnitService(); /* UnitService */
  61789. }
  61790. scopedConvert(t, n) {
  61791. var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
  61792. var r = arguments.length > 3 ? arguments[3] : undefined;
  61793. var minFactor = arguments.length > 4 ? arguments[4] : undefined;
  61794. return this.convert(t, n, precision, r, minFactor);
  61795. }
  61796. convert(number, domain) {
  61797. var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
  61798. var system = arguments.length > 3 ? arguments[3] : undefined;
  61799. var ifEighths = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : !1;
  61800. var o /* minFactor, ifRestrict */ = arguments.length > 5 ? arguments[5] : undefined;
  61801. var {
  61802. minFactor,
  61803. restrictUnit
  61804. } = o[system];
  61805. //if (!number) return "";
  61806. var s = this.getMostRelevantMeasurement(domain, system || this.UnitService.currentSystem, number, minFactor, restrictUnit);
  61807. return this.getFormattedMeasurementString(s[0], s[1], precision, ifEighths);
  61808. }
  61809. convertBack(number, domain) {
  61810. var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
  61811. var fromSystem = arguments.length > 3 ? arguments[3] : undefined;
  61812. var minFactor = arguments.length > 4 ? arguments[4] : undefined;
  61813. //从英制转到'metric'
  61814. if (!number) return "";
  61815. var d = UnitsOfMeasurement.getDefaultUnitByDomainAndSystem(domain, 'metric');
  61816. var s = this.getMostRelevantMeasurement2(domain, fromSystem, number, minFactor);
  61817. return this.getFormattedMeasurementString(s[0], d, precision);
  61818. /* 栗子:
  61819. viewer.unitConvert.convertBack(1, 'area', 5, 'imperial')
  61820. '0.09290 m²'
  61821. viewer.unitConvert.convertBack(1, 'Distance', 2, 'imperial')
  61822. '0.03 m'
  61823. */
  61824. }
  61825. getFormattedMeasurementString(number, unit, precision, ifEighths) {
  61826. var result;
  61827. if (ifEighths && unit.name === UnitsOfMeasurement.FOOT[0]) {
  61828. result = this.formatImperialDistance(number * FEET_TO_INCHES_FACTOR);
  61829. } else if (ifEighths && unit.name === UnitsOfMeasurement.INCH[0]) {
  61830. result = this.formatImperialDistance(number);
  61831. } else {
  61832. result = number.toLocaleString(void 0, {
  61833. minimumFractionDigits: precision,
  61834. maximumFractionDigits: precision
  61835. }) + " " + unit.symbol;
  61836. }
  61837. return result;
  61838. }
  61839. formatImperialDistance(e) {
  61840. var n = Math.round(8 * e),
  61841. i = Math.floor(n / 8),
  61842. r = Math.floor(i / FEET_TO_INCHES_FACTOR),
  61843. o = i - r * FEET_TO_INCHES_FACTOR,
  61844. a = EIGHTHS_SYMBOLS[Math.abs(n % 8)],
  61845. s = 0 === o && "" !== a ? "" : o;
  61846. "" !== s && "" !== a && (a = " " + a);
  61847. return 0 !== r ? r + "' " + s + a + '"' : "" + s + a + '"';
  61848. }
  61849. getMostRelevantMeasurement(domain, system, number) {
  61850. var minFactor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  61851. var restrictUnit = arguments.length > 4 ? arguments[4] : undefined;
  61852. /* var a = r.values(UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system))
  61853. , s = r.filter(a, function(t) {
  61854. return t.factor >= i
  61855. })
  61856. , c = r.reduce(s, function(t, e) {
  61857. return e.fromBase(number) < t.fromBase(number) && e.fromBase(number) >= 1 ? e : t
  61858. }); */
  61859. var a = [];
  61860. var u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  61861. for (var i in u) {
  61862. a.push(u[i]);
  61863. }
  61864. var s = a;
  61865. if (s.length > 1) {
  61866. if (restrictUnit) {
  61867. //是否只用这一单位,如只用mm。如果不是,就会寻找最大的接近的单位,如设置最小为mmminFactor=0.001),则1.2米时是'1.2m'、0.2米时是'20cm'、0.002米时是'2mm'
  61868. s = a.filter(m => m.name == restrictUnit);
  61869. } else {
  61870. s = a.filter(m => m.factor >= minFactor);
  61871. }
  61872. }
  61873. var c = s.reduce(function (prev, currentValue) {
  61874. //reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  61875. return currentValue.fromBase(number) < prev.fromBase(number) && currentValue.fromBase(number) >= 1 ? currentValue : prev;
  61876. });
  61877. return c ? [c.fromBase(number), c] : void 0;
  61878. }
  61879. getMostRelevantMeasurement2(domain, system, number) {
  61880. var minFactor = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  61881. //add
  61882. var a = [];
  61883. var u = UnitsOfMeasurement.getUnitsOfMeasurementByDomainAndSystem(domain, system);
  61884. for (var i in u) {
  61885. a.push(u[i]);
  61886. }
  61887. var s = a.filter(m => m.factor >= minFactor);
  61888. var c = s.reduce(function (prev, currentValue) {
  61889. //reduce最终值是最后一次return的值 ( 没看懂这句话作用)
  61890. return currentValue.toBase(number) < prev.toBase(number) && currentValue.toBase(number) >= 1 ? currentValue : prev;
  61891. });
  61892. return c ? [c.toBase(number), c] : void 0;
  61893. }
  61894. /* ɵfac(e){
  61895. return new (e || t)(c.ɵɵinject(l.UnitService))
  61896. }
  61897. ɵprov = c.ɵɵdefineInjectable({
  61898. token: t,
  61899. factory: t.ɵfac,
  61900. providedIn: "root"
  61901. }) */
  61902. }
  61903. var texLoader$8 = new TextureLoader();
  61904. var color$1 = new Color(config$1.clip.color);
  61905. var markerMats$1;
  61906. var markerSizeInfo$1 = {
  61907. width2d: 40
  61908. };
  61909. var pickOrders = {
  61910. marker: 1,
  61911. area: 0
  61912. };
  61913. class mapClipBox extends ctrlPolygon {
  61914. constructor(center, scale) {
  61915. center = center.clone().setZ(0); //所有Z都为0
  61916. var prop = {
  61917. points: getPoints(center, scale, 0),
  61918. closed: true,
  61919. atPlane: true,
  61920. isRect: true,
  61921. dimension: '2d'
  61922. };
  61923. super('mapClipBox', prop);
  61924. this.angle = 0;
  61925. this.createRotateBar();
  61926. this.edgeMarkers = [];
  61927. //addMarkers:
  61928. this.initData(prop);
  61929. {
  61930. //areaPlane event 能拖动
  61931. this.areaPlane.addEventListener('mouseover', () => {
  61932. viewer.dispatchEvent({
  61933. type: "CursorChange",
  61934. action: "add",
  61935. name: "mapClipMove"
  61936. });
  61937. });
  61938. this.areaPlane.addEventListener('mouseleave', () => {
  61939. viewer.dispatchEvent({
  61940. type: "CursorChange",
  61941. action: "remove",
  61942. name: "mapClipMove"
  61943. });
  61944. });
  61945. var lastPos;
  61946. var drag = e => {
  61947. var intersect = e.intersect.orthoIntersect;
  61948. if (lastPos) {
  61949. var moveVec = new Vector3().subVectors(intersect, lastPos).setZ(0);
  61950. this.center.add(moveVec);
  61951. this.updatePoints();
  61952. this.dispatchEvent({
  61953. type: 'repos'
  61954. });
  61955. }
  61956. lastPos = intersect.clone();
  61957. };
  61958. var drop = e => {
  61959. lastPos = null;
  61960. };
  61961. this.areaPlane.addEventListener('drag', drag);
  61962. this.areaPlane.addEventListener('drop', drop);
  61963. }
  61964. /* this.addEventListener('dragChange',()=>{
  61965. this.updateTwoMidMarker(index+1)
  61966. }) */
  61967. Potree.Utils.setObjectLayers(this, 'mapObjects');
  61968. }
  61969. getScale() {
  61970. return new Vector3(this.points[0].distanceTo(this.points[1]), this.points[1].distanceTo(this.points[2]), 1);
  61971. }
  61972. addMarker() {
  61973. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  61974. var marker = new Sprite$2({
  61975. mat: this.getMarkerMaterial('default'),
  61976. pickOrder: pickOrders.marker,
  61977. sizeInfo: markerSizeInfo$1,
  61978. dontFixOrient: true,
  61979. viewports: viewer.mapViewer.viewports,
  61980. name: "mapClipBox_marker"
  61981. });
  61982. marker.renderOrder = 3;
  61983. //marker.markerSelectStates = {}
  61984. var edge = LineDraw.createLine([new Vector3(), new Vector3()], {
  61985. color: color$1
  61986. });
  61987. var edgeMarker = new Sprite$2({
  61988. mat: this.getMarkerMaterial('default'),
  61989. pickOrder: pickOrders.marker,
  61990. sizeInfo: markerSizeInfo$1,
  61991. dontFixOrient: true,
  61992. viewports: viewer.mapViewer.viewports,
  61993. name: "mapClipBox_edgePoint"
  61994. });
  61995. var mouseover = e => {
  61996. this.setMarkerSelected(e.object, true, 'single');
  61997. viewer.dispatchEvent({
  61998. type: "CursorChange",
  61999. action: "add",
  62000. name: "markerMove"
  62001. });
  62002. };
  62003. var mouseleave = e => {
  62004. this.setMarkerSelected(e.object, false, 'single');
  62005. viewer.dispatchEvent({
  62006. type: "CursorChange",
  62007. action: "remove",
  62008. name: "markerMove"
  62009. });
  62010. };
  62011. edgeMarker.addEventListener('mouseover', mouseover);
  62012. edgeMarker.addEventListener('mouseleave', mouseleave);
  62013. var dragInfo = {
  62014. lastPos: null
  62015. };
  62016. edgeMarker.addEventListener('drag', this.dragEdge.bind(this, dragInfo));
  62017. edgeMarker.addEventListener('drop', this.dropEdge.bind(this, dragInfo));
  62018. this.edgeMarkers.push(edgeMarker);
  62019. this.add(edgeMarker);
  62020. marker.dispatchEvent('addHoverEvent');
  62021. super.addMarker({
  62022. point: o.point,
  62023. marker: marker,
  62024. edge
  62025. });
  62026. }
  62027. dragEdge(dragInfo, e) {
  62028. //拖拽一个边(或一个边类型的marker),带动它的两个端点。 可以转化为拖拽marker往法线方向
  62029. var I, atMap;
  62030. atMap = e.dragViewport.name == 'mapViewport';
  62031. I = e.intersect.orthoIntersect;
  62032. if (I && dragInfo.lastPos) {
  62033. var i = this.edgeMarkers.indexOf(e.drag.object);
  62034. if (i !== -1) {
  62035. var lineNormal = math.getNormal2d({
  62036. p1: this.points[i],
  62037. p2: this.points[(i + 1) % 4]
  62038. });
  62039. var moveVec = new Vector3().subVectors(I, dragInfo.lastPos).setZ(0); //移动的向量
  62040. var dragVec = moveVec.projectOnVector(lineNormal).setZ(0); //在法线上移动的向量
  62041. var newPos = new Vector3().addVectors(this.points[i], dragVec); //marker应到的位置
  62042. this.dragChange(newPos, i, atMap); //转化为这个marker的拖拽
  62043. }
  62044. }
  62045. dragInfo.lastPos = I.clone();
  62046. }
  62047. dropEdge(dragInfo, e) {
  62048. dragInfo.lastPos = null;
  62049. this.setMarkerSelected(e.drag.object, false, 'single'); //拖拽时似乎没有触发mouseout
  62050. }
  62051. createAreaPlane() {
  62052. var planeMat = new MeshBasicMaterial({
  62053. color: color$1,
  62054. //"#00eeff",
  62055. side: DoubleSide,
  62056. opacity: 0.3,
  62057. transparent: true,
  62058. depthTest: false
  62059. });
  62060. return super.createAreaPlane(planeMat);
  62061. }
  62062. getMarkerMaterial(type) {
  62063. if (!markerMats$1) {
  62064. markerMats$1 = {
  62065. default: new MeshBasicMaterial({
  62066. transparent: !0,
  62067. color: color$1,
  62068. opacity: 0.8,
  62069. map: texLoader$8.load(Potree.resourcePath + '/textures/whiteCircle.png')
  62070. }),
  62071. select: new MeshBasicMaterial({
  62072. transparent: !0,
  62073. color: color$1,
  62074. opacity: 1,
  62075. map: texLoader$8.load(Potree.resourcePath + '/textures/whiteCircle.png')
  62076. })
  62077. };
  62078. mapClipBox.markerMats = markerMats$1;
  62079. }
  62080. return markerMats$1[type];
  62081. }
  62082. setMarkerSelected(marker, state, hoverObject) {
  62083. //console.warn(marker.id , state, hoverObject)
  62084. if (state == 'hover') {
  62085. marker.material = this.getMarkerMaterial('select');
  62086. } else {
  62087. marker.material = this.getMarkerMaterial('default');
  62088. }
  62089. /* marker.markerSelectStates[hoverObject] = state
  62090. let absoluteState = false
  62091. for(var i in marker.markerSelectStates){
  62092. if(marker.markerSelectStates[i]){
  62093. absoluteState = true; break;
  62094. }
  62095. }
  62096. if(absoluteState){
  62097. marker.material = this.getMarkerMaterial('select')
  62098. }else{
  62099. marker.material = this.getMarkerMaterial('default')
  62100. }
  62101. marker.selected = absoluteState */
  62102. viewer.mapViewer.dispatchEvent('content_changed');
  62103. }
  62104. createRotateBar() {
  62105. //中心点在线的一端,整体初始在box上方
  62106. var lineLen = 1.5,
  62107. circleWidth = 2,
  62108. barOpacity = 0.7;
  62109. var object = new Object3D();
  62110. var bar = new Sprite$2({
  62111. mat: new MeshBasicMaterial({
  62112. side: DoubleSide,
  62113. opacity: barOpacity,
  62114. transparent: true,
  62115. depthTest: false,
  62116. map: texLoader$8.load(Potree.resourcePath + '/textures/rotation_circle.png')
  62117. }),
  62118. root: object,
  62119. sizeInfo: markerSizeInfo$1,
  62120. dontFixOrient: true,
  62121. viewports: viewer.mapViewer.viewports,
  62122. name: "mapClipRotateBar"
  62123. });
  62124. bar.position.set(0, lineLen + circleWidth / 2, 0);
  62125. bar.scale.set(circleWidth, circleWidth, circleWidth);
  62126. bar.addEventListener('mouseover', () => {
  62127. bar.material.opacity = 1;
  62128. viewer.dispatchEvent({
  62129. type: "CursorChange",
  62130. action: "add",
  62131. name: "mapClipRotate"
  62132. });
  62133. viewer.mapViewer.dispatchEvent('content_changed');
  62134. });
  62135. var leave = () => {
  62136. bar.material.opacity = barOpacity;
  62137. viewer.dispatchEvent({
  62138. type: "CursorChange",
  62139. action: "remove",
  62140. name: "mapClipRotate"
  62141. });
  62142. viewer.mapViewer.dispatchEvent('content_changed');
  62143. };
  62144. bar.addEventListener('mouseleave', leave);
  62145. this.addEventListener('dispose', leave);
  62146. var lastPos;
  62147. bar.addEventListener('drag', e => {
  62148. var intersect = e.intersect.orthoIntersect;
  62149. if (lastPos) {
  62150. var vec1 = new Vector3().subVectors(lastPos, this.center).setZ(0);
  62151. var vec2 = new Vector3().subVectors(intersect, this.center).setZ(0);
  62152. var angle = math.getAngle(vec1, vec2, 'z');
  62153. this.angle += angle;
  62154. this.rotateBar.rotation.z = this.angle;
  62155. this.updatePoints();
  62156. this.dispatchEvent({
  62157. type: 'rotate',
  62158. angle: this.angle
  62159. });
  62160. }
  62161. lastPos = intersect.clone();
  62162. });
  62163. bar.addEventListener('drop', () => {
  62164. lastPos = null;
  62165. viewer.dispatchEvent({
  62166. type: "CursorChange",
  62167. action: "remove",
  62168. name: "mapClipRotate"
  62169. });
  62170. });
  62171. var line = LineDraw.createLine([new Vector3(), new Vector3(0, lineLen, 0)], {
  62172. color: color$1
  62173. });
  62174. object.add(bar);
  62175. object.add(line);
  62176. this.add(object);
  62177. this.rotateBar = object;
  62178. this.rotateBar.bar = bar;
  62179. }
  62180. updatePoints(scale) {
  62181. this.points = getPoints(this.center, scale || this.getScale(), this.angle);
  62182. this.getPoint2dInfo(this.points);
  62183. this.update({
  62184. ifUpdateMarkers: true
  62185. });
  62186. }
  62187. update() {
  62188. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  62189. super.update(options);
  62190. {
  62191. //update rotateBar
  62192. var center = new Vector3().addVectors(this.points[0], this.points[1]).multiplyScalar(0.5);
  62193. this.rotateBar.position.copy(center);
  62194. this.rotateBar.bar.waitUpdate(); //更新sprite matrix
  62195. }
  62196. {
  62197. for (var i = 0; i < 4; i++) {
  62198. var current = this.points[i];
  62199. var next = this.points[(i + 1) % 4];
  62200. var mid = new Vector3().addVectors(current, next).multiplyScalar(0.5);
  62201. this.updateMarker(this.edgeMarkers[i], mid);
  62202. }
  62203. }
  62204. }
  62205. dispose() {
  62206. super.dispose();
  62207. this.dispatchEvent('dispose');
  62208. this.rotateBar.bar.dispose();
  62209. }
  62210. }
  62211. function getPoints(center, scale) {
  62212. var angle = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  62213. var points = [new Vector3(-scale.x / 2, +scale.y / 2, 0), new Vector3(+scale.x / 2, +scale.y / 2, 0), new Vector3(+scale.x / 2, -scale.y / 2, 0), new Vector3(-scale.x / 2, -scale.y / 2, 0)];
  62214. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); //再旋转
  62215. points.forEach(e => {
  62216. e.applyMatrix4(rotMatrix);
  62217. e.add(center);
  62218. });
  62219. return points;
  62220. }
  62221. var defaultBoxWidth = 16; //navvis: 10
  62222. //navvis position: si {x: 0, y: 0, z: 0}
  62223. var cameraProps = [{
  62224. name: 'top',
  62225. axis: ["x", "y"],
  62226. direction: new Vector3(0, 0, -1),
  62227. //镜头朝向
  62228. openCount: 0
  62229. }, {
  62230. name: 'front',
  62231. axis: ["x", "z"],
  62232. direction: new Vector3(0, 1, 0),
  62233. openCount: 0
  62234. }, {
  62235. name: 'mainView',
  62236. openCount: 0
  62237. }];
  62238. var Clip = {
  62239. bus: new EventDispatcher(),
  62240. selectedDatasets: [],
  62241. changeCallback(force) {
  62242. if (this.activeViewName != 'mainView') {
  62243. this.splitScreenTool.updateCameraOutOfModel(); //更新相机位置
  62244. }
  62245. if (Potree.settings.isOfficial && this.showMap) {
  62246. var fun = () => {
  62247. var pointclouds = this.getIntersectPointcloud();
  62248. if (Common.getDifferenceSet(pointclouds, this.selectedDatasets).length) {
  62249. this.selectedDatasets = pointclouds;
  62250. //console.error('clipSelectedDatasets',selectedDatasets)
  62251. this.bus.dispatchEvent({
  62252. type: 'updateSelectedDatasets',
  62253. selectedDatasets: pointclouds.map(e => e.dataset_id)
  62254. });
  62255. }
  62256. };
  62257. if (force) fun();else Common.intervalTool.isWaiting('clipSelectedDatasets', fun, 300);
  62258. }
  62259. },
  62260. enter: function enter() {
  62261. this.initViews();
  62262. this.previousView = {
  62263. position: viewer.images360.position,
  62264. target: viewer.scene.view.getPivot(),
  62265. displayMode: Potree.settings.displayMode,
  62266. //---
  62267. ifShowMarker: Potree.settings.ifShowMarker
  62268. };
  62269. var pointcloud = this.getPointcloud();
  62270. var bound = pointcloud.bound; //只选取其中一个数据集的bound,而非整体,是因为担心两个数据集中间有空隙,于是刚好落在没有点云的地方。
  62271. var boundSize = bound.getSize(new Vector3());
  62272. var target = this.getTarget(bound.getCenter(new Vector3())); //navvis的位置xy是用相机位置 this.ViewService.mainView.getCamera().position 我觉得也可以用第一个漫游点的,或者最接近bound中心的漫游点
  62273. var scale = new Vector3(defaultBoxWidth, defaultBoxWidth, boundSize.z); //z和navvis一样
  62274. var eyeDir = viewer.scene.view.direction.clone().setZ(0 /* -boundSize.z/3 */).multiplyScalar(-defaultBoxWidth); //为了使所在楼层不变,不修改z
  62275. //let eyeDir = scale.clone().setZ(boundSize.z/3).multiplyScalar(1.3)
  62276. var position = new Vector3().addVectors(target, eyeDir);
  62277. Potree.settings.displayMode = 'showPointCloud';
  62278. viewer.setView({
  62279. position,
  62280. target,
  62281. duration: 300,
  62282. callback: function callback() {}
  62283. });
  62284. //viewer.setControls(viewer.orbitControls);
  62285. viewer.setLimitFar(false);
  62286. //viewer.setClipState(false) //暂时关闭旧的clipping
  62287. /* new AxisViewer(viewer.mainViewport, viewer.renderArea,{domStyle:{
  62288. bottom: '2px',right: '20px', width:'80px',height:'80px'}
  62289. }) */
  62290. {
  62291. this.box = new BoxVolume$1({
  62292. clip: true
  62293. });
  62294. this.box.clipTask = ClipTask['SHOW_INSIDE_Big' /* "SHOW_INSIDE" */];
  62295. this.box.showBox = false;
  62296. this.box.name = "ClipBox";
  62297. this.box.position.copy(target);
  62298. this.box.scale.copy(scale);
  62299. viewer.controls.setTarget(this.box.position); //绕其旋转
  62300. this.splitScreenTool.focusCenter = this.box.position;
  62301. //带动mapBox
  62302. this.box.addEventListener('position_changed', e => {
  62303. if (this.showMap) {
  62304. this.mapBox.center.setX(this.box.position.x);
  62305. this.mapBox.center.setY(this.box.position.y);
  62306. this.mapBox.updatePoints();
  62307. }
  62308. this.changeCallback();
  62309. });
  62310. this.box.addEventListener('scale_changed', e => {
  62311. if (this.showMap) {
  62312. var scale = this.box.scale;
  62313. this.mapBox.updatePoints(scale);
  62314. }
  62315. this.changeCallback();
  62316. });
  62317. this.box.addEventListener('orientation_changed', e => {
  62318. if (this.showMap) {
  62319. this.mapBox.angle = this.box.rotation.z;
  62320. this.mapBox.rotateBar.rotation.z = this.mapBox.angle;
  62321. this.mapBox.updatePoints();
  62322. }
  62323. this.changeCallback();
  62324. });
  62325. viewer.scene.addVolume(this.box);
  62326. }
  62327. if (this.showMap) {
  62328. //map
  62329. var boxRotateBack = () => {
  62330. //不知道是不是这么写。 因为可能z的旋转不一定都在z
  62331. this.box.rotation.x = 0;
  62332. this.box.rotation.y = 0;
  62333. };
  62334. this.mapBox = new mapClipBox(target, scale);
  62335. viewer.mapViewer.scene.add(this.mapBox);
  62336. //带动box
  62337. this.mapBox.addEventListener('repos', e => {
  62338. this.box.position.setX(this.mapBox.center.x);
  62339. this.box.position.setY(this.mapBox.center.y);
  62340. boxRotateBack();
  62341. this.changeCallback();
  62342. });
  62343. this.mapBox.addEventListener('dragChange', e => {
  62344. var scale = this.mapBox.getScale();
  62345. this.box.scale.setX(scale.x);
  62346. this.box.scale.setY(scale.y);
  62347. this.box.position.setX(this.mapBox.center.x);
  62348. this.box.position.setY(this.mapBox.center.y);
  62349. boxRotateBack();
  62350. this.changeCallback();
  62351. });
  62352. this.mapBox.addEventListener('rotate', e => {
  62353. this.box.rotation.z = this.mapBox.angle;
  62354. boxRotateBack();
  62355. this.changeCallback();
  62356. });
  62357. }
  62358. this.switchView('mainView');
  62359. {
  62360. //viewer.setClipTask(ClipTask["SHOW_INSIDE"])
  62361. }
  62362. Potree.settings.unableNavigate = true;
  62363. Potree.settings.ifShowMarker = false;
  62364. Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', false);
  62365. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', false)//隐藏地图游标
  62366. viewer.inputHandler.toggleSelection(this.box);
  62367. viewer.inputHandler.fixSelection = true;
  62368. viewer.transformationTool.setModeEnable(['scale', 'translation', 'rotation']);
  62369. viewer.transformationTool.frame.material.color.set(Potree.config.clip.color); //navvis 15899953
  62370. viewer.setPointStandardMat(true);
  62371. if (this.showMap) {
  62372. var mapVisi = false;
  62373. this.events = {
  62374. flyToPos: e => {
  62375. var dis = 2;
  62376. var target = e.position;
  62377. target = this.box.position;
  62378. position = e.position;
  62379. //为了方便缩放操作,直接使用box中心作为target
  62380. var duration = e.duration == void 0 ? 1000 : e.duration;
  62381. viewer.scene.view.setView({
  62382. position,
  62383. duration,
  62384. target
  62385. });
  62386. },
  62387. mapVisiChange(e) {
  62388. mapVisi = e.visible;
  62389. var delay = 100; //因resize了camera需要时间更新projectionMatrix
  62390. setTimeout(() => {
  62391. var boundingBox = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld);
  62392. if (mapVisi) {
  62393. //切换地图
  62394. if (viewer.fpVisiDatasets.length == 0) {
  62395. //不会显示任何一个floorplan图,就要就近移动到一个可见数据集里
  62396. var clouds = viewer.scene.pointclouds.filter(e => e.visible);
  62397. if (clouds.length == 0) clouds = viewer.scene.pointclouds;
  62398. var scores = clouds.map((e, i) => {
  62399. return [-viewer.scene.view.position.distanceToSquared(e.bound2), i];
  62400. });
  62401. scores = scores.sort((a, b) => a[0] - b[0]);
  62402. var neareast = clouds[scores[0][1]];
  62403. viewer.flyToDataset({
  62404. pointcloud: neareast,
  62405. duration: 0
  62406. });
  62407. }
  62408. if (Clip.switchMapCount == 0 || !Potree.Utils.getPos2d(viewer.scene.view.position, viewer.mapViewer.viewports[0], viewer.mapViewer.renderArea).inSight || !Potree.Utils.isInsideFrustum(boundingBox, viewer.mapViewer.camera)) {
  62409. //要使box框和游标都在屏幕内。因为游标是3d的当前位置,很可能是准备去框住的位置
  62410. var _bound = boundingBox.clone();
  62411. _bound.expandByPoint(viewer.scene.view.position);
  62412. var size = _bound.getSize(new Vector3());
  62413. var center = _bound.getCenter(new Vector3());
  62414. var margin = viewer.mainViewport.resolution.clone().multiplyScalar(0.3);
  62415. viewer.mapViewer.moveTo(center, size, 100, margin);
  62416. }
  62417. Clip.switchMapCount++;
  62418. //关于究竟是focus box还是dataset有点纠结,又或是两个的union。box和数据集可能离得很远,且无法确定当前想选择的数据集,且数据集可能无floorplan, 即使有可能也不展示……
  62419. } else {
  62420. //切换3d
  62421. if (!Potree.Utils.isInsideFrustum(boundingBox, viewer.scene.getActiveCamera())) {
  62422. //屏幕上没有box的话
  62423. viewer.focusOnObject({
  62424. boundingBox
  62425. }, 'boundingBox', 100);
  62426. }
  62427. }
  62428. }, delay);
  62429. }
  62430. };
  62431. this.switchMapCount = 0;
  62432. this.bus.addEventListener('flyToPos', this.events.flyToPos);
  62433. viewer.mapViewer.addEventListener('forceVisible', this.events.mapVisiChange);
  62434. }
  62435. this.editing = true;
  62436. setTimeout(() => {
  62437. this.changeCallback(true);
  62438. }, 1);
  62439. },
  62440. leave: function leave() {
  62441. viewer.inputHandler.fixSelection = false;
  62442. viewer.scene.removeVolume(this.box);
  62443. this.showMap && this.mapBox.dispose();
  62444. //viewer.setControls(viewer.fpControls);
  62445. this.switchView('mainView');
  62446. Potree.settings.unableNavigate = false;
  62447. Potree.settings.ifShowMarker = this.previousView.ifShowMarker;
  62448. Potree.Utils.updateVisible(viewer.measuringTool.scene, 'clipModel', true);
  62449. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'clipModel', true)
  62450. viewer.setView(this.previousView);
  62451. viewer.setLimitFar(true);
  62452. viewer.setPointStandardMat(false);
  62453. //viewer.setClipState(true)
  62454. viewer.controls.setTarget(null);
  62455. this.splitScreenTool.focusCenter = null;
  62456. //viewer.mainViewport.axis.dispose()
  62457. cameraProps.forEach(e => e.openCount = 0);
  62458. if (this.showMap) {
  62459. this.bus.removeEventListener('flyToPos', this.events.flyToPos);
  62460. viewer.mapViewer.removeEventListener('forceVisible', this.events.mapVisiChange);
  62461. this.events = null;
  62462. }
  62463. this.editing = false;
  62464. },
  62465. initViews() {
  62466. if (this.views) {
  62467. this.views.top.pitch = -Math.PI;
  62468. this.views.top.yaw = 0;
  62469. this.views.front.pitch = 0;
  62470. this.views.front.yaw = 0; //--还原for bugID 44757
  62471. return;
  62472. }
  62473. this.views = {};
  62474. this.cameras = {};
  62475. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  62476. this.orthoCamera.up.set(0, 0, 1);
  62477. this.splitScreenTool = new SplitScreen();
  62478. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  62479. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置
  62480. for (var i = 0; i < 2; i++) {
  62481. var prop = cameraProps[i];
  62482. var view = new ExtendView();
  62483. this.views[prop.name] = view;
  62484. this.cameras[prop.name] = this.orthoCamera;
  62485. view.name = prop.name;
  62486. view.direction = prop.direction;
  62487. }
  62488. this.views.mainView = viewer.mainViewport.view;
  62489. this.cameras.mainView = viewer.mainViewport.camera;
  62490. },
  62491. switchView(name) {
  62492. //替换view和camera到mainViewport
  62493. if (this.activeViewName == name) return;
  62494. var view = this.views[name];
  62495. var camera = this.cameras[name];
  62496. var prop = cameraProps.find(e => e.name == name);
  62497. var {
  62498. boundSize,
  62499. center,
  62500. boundingBox
  62501. } = viewer.bound;
  62502. this.lastViewName = this.activeViewName;
  62503. this.activeViewName = name;
  62504. var lastView = this.views[this.lastViewName];
  62505. var lastCamera = this.cameras[this.lastViewName];
  62506. viewer.mainViewport.view = view;
  62507. viewer.mainViewport.camera = camera;
  62508. if (lastCamera) lastView.zoom = lastCamera.zoom;
  62509. view.zoom && (camera.zoom = view.zoom);
  62510. viewer.updateScreenSize({
  62511. forceUpdateSize: true
  62512. }); //更新camera aspect left等
  62513. view.applyToCamera(camera);
  62514. var ifFocus;
  62515. var boxBound = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld);
  62516. if (!Potree.Utils.isInsideFrustum(boxBound, camera)) {
  62517. //屏幕上没有box的话
  62518. ifFocus = true;
  62519. }
  62520. if (name == 'mainView') {
  62521. if (lastView) {//2d->3d
  62522. }
  62523. if (prop.openCount == 0) ifFocus = false;
  62524. //viewer.fpControls.lockKey = false
  62525. } else {
  62526. this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center);
  62527. this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外
  62528. //view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport))
  62529. //if(view.zoom)camera.zoom = view.zoom//恢复上次的zoom
  62530. if (prop.openCount == 0) {
  62531. //至多执行一次
  62532. ifFocus = true;
  62533. }
  62534. if (this.lastViewName == 'mainView') {//3d->2d
  62535. } else {}
  62536. ifFocus || this.splitScreenTool.updateCameraOutOfModel(); //更新相机位置
  62537. //if(name == 'top') viewer.mainViewport.alignment = {rotate:true,translate:true};
  62538. if (name == 'front') {
  62539. //viewer.mainViewport.alignment = {translate:true, rotateSide:true, translateVec:new THREE.Vector3(0,0,1)}; //只能上下移动
  62540. viewer.mainViewport.rotateSide = true;
  62541. } else {
  62542. viewer.mainViewport.rotateSide = false;
  62543. }
  62544. //viewer.fpControls.lockKey = true
  62545. }
  62546. ifFocus && this.focusOnObject(this.box);
  62547. //首次到front最好能自动对准box的长边的角度上
  62548. prop.openCount++;
  62549. },
  62550. focusOnObject(box) {
  62551. var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  62552. if (this.activeViewName == 'mainView') {
  62553. viewer.focusOnObject({
  62554. boundingBox: box.boundingBox.clone().applyMatrix4(box.matrixWorld)
  62555. }, 'boundingBox', duration);
  62556. } else {
  62557. this.orthoMoveFit(box.position, {
  62558. bound: box.boundingBox.clone().applyMatrix4(box.matrixWorld)
  62559. }, duration);
  62560. }
  62561. },
  62562. transform(type, axis, value) {
  62563. //使用按键微调
  62564. this.box[type][axis] += value;
  62565. },
  62566. setModeEnable(type, enable) {
  62567. var modes = [];
  62568. ['scale', 'translation', 'rotation'].forEach(e => {
  62569. if (e == type) {
  62570. enable && modes.push(e);
  62571. } else {
  62572. viewer.transformationTool.modesEnabled[e] && modes.push(e);
  62573. }
  62574. });
  62575. viewer.transformationTool.setModeEnable(modes);
  62576. viewer.dispatchEvent('content_changed');
  62577. },
  62578. rotateSideCamera(angle) {
  62579. //侧视图绕模型中心水平旋转到的角度 angle: -180 ~ 180
  62580. var diff = MathUtils.degToRad(angle) - viewer.mainViewport.view.yaw;
  62581. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, diff);
  62582. },
  62583. orthoMoveFit(pos, info, duration) {
  62584. var margin = {
  62585. x: viewer.mainViewport.resolution.x * 0.4,
  62586. y: viewer.mainViewport.resolution.y * 0.4
  62587. };
  62588. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin);
  62589. },
  62590. getPointcloud: function getPointcloud() {
  62591. //找一个离当前最近的点云,且最好有漫游点
  62592. var pointclouds = viewer.scene.pointclouds.filter(e => e.panos.length > 0);
  62593. if (pointclouds.length == 0) pointclouds = viewer.scene.pointclouds;
  62594. var result = Common.sortByScore(pointclouds, [], [e => {
  62595. var center = e.bound.getCenter(new Vector3());
  62596. var size = e.bound.getSize(new Vector3()).length() / 2;
  62597. var posToCenter = viewer.images360.position.distanceTo(center);
  62598. return size / posToCenter;
  62599. }]);
  62600. return result[0].item;
  62601. },
  62602. getTarget: function getTarget(boundCenter) {
  62603. //box位置。要找一个有点云的地方。方案1相机位置, 方案2接近相机的漫游点, 方案3接近中心的漫游点。选择方案2,因最大概率有点云
  62604. var target = new Vector3();
  62605. var cameraPos = viewer.images360.position;
  62606. var pano = Common.find(viewer.images360.panos, [], [Images360.sortFunctions.floorDisSquaredToPoint(cameraPos)]);
  62607. if (pano) {
  62608. target.copy(pano.position);
  62609. target.setZ(boundCenter.z);
  62610. } else {
  62611. target.copy(boundCenter);
  62612. }
  62613. return target;
  62614. },
  62615. /* switchMap:function(state){
  62616. }, */
  62617. download: function download() {
  62618. if (this.getIntersectPointcloud().length == 0) {
  62619. return null;
  62620. }
  62621. var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  62622. visiPointclouds.sort((a, b) => {
  62623. return a.dataset_id - b.dataset_id;
  62624. }); //缓存需要固定排序好比较
  62625. var data = {
  62626. transformation_matrix: visiPointclouds.map(cloud => {
  62627. var data = {
  62628. id: cloud.dataset_id,
  62629. matrix: this.getTransformationMatrix(cloud).elements,
  62630. //剪裁大框
  62631. visiMatrixes: cloud.material.clipBoxes_in.map(e => this.getTransformationMatrix(cloud, e.inverse).elements),
  62632. //若干个可见型小框(虽然现在用不到了,因为普通界面不展示这些剪裁区域)
  62633. unVisiMatrixes: cloud.material.clipBoxes_out.map(e => this.getTransformationMatrix(cloud, e.inverse).elements),
  62634. //若干个不可见型小框
  62635. modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements
  62636. };
  62637. return data;
  62638. }),
  62639. aabb: "b-0.5 -0.5 -0.5 0.5 0.5 0.5" //剪裁空间( 所有点在乘上这个矩阵后, 还能落在 1 * 1 * 1的box内的点就是所裁剪的
  62640. };
  62641. return data;
  62642. },
  62643. downloadNoCrop() {
  62644. //不剪裁 下载整个点云
  62645. var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  62646. visiPointclouds.sort((a, b) => {
  62647. return a.dataset_id - b.dataset_id;
  62648. }); //缓存需要固定排序好比较
  62649. var data = {
  62650. transformation_matrix: visiPointclouds.map(cloud => {
  62651. var data = {
  62652. id: cloud.dataset_id,
  62653. matrix: new Matrix4().elements,
  62654. //固定值
  62655. modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements
  62656. };
  62657. return data;
  62658. }),
  62659. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //固定剪裁空间
  62660. };
  62661. console.log(data);
  62662. return data;
  62663. },
  62664. getTransformationMatrix: function getTransformationMatrix(pointcloud, invMatrix) {
  62665. //剪裁矩阵
  62666. var invMatrix = invMatrix || this.box.matrixWorld.clone().invert();
  62667. return new Matrix4().multiplyMatrices(invMatrix, pointcloud.transformMatrix).transpose();
  62668. },
  62669. getIntersectPointcloud() {
  62670. var intersect = pointcloud => {
  62671. if (pointcloud.intersectBox(this.box.matrixWorld)) return true;
  62672. };
  62673. return viewer.scene.pointclouds.filter(e => intersect(e));
  62674. },
  62675. getRulerBound() {
  62676. //坐标尺边界
  62677. var camera = viewer.mainViewport.camera;
  62678. if (!camera.isOrthographicCamera) return;
  62679. var w = camera.right / camera.zoom; //half
  62680. var h = camera.top / camera.zoom;
  62681. var points = [];
  62682. var boundAtCamera = new Box3();
  62683. Clip.box.children[0].geometry.vertices.forEach(e => {
  62684. //模仿getPosWithFullBound
  62685. var p = e.clone().applyMatrix4(Clip.box.matrixWorld);
  62686. points.push(p);
  62687. var p1 = p.clone().applyMatrix4(camera.matrixWorldInverse);
  62688. boundAtCamera.expandByPoint(p1);
  62689. });
  62690. //需要找出clipbox的bound的左上角,它在标尺中是原点
  62691. var ClipBoxLeftTop = new Vector2(boundAtCamera.min.x, boundAtCamera.max.y); //相对于相机的位置
  62692. var camPos = new Vector2(-ClipBoxLeftTop.x, ClipBoxLeftTop.y); //由于ClipBoxLeftTop要变换到原点,所以相机位置就成了ClipBoxLeftTop的相反数, 但因是从上到下所以y再乘-1
  62693. var bound_ = {
  62694. left: camPos.x - w,
  62695. right: camPos.x + w,
  62696. bottom: camPos.y + h,
  62697. //注意从上到下增大
  62698. top: camPos.y - h
  62699. };
  62700. //console.log(bound)
  62701. return bound_;
  62702. },
  62703. screenshot: function () {
  62704. var _screenshot = _asyncToGenerator(function* (rulerBound, rulerMargin) {
  62705. var unitText = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '像素 : 米';
  62706. //测绘图下载。顶视图|侧视图
  62707. return new Promise((resolve, reject) => {
  62708. if (Clip.screenshoting) return reject();
  62709. var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  62710. var camera = viewer.mainViewport.camera;
  62711. //if(Clip.activeViewName == 'mainView')return reject()
  62712. var maxWidth = 8192,
  62713. minWidth = Potree.browser.urlHasValue('clipMinWidth', true) || 1024; //图片尺寸最大最小值。
  62714. //Potree.settings.pointDensity = 'ultraHigh'
  62715. viewer.inputHandler.deselectAll();
  62716. Clip.box.visible = false;
  62717. Clip.screenshoting = true;
  62718. var material = new ExtendPointCloudMaterial();
  62719. material.pointSizeType = Potree.PointSizeType.FIXED; //Potree.PointSizeType
  62720. material.size = Potree.browser.urlHasValue('clipPointSize', true) || 1;
  62721. material.uniforms.minSize.value = 0.1;
  62722. material.activeAttributeName = 'rgba';
  62723. //material.classification = pointcloud.material.classification;
  62724. material.clipBoxBig_in = visiPointclouds[0].material.clipBoxBig_in;
  62725. material.shaderNeedsUpdate = true;
  62726. material.bigClipInBox = visiPointclouds[0].material.bigClipInBox;
  62727. var materials = visiPointclouds.map(e => {
  62728. var mat = e.material;
  62729. e.material = material;
  62730. return mat;
  62731. });
  62732. //根据boundingBox尺寸来定图片尺寸
  62733. var boundingBox = Clip.box.boundingBox.clone().applyMatrix4(Clip.box.matrixWorld);
  62734. var points = [];
  62735. var bound = new Box3();
  62736. Clip.box.children[0].geometry.vertices.forEach(e => {
  62737. //模仿getPosWithFullBound
  62738. var p = e.clone().applyMatrix4(Clip.box.matrixWorld);
  62739. points.push(p);
  62740. var p1 = p.clone().applyMatrix4(camera.matrixWorldInverse);
  62741. bound.expandByPoint(p1);
  62742. });
  62743. var boundSize = bound.getSize(new Vector3());
  62744. var minZoom = Potree.browser.urlHasValue('clipZoom', true) || 80; //1px = 1个点 = 1cm , 如果一个点都是1cm的话
  62745. //zoom不宜过大或过小,过小点云重叠、画面模糊;过大点云有间隙,纹理就看不清
  62746. //中间部分75-80为佳,文字100,边缘50. 最好支持调节 . 且当下载尺寸变大往往点云也多,可能冲破pointbudget限制
  62747. //let text = `1 : ${(1 / camera.zoom).toFixed(4)}(像素 : 米)`
  62748. var w = boundSize.x * minZoom;
  62749. var h = boundSize.y * minZoom;
  62750. var max = Math.max(w, h);
  62751. var s = 1;
  62752. if (max > maxWidth) {
  62753. s = maxWidth / max;
  62754. } else if (max < minWidth) {
  62755. s = minWidth / max;
  62756. }
  62757. w *= s, h *= s;
  62758. material.size *= s;
  62759. s != 1 && console.log('宽度缩放倍数', s);
  62760. //虽然size>1就是浪费像素,但是太小了视觉效果有点差……可能因为fov不真实。 点云大就像是老式电视机虽然显示像素量少但感觉不出画面模糊,且边缘锐利。
  62761. w = Math.round(w);
  62762. h = Math.round(h);
  62763. var focusObjectInfo = [{
  62764. boundingBox,
  62765. points
  62766. }, 'boundingBox', 0, {
  62767. dontChangeCamDir: true,
  62768. dontMoveMap: true,
  62769. boundScale: 1
  62770. }];
  62771. //分块渲染截图,最后拼合图片。需要使每一块的点数不超过pointBudget, 且尺寸不超过4096(会崩溃),过小的话一般不会超过pointBudget,除非是深度较大后排点云多。
  62772. var r = MathUtils.clamp(Math.sqrt(3.5e7 / boundSize.z) * s, 1024, 4096); //每多少米分一块。 推理 wc*hc = w / r * h / r = zoom * w * s * zoom * h * s / r^2 = xyz / V(常数,每多少立方米会超出pointBudget,就是括号里的数字,给大概值)
  62773. //let r = THREE.Math.clamp(1024 / boundSize.z, 256, 4096);
  62774. var wc = w / r; //横向块数
  62775. var hc = h / r; //纵向块数
  62776. var splitRenderInfo = (wc > 1 || hc > 1) && {
  62777. wc: Math.ceil(wc),
  62778. hc: Math.ceil(hc)
  62779. }; //因为结果需要化为整数所以可能不太理想, 分割数过多。 另外如果面积小但是因z过长而超出pointBudget没关系,因后排点云无需绘制
  62780. console.log({
  62781. wc,
  62782. hc,
  62783. w,
  62784. h
  62785. });
  62786. var meterPerPixel = boundSize.x / w;
  62787. var text = "1 : ".concat(meterPerPixel.toFixed(4), "\uFF08").concat(unitText, "\uFF09");
  62788. var beforeScreenshot = () => {
  62789. if (rulerBound) {
  62790. var ruler = Clip.getRulerBound();
  62791. Object.assign(rulerBound, ruler);
  62792. }
  62793. };
  62794. var {
  62795. getImagePromise,
  62796. finishPromise
  62797. } = viewer.startScreenshot({
  62798. type: 'default',
  62799. bgOpacity: 0,
  62800. focusObjectInfo,
  62801. maxTimeForPointLoad: 3e5,
  62802. pointDensity: 'screenshot2',
  62803. splitRenderInfo,
  62804. beforeScreenshot
  62805. }, w, h, 1);
  62806. finishPromise.done(_ref => {
  62807. var {
  62808. dataUrl
  62809. } = _ref;
  62810. viewer.inputHandler.toggleSelection(Clip.box);
  62811. Clip.box.visible = true;
  62812. var img = new Image();
  62813. img.src = dataUrl;
  62814. img.onload = /*#__PURE__*/_asyncToGenerator(function* () {
  62815. //加上标尺比例水印
  62816. //固定文字大小和边距像素 //如果有一边过小,可能超出画面外,暂时不管这种可能
  62817. var fontsize = math.linearClamp(w, [100, 700, 8000], [12, 20, 30]);
  62818. var marginSelf = {
  62819. //img外的margin(标尺内)
  62820. left: rulerBound ? 76 : 40,
  62821. right: rulerBound ? 30 : 40,
  62822. bottom: rulerBound ? 20 + fontsize * 2 : 40 + fontsize * 2,
  62823. top: rulerBound ? 60 : 40
  62824. };
  62825. //const Margin = rulerMargin + marginSelf
  62826. //文字的边距
  62827. var bottomRatioToImg = -Math.min(fontsize * 2.5, rulerBound ? marginSelf.bottom : marginSelf.bottom * 0.9) / h; //- (marginSelf.bottom - fontsize)/ h //在img之下. text底部到img底部的距离
  62828. //let leftRatioToImg = Margin / w
  62829. var labelInfo = {
  62830. bottomRatioToImg,
  62831. horizonCenter: true,
  62832. //leftRatioToImg,
  62833. textColor: rulerBound ? {
  62834. r: 0,
  62835. g: 0,
  62836. b: 0,
  62837. a: 1
  62838. } : {
  62839. r: 255,
  62840. g: 255,
  62841. b: 255,
  62842. a: 1
  62843. },
  62844. textBorderColor: {
  62845. r: 30,
  62846. g: 30,
  62847. b: 30,
  62848. a: 1
  62849. },
  62850. textBorderThick: rulerBound ? 0 : 1,
  62851. fontsize,
  62852. fontWeight: rulerBound ? 'normal' : 'Bold',
  62853. outputCanvas: !!rulerBound,
  62854. bgColor: rulerBound ? {
  62855. r: 255,
  62856. g: 255,
  62857. b: 255,
  62858. a: 255
  62859. } : null
  62860. };
  62861. labelInfo.bgMargin = {
  62862. //img外需要多少margin
  62863. left: marginSelf.left + rulerMargin,
  62864. //rulerMargin是在标尺外的margin
  62865. bottom: marginSelf.bottom + rulerMargin,
  62866. right: marginSelf.right + rulerMargin,
  62867. top: marginSelf.top + rulerMargin
  62868. };
  62869. if (rulerBound) {
  62870. //因为margin 扩大bound
  62871. rulerBound.left -= marginSelf.left * meterPerPixel;
  62872. rulerBound.right += marginSelf.right * meterPerPixel;
  62873. rulerBound.top -= marginSelf.top * meterPerPixel;
  62874. rulerBound.bottom += marginSelf.bottom * meterPerPixel;
  62875. }
  62876. //console.log('topRatioToImg',topRatioToImg,'leftRatioToImg',leftRatioToImg,'fontsize', labelInfo.fontsize)
  62877. var result = yield Potree.Utils.imgAddText(img, text, labelInfo);
  62878. //Common.downloadFile(finalDataUrl, 'screenshot11.png')
  62879. visiPointclouds.forEach((e, i) => e.material = materials[i]);
  62880. Clip.screenshoting = false;
  62881. viewer.viewports = [viewer.mainViewport];
  62882. resolve(result);
  62883. });
  62884. });
  62885. });
  62886. /*
  62887. 隐患:无法获知最大可加载的点的数量,也未知需要加载的点的数量。需要掌控好分块数量,避免因pointBudget限制造成周围的点稀疏。
  62888. 加载点云时间过久
  62889. */
  62890. return finishPromise;
  62891. });
  62892. function screenshot(_x, _x2) {
  62893. return _screenshot.apply(this, arguments);
  62894. }
  62895. return screenshot;
  62896. }()
  62897. };
  62898. /*
  62899. 裁剪点云时,2D界面显示全部平面图,按楼层切换显示。
  62900. 所有点云下载后点云所带的本地坐标都是场景显示的local坐标,这样才能看起来一样。
  62901. 且为了使之和坐标页面对应,坐标页面的本地坐标也是local,而非mesh_local.
  62902. //保存box
  62903. viewer.modules.Clip.box.matrix
  62904. //恢复box
  62905. let a = new THREE.Matrix4().fromArray([
  62906. 14.189120116830964,
  62907. 0,
  62908. 0,
  62909. 0,
  62910. 0,
  62911. 9.924790069368392,
  62912. 0,
  62913. 0,
  62914. 0,
  62915. 0,
  62916. 0.8751009568437951,
  62917. 0,
  62918. -7.433819981633984,
  62919. 1.528696446650445,
  62920. 2.9412375879215977,
  62921. 1
  62922. ])
  62923. a.decompose(viewer.modules.Clip.box.position,viewer.modules.Clip.box.quaternion,viewer.modules.Clip.box.scale)
  62924. viewer.modules.Clip.rotateSideCamera(-93)
  62925. */
  62926. var viewportProps = [{
  62927. left: 0.5,
  62928. bottom: 0.5,
  62929. width: 0.5,
  62930. height: 0.5,
  62931. name: 'MainView',
  62932. //view: viewer.scene.view,
  62933. active: true
  62934. }, {
  62935. left: 0,
  62936. bottom: 0.5,
  62937. width: 0.5,
  62938. height: 0.5,
  62939. name: 'top',
  62940. name2: 'mapViewport',
  62941. axis: ["x", "y"],
  62942. direction: new Vector3(0, 0, -1),
  62943. //镜头朝向
  62944. //axisSign:[1,1],
  62945. active: true
  62946. //相机位置在z轴正向
  62947. }, {
  62948. left: 0.5,
  62949. bottom: 0,
  62950. width: 0.5,
  62951. height: 0.5,
  62952. name: 'right',
  62953. axis: ["y", "z"],
  62954. direction: new Vector3(1, 0, 0),
  62955. //axisSign:[1,1],
  62956. active: true
  62957. //相机位置在x轴负向 右下角屏
  62958. }, {
  62959. left: 0,
  62960. bottom: 0,
  62961. width: 0.5,
  62962. height: 0.5,
  62963. name: 'back',
  62964. axis: ["x", "z"],
  62965. direction: new Vector3(0, -1, 0),
  62966. //axisSign:[-1,1], // 从镜头方向看 x向左 所以取负
  62967. active: true
  62968. //相机位置在y轴正向 左下角屏
  62969. }];
  62970. var SplitScreen4Views = new SplitScreen();
  62971. SplitScreen4Views.split = function () {
  62972. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  62973. var defaultCamera = viewer.scene.getActiveCamera();
  62974. var {
  62975. boundSize,
  62976. center
  62977. } = viewer.bound;
  62978. viewer.setLimitFar(false);
  62979. viewer.mapViewer.attachToMainViewer(true, 'split4Screens', 'dontSet');
  62980. viewer.renderer.clear(); //clear back的viewport左边的1px宽的部分,因setScissor的bug
  62981. var viewports = this.splitStart(viewportProps);
  62982. //覆盖在map上、点云等其他物体之下的一层背景
  62983. var mapViewport = viewer.mapViewer.viewports[0];
  62984. mapViewport.noPointcloud = false;
  62985. //隐藏地图游标
  62986. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', false)
  62987. /* viewer.images360.panos.forEach(pano=>{
  62988. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false) //希望这时候mapMarker已经建好了吧
  62989. }) */
  62990. /* viewer.images360.panos.forEach(pano=>{
  62991. pano.addLabel2()
  62992. Potree.Utils.updateVisible(pano.label2, 'notDisplay', true)
  62993. pano.dispatchEvent({type:'changeMarkerTex',name:'ring'})
  62994. }) */
  62995. //材质
  62996. this.statesBefore = {
  62997. pointDensity: Potree.settings.pointDensity,
  62998. displayMode: Potree.settings.displayMode,
  62999. position: viewer.images360.position,
  63000. target: viewer.scene.view.getPivot(),
  63001. currentPano: viewer.images360.currentPano
  63002. //---
  63003. //ifShowMarker : Potree.settings.ifShowMarker,
  63004. };
  63005. viewer.setPointStandardMat(true, null, true); //切换到标准模式(主要为了mainViewport) 点云使用标准大小
  63006. var matBefore = {
  63007. opacity: new Map()
  63008. };
  63009. var newOpacityMap = new Map();
  63010. viewer.scene.pointclouds.forEach(e => {
  63011. matBefore.opacity.set(e, e.temp.pointOpacity);
  63012. matBefore.colorType = e.material.activeAttributeName;
  63013. /* {
  63014. var map = new Map()
  63015. newOpacityMap.set(e, map )
  63016. var size = e.bound.getSize()
  63017. viewports.forEach(viewport=>{//根据bound设置opacity,越小的要靠越近,需要大的opacity。但似乎影响太大了
  63018. if(viewport.name == 'MainView')return;
  63019. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  63020. let axis = prop.axis
  63021. var width = size[axis[0]]
  63022. var height = size[axis[1]]
  63023. var area = width * height
  63024. map.set(viewport, 5000/area);
  63025. })
  63026. } */
  63027. });
  63028. var beforeRender = function beforeRender() {
  63029. viewer.dealBeforeRender = true; //使不全部渲染
  63030. viewer.scene.pointclouds.forEach(e => {
  63031. if (this.name == "MainView") {
  63032. e.material.activeAttributeName = matBefore.colorType; // 'rgba'
  63033. e.material.useFilterByNormal = false;
  63034. //e.material.pointSizeType = Potree.config.material.pointSizeType
  63035. e.changePointOpacity(matBefore.opacity.get(e)); //1 //恢复下 e.temp.pointOpacity 其实就是1
  63036. Potree.settings.pointDensity = 'fourViewportsMain'; /* 'fourViewports' */ //本来想比另外三屏高一点质量,结果发现会闪烁,因为点云加载需要时间 (navvis仿版也是一样,以后看看能否优化)
  63037. } else {
  63038. e.material.activeAttributeName = "color";
  63039. e.material.useFilterByNormal = true;
  63040. //e.material.pointSizeType = 'ADAPTIVE'
  63041. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  63042. //侧面重叠概率更大,所以透明度调小
  63043. e.changePointOpacity(this.name == "mapViewport" ? 0.5 : 0.1 /* newOpacityMap.get(e).get(viewport), true */); //多数据集有的数据集很小,放大后显示特别淡
  63044. //console.log(e.name, viewport.name, e.temp.pointOpacity, e.material.opacity)
  63045. }
  63046. viewer.images360.panos.forEach(pano => {
  63047. if (this.name == 'mapViewport') {
  63048. Potree.Utils.updateVisible(pano.marker, 'showOnMap', true, 1, 'add');
  63049. } else {
  63050. Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel');
  63051. }
  63052. });
  63053. });
  63054. viewer.dealBeforeRender = false;
  63055. };
  63056. viewports.forEach(viewport => {
  63057. viewport.beforeRender = beforeRender;
  63058. new AxisViewer(viewport, viewer.renderArea, {
  63059. domStyle: {
  63060. top: '22px',
  63061. //viewport.name == 'mapViewport' ? '2px' : '-25px',
  63062. right: viewport.name == 'mapViewport' ? '30px' : '2px',
  63063. width: '80px',
  63064. height: '80px'
  63065. }
  63066. });
  63067. });
  63068. this.enableMap(false);
  63069. this.enableFloorplan(false);
  63070. viewer.mapViewer.setViewLimit('null'); //多数据集距离远时可以任意远,所以不限制了。但是这样就会看到地图边界了怎么办?超出后让地图隐藏?
  63071. //viewer.dispatchEvent({'type': 'beginSplitView' })
  63072. //viewer.updateScreenSize({forceUpdateSize:true})
  63073. //this.viewportFitBound(mapViewport, boundSize, center)
  63074. //Potree.settings.ifShowMarker = false
  63075. Potree.settings.displayMode = 'showPointCloud';
  63076. };
  63077. SplitScreen4Views.recover = function () {
  63078. viewer.viewports.forEach(e => {
  63079. e.axis.dispose();
  63080. });
  63081. this.unSplit();
  63082. viewer.mapViewer.viewports[0].beforeRender = null;
  63083. /* const {width, height} = viewer.renderer.getSize(new THREE.Vector2());
  63084. viewer.renderer.setViewport(0,0,width,height)
  63085. viewer.renderer.setScissorTest( false ); */
  63086. viewer.setView({
  63087. position: this.statesBefore.position,
  63088. target: this.statesBefore.target,
  63089. currentPano: this.statesBefore.currentPano,
  63090. duration: 300,
  63091. callback: function callback() {}
  63092. });
  63093. viewer.mainViewport.beforeRender = null;
  63094. viewer.setLimitFar(true);
  63095. var mapViewport = viewer.mapViewer.viewports[0];
  63096. viewer.mapViewer.attachToMainViewer(false);
  63097. //Potree.Utils.updateVisible(viewer.mapViewer.cursor, 'split4Screens', true)
  63098. /* viewer.images360.panos.forEach(pano=>{
  63099. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true)
  63100. }) */
  63101. /* viewer.images360.panos.forEach(pano=>{
  63102. Potree.Utils.updateVisible(pano.label2, 'notDisplay', false )
  63103. pano.dispatchEvent({type:'changeMarkerTex',name:'default'})
  63104. }) */
  63105. mapViewport.noPointcloud = true;
  63106. {
  63107. this.enableMap(Potree.settings.mapEnable);
  63108. this.enableFloorplan(Potree.settings.floorplanEnable);
  63109. if (this.floorplanListener) {
  63110. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', this.floorplanListener);
  63111. this.floorplanListener = null;
  63112. }
  63113. }
  63114. Potree.settings.pointDensity = this.statesBefore.pointDensity;
  63115. if (!Potree.settings.isOfficial) {
  63116. Potree.settings.displayMode = this.statesBefore.displayMode;
  63117. }
  63118. viewer.scene.pointclouds.forEach(e => {
  63119. e.material.useFilterByNormal = false;
  63120. //e.material.pointSizeType = Potree.config.material.pointSizeType
  63121. });
  63122. viewer.setPointStandardMat(false);
  63123. viewer.mapViewer.setViewLimit('standard');
  63124. viewer.images360.panos.forEach(pano => {
  63125. Potree.Utils.updateVisible(pano.marker, 'showOnMap', false, 1, 'cancel');
  63126. });
  63127. //Potree.settings.ifShowMarker = this.statesBefore.ifShowMarker
  63128. //viewer.dispatchEvent({'type': 'finishSplitView' })
  63129. //viewer.updateScreenSize({forceUpdateSize:true})
  63130. };
  63131. SplitScreen4Views.updateMapViewerBG = function () {
  63132. var mapViewport = viewer.mapViewer.viewports[0];
  63133. if (this.splited && (this.floorplanEnabled || this.mapEnabled)) {
  63134. mapViewport.background = 'overlayColor';
  63135. mapViewport.backgroundColor = new Color(0, 0, 0);
  63136. mapViewport.backgroundOpacity = 0.5;
  63137. } else {
  63138. mapViewport.background = null;
  63139. mapViewport.backgroundColor = null;
  63140. mapViewport.backgroundOpacity = null;
  63141. }
  63142. viewer.mapViewer.mapChanged = true;
  63143. viewer.mapViewer.needUpdate = true;
  63144. };
  63145. SplitScreen4Views.setFloorplanDisplay = function (e) {
  63146. var show = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  63147. e.floorplan.setEnable(show);
  63148. };
  63149. SplitScreen4Views.enableMap = function (enable) {
  63150. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'map');
  63151. map.setEnable(!!enable);
  63152. //viewer.mapViewer.mapGradientBG = viewer.background == 'gradient' && !enable
  63153. this.mapEnabled = enable;
  63154. this.updateMapViewerBG();
  63155. },
  63156. //直接覆盖原设置
  63157. SplitScreen4Views.enableFloorplan = function (enable) {
  63158. //是否让自定义的平面图显示
  63159. var floorplans = viewer.mapViewer.mapLayer.maps.filter(e => e.name.includes('floorplan'));
  63160. if (this.floorplanListener) {
  63161. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', this.floorplanListener);
  63162. }
  63163. this.floorplanListener = e => {
  63164. this.setFloorplanDisplay(e, enable);
  63165. };
  63166. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', this.floorplanListener); //万一之后才加载
  63167. if (!enable) {
  63168. //隐藏平面图
  63169. floorplans.forEach(floorplan => this.setFloorplanDisplay({
  63170. floorplan
  63171. }, false));
  63172. } else {
  63173. floorplans.forEach(floorplan => this.setFloorplanDisplay({
  63174. floorplan
  63175. }, true));
  63176. }
  63177. if (enable && floorplans.length == 0) Potree.loadMapEntity('all', true);
  63178. this.floorplanEnabled = enable;
  63179. this.updateMapViewerBG();
  63180. },
  63181. /* viewportFitBound:function(viewport, boundSize, center){ //使一个viewport聚焦在某个范围
  63182. var prop = viewportProps.find(v => viewport.name == v.name2||viewport.name == v.name)
  63183. let axis = prop.axis
  63184. let expand = 10;
  63185. let position = center.clone()
  63186. var moveAtAxis = ['x','y','z'].find(e=>!(axis.includes(e)))
  63187. if(viewport.name == 'mapViewport'){
  63188. let ori = viewport.view.position[moveAtAxis]
  63189. position[moveAtAxis] = ori //不改变这个值,尤其是mapViewer中的z
  63190. }else{
  63191. position[moveAtAxis] += boundSize[moveAtAxis]/2+expand//移动到bounding边缘外
  63192. }
  63193. viewport.view.position.copy(position)
  63194. var width = Math.max(boundSize[axis[0]], boundSize[axis[1]] * viewport.camera.aspect)//视口宽度(米)
  63195. var margin = 50 //px
  63196. viewport.camera.zoom = (viewport.resolution.x - margin) / width
  63197. viewport.camera.updateProjectionMatrix()
  63198. },
  63199. */
  63200. SplitScreen4Views.focusOnPointCloud = function (pointcloud) {
  63201. //三个屏都聚焦在这个点云
  63202. var boundSize = pointcloud.bound.getSize(new Vector3());
  63203. var center = pointcloud.bound.getCenter(new Vector3());
  63204. var target = pointcloud.panosBound && pointcloud.panosBound.center; //看向pano集中的地方,也就是真正有点云的地方。(因为需要展示所有点云,所以没办法用这个做为center)
  63205. this.focusOnObject(pointcloud.bound, center, target);
  63206. viewer.flyToDataset({
  63207. pointcloud,
  63208. dontMoveMap: true,
  63209. duration: 0
  63210. });
  63211. };
  63212. SplitScreen4Views.focusOnObject = function (bound, center, target) {
  63213. var duration = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
  63214. viewer.viewports.forEach(e => {
  63215. if (e.name == 'MainView') {
  63216. /* let len = boundSize.length()
  63217. let distance = THREE.Math.clamp(e.view.position.distanceTo(center), len * 0.01, len*0.3 ) //距离限制
  63218. //viewer.focusOnObject({position:center}, 'point', duration, {distance, direction: e.view.direction,dontMoveMap:true} )//平移镜头
  63219. //为了方便定位,直接飞到中心位置:
  63220. e.view.setView({
  63221. position:center, duration, target
  63222. }) */
  63223. } else {
  63224. this.viewportFitBound(e, bound, center);
  63225. }
  63226. });
  63227. };
  63228. var Alignment = {
  63229. SplitScreen: SplitScreen4Views,
  63230. handleState: null,
  63231. //操作状态 'translate'|'rotate'
  63232. bus: new EventDispatcher(),
  63233. /* prepareRecord : true,
  63234. writeToHistory(pointclouds){
  63235. if(!this.prepareRecord)return;
  63236. this.prepareRecord = false
  63237. let content = this.getTemp(pointclouds)
  63238. this.history.writeIn(content)
  63239. },
  63240. undo(){//撤销一步
  63241. let last = this.history.pop();
  63242. last && last.forEach(item=>{
  63243. this.applyTemp(item)
  63244. })
  63245. }, */
  63246. applyTemp(item) {
  63247. var pointcloud = viewer.scene.pointclouds.find(p => p.dataset_id + p.name == item.sid);
  63248. pointcloud.orientationUser = item.orientationUser;
  63249. pointcloud.translateUser = item.translateUser;
  63250. this.setMatrix(pointcloud);
  63251. },
  63252. getTemp(pointclouds) {
  63253. //记录最近一次保存后的状态,便于恢复
  63254. pointclouds = pointclouds || viewer.scene.pointclouds;
  63255. return pointclouds.map(e => {
  63256. return {
  63257. sid: e.dataset_id + e.name,
  63258. orientationUser: e.orientationUser,
  63259. translateUser: e.translateUser.clone()
  63260. };
  63261. });
  63262. },
  63263. init: function init() {
  63264. var transfromInfo;
  63265. this.history = new History({
  63266. applyData: data => {
  63267. data.forEach(item => {
  63268. Alignment.applyTemp(item);
  63269. });
  63270. return true;
  63271. },
  63272. getData: pointclouds => {
  63273. return Alignment.getTemp(pointclouds);
  63274. }
  63275. });
  63276. viewer.fpControls.addEventListener("transformPointcloud", e => {
  63277. if (e.pointclouds[0].dataset_id == Potree.settings.originDatasetId) {
  63278. //禁止手动移动初始数据集
  63279. return this.bus.dispatchEvent('forbitMoveOriginDataset');
  63280. }
  63281. this.history.beforeChange(e.pointclouds);
  63282. //this.writeToHistory( e.pointclouds )
  63283. if (!transfromInfo) {
  63284. transfromInfo = {
  63285. pointclouds: e.pointclouds
  63286. };
  63287. }
  63288. if (this.handleState == 'translate') {
  63289. e.pointclouds.forEach(cloud => Alignment.translate(cloud, e.moveVec));
  63290. } else if (this.handleState == 'rotate') {
  63291. if (Potree.settings.editType == 'pano') {
  63292. //旋转中心是intersectStart的版本
  63293. /* let center = e.intersectStart //旋转中心是mousedown的位置
  63294. if(e.intersect.equals(center))return
  63295. if(!transfromInfo){
  63296. transfromInfo = {
  63297. orientationUser : e.pointclouds[0].orientationUser,
  63298. //vecStart : e.moveVec, // 首次移动向量 只有八个方向,精度太小,所以延迟
  63299. pointclouds: e.pointclouds
  63300. }
  63301. this.bus.dispatchEvent({type:'rotateStart', startPoint:center})
  63302. return
  63303. }else if(!transfromInfo.vecStart){
  63304. let vec = new THREE.Vector3().subVectors(e.intersect, center).setZ(0)
  63305. if(vec.length() * e.camera.zoom > 30){ //在屏幕上距离初始点有一定距离后开始算
  63306. //console.log('moveVec',vec)
  63307. transfromInfo.vecStart = vec
  63308. } */
  63309. var center = e.pointclouds[0].translateUser; //旋转中心是第一个点云的位置
  63310. if (e.intersect.equals(center)) return;
  63311. if (!transfromInfo.vecStart) {
  63312. transfromInfo.orientationUser = e.pointclouds[0].orientationUser;
  63313. transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, center).setZ(0);
  63314. } else {
  63315. var vec = new Vector3().subVectors(e.intersect, center).setZ(0);
  63316. var angle = math.getAngle(transfromInfo.vecStart, vec, 'z');
  63317. var diffAngle = transfromInfo.orientationUser + angle - transfromInfo.pointclouds[0].orientationUser;
  63318. transfromInfo.pointclouds.forEach(cloud => {
  63319. /* let centerNoTranfrom = Potree.Utils.datasetPosTransform({ toDataset: true, pointcloud:cloud, position: center }) //中心点在数据集中的位置
  63320. Alignment.rotate(cloud, null, diffAngle)
  63321. let centerNow = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:cloud, position: centerNoTranfrom }) //中心点的现在位置
  63322. let shift = new THREE.Vector3().subVectors( center, centerNow); //偏移量
  63323. Alignment.translate(cloud,shift) //使center还保留在原位
  63324. //let centerNow1 = Potree.Utils.datasetPosTransform({ fromDataset: true, pointcloud:transfromInfo.pointcloud, position: centerNoTranfrom }) //中心点的现在位置
  63325. */
  63326. Alignment.rotateAround(center, cloud, null, diffAngle);
  63327. });
  63328. }
  63329. //this.bus.dispatchEvent({type:'rotate', endPoint: e.intersect})
  63330. } else {
  63331. var _center = e.pointclouds[0].translateUser; //移动到的位置就是中心
  63332. if (e.intersect.equals(_center)) return;
  63333. if (!transfromInfo.vecStart) {
  63334. transfromInfo.orientationUser = e.pointclouds[0].orientationUser;
  63335. transfromInfo.vecStart = new Vector3().subVectors(e.intersectStart, _center).setZ(0);
  63336. } else {
  63337. var _vec = new Vector3().subVectors(e.intersect, _center).setZ(0);
  63338. var _angle = math.getAngle(transfromInfo.vecStart, _vec, 'z');
  63339. var _diffAngle = transfromInfo.orientationUser + _angle - transfromInfo.pointclouds[0].orientationUser;
  63340. Alignment.rotate(transfromInfo.pointclouds[0], null, _diffAngle);
  63341. }
  63342. }
  63343. }
  63344. });
  63345. viewer.fpControls.addEventListener("end", e => {
  63346. transfromInfo && this.history.afterChange(transfromInfo.pointclouds);
  63347. transfromInfo = null;
  63348. });
  63349. // cursor:
  63350. var updateCursor = e => {
  63351. if (e.drag || !this.editing) return; //仅在鼠标不按下时更新:
  63352. var handleState = Alignment.handleState;
  63353. if (e.hoverViewport.alignment && handleState && e.hoverViewport.alignment[handleState]) {
  63354. if (handleState == 'translate') {
  63355. if (e.intersect && e.intersect.location) {
  63356. viewer.dispatchEvent({
  63357. type: "CursorChange",
  63358. action: "add",
  63359. name: "movePointcloud"
  63360. });
  63361. } else {
  63362. viewer.dispatchEvent({
  63363. type: "CursorChange",
  63364. action: "remove",
  63365. name: "movePointcloud"
  63366. });
  63367. }
  63368. } else if (handleState == 'rotate') {
  63369. if (e.intersect && e.intersect.location) {
  63370. viewer.dispatchEvent({
  63371. type: "CursorChange",
  63372. action: "add",
  63373. name: "rotatePointcloud"
  63374. });
  63375. } else {
  63376. viewer.dispatchEvent({
  63377. type: "CursorChange",
  63378. action: "remove",
  63379. name: "rotatePointcloud"
  63380. });
  63381. }
  63382. }
  63383. } else {
  63384. //清空:
  63385. viewer.dispatchEvent({
  63386. type: "CursorChange",
  63387. action: "remove",
  63388. name: "movePointcloud"
  63389. });
  63390. viewer.dispatchEvent({
  63391. type: "CursorChange",
  63392. action: "remove",
  63393. name: "rotatePointcloud"
  63394. });
  63395. }
  63396. };
  63397. viewer.addEventListener('global_mousemove', updateCursor);
  63398. viewer.addEventListener('global_drop', updateCursor); //拖拽结束
  63399. viewer.addEventListener('updateModelBound', e => {
  63400. if (this.editing) {
  63401. this.SplitScreen.updateCameraOutOfModel();
  63402. }
  63403. });
  63404. },
  63405. setMatrix: function setMatrix(pointcloud) {
  63406. var vec1 = pointcloud.position; //position为数据集内部的偏移,在navvis中对应的是dataset.pointCloudSceneNode的children[0].position
  63407. var vec2 = pointcloud.translateUser;
  63408. var angle = pointcloud.orientationUser;
  63409. var pos1Matrix = new Matrix4().setPosition(vec1); //先移动到点云本身应该在的初始位置(在4dkk里和其他应用中都是在这个位置的,也能和漫游点对应上)
  63410. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle); //再旋转
  63411. var pos2Matrix = new Matrix4().setPosition(vec2); //最后是平移
  63412. var matrix = new Matrix4().multiplyMatrices(pos2Matrix, rotMatrix);
  63413. pointcloud.transformMatrix = matrix.clone(); //为该数据集的变化矩阵。 对应navvis的m2w_
  63414. pointcloud.transformInvMatrix.copy(pointcloud.transformMatrix).invert();
  63415. pointcloud.rotateMatrix = rotMatrix;
  63416. pointcloud.rotateInvMatrix.copy(rotMatrix).invert();
  63417. pointcloud.panos.forEach(e => e.transformByPointcloud());
  63418. matrix = new Matrix4().multiplyMatrices(matrix, pos1Matrix);
  63419. //matrix.premultiply(viewer.scene.scene.matrix);////////////////////////add
  63420. pointcloud.matrix = matrix;
  63421. //pointcloud.matrixWorldNeedsUpdate = true //更新matrixWorld (非计算,直接赋值)
  63422. pointcloud.updateMatrixWorld(true);
  63423. if (this.editing) {
  63424. Alignment.changeCallBack && Alignment.changeCallBack();
  63425. }
  63426. if (pointcloud.spriteNodeRoot) {
  63427. pointcloud.spriteNodeRoot.matrixWorld.copy(pointcloud.matrixWorld); //.multiplyMatrices(pointcloud.matrixWorld, pointcloud.matrixWorld);
  63428. }
  63429. viewer.boundNeedUpdate = true;
  63430. //pointcloud.updateBound()
  63431. pointcloud.getPanosBound();
  63432. viewer.dispatchEvent('content_changed');
  63433. },
  63434. rotateAround(center, pointcloud, deg, angle) {
  63435. //绕center点转动
  63436. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg);
  63437. var vec1 = new Vector3().subVectors(pointcloud.translateUser, center);
  63438. var rotMatrix = new Matrix4().makeRotationAxis(new Vector3(0, 0, 1), angle);
  63439. var vec2 = vec1.clone().applyMatrix4(rotMatrix); //将到旋转中心的偏差也转动
  63440. var vec3 = new Vector3().subVectors(vec2, vec1); //这个就是多出来的一步translateUser
  63441. this.rotate(pointcloud, deg, angle);
  63442. this.translate(pointcloud, vec3);
  63443. //绕点转动就是比普通转动多一步移动到相对center的某个位置。 1 初始点云移动到自己的position; 2 移动一个vec1 3绕原点旋转 4再移动一个原本的translateUser。 绘制出来后发现移动量就是第二步vec旋转后的偏移
  63444. },
  63445. rotate: function rotate(pointcloud, deg, angle) {
  63446. //绕各自中心转动(各自的position) 假设点云位移position后0,0,0就是它的中心了(根据navvis观察这样做是绕同一个点旋转的)
  63447. var angle = angle != void 0 ? angle : MathUtils.degToRad(deg); //正逆负顺
  63448. pointcloud.orientationUser += angle;
  63449. Alignment.setMatrix(pointcloud);
  63450. },
  63451. translate: function translate(pointcloud, vec) {
  63452. pointcloud.translateUser.add(vec);
  63453. Alignment.setMatrix(pointcloud);
  63454. },
  63455. enter: function enter() {
  63456. //this.saveTemp()
  63457. this.originData = this.getTemp();
  63458. this.SplitScreen.split({
  63459. alignment: true
  63460. });
  63461. /* viewer.images360.panos.forEach(pano=>{
  63462. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', false)
  63463. }) */
  63464. viewer.viewports.find(e => e.name == 'mapViewport').alignment = {
  63465. rotate: true,
  63466. translate: true
  63467. };
  63468. viewer.viewports.find(e => e.name == 'right').alignment = {
  63469. translate: true,
  63470. translateVec: new Vector3(0, 0, 1)
  63471. }; //只能上下移动
  63472. viewer.viewports.find(e => e.name == 'back').alignment = {
  63473. translate: true,
  63474. translateVec: new Vector3(0, 0, 1)
  63475. }; //只能上下移动
  63476. this.editing = true;
  63477. viewer.updateFpVisiDatasets();
  63478. },
  63479. leave: function leave() {
  63480. this.switchHandle(null);
  63481. /* this.originData.forEach(e=>{//恢复
  63482. var pointcloud = viewer.scene.pointclouds.find(p=>p.dataset_id == e.id)
  63483. this.translate(pointcloud, new THREE.Vector3().subVectors(e.translateUser , pointcloud.translateUser))
  63484. this.rotate(pointcloud, null, e.orientationUser - pointcloud.orientationUser)
  63485. }) */
  63486. this.originData.forEach(e => {
  63487. //恢复
  63488. this.applyTemp(e);
  63489. });
  63490. this.SplitScreen.recover();
  63491. /* viewer.images360.panos.forEach(pano=>{
  63492. Potree.Utils.updateVisible(pano.mapMarker, 'split4Screens', true)
  63493. }) */
  63494. this.editing = false;
  63495. this.history.clear();
  63496. viewer.updateFpVisiDatasets();
  63497. viewer.dispatchEvent({
  63498. type: "CursorChange",
  63499. action: "remove",
  63500. name: "movePointcloud"
  63501. });
  63502. viewer.dispatchEvent({
  63503. type: "CursorChange",
  63504. action: "remove",
  63505. name: "rotatePointcloud"
  63506. });
  63507. },
  63508. switchHandle: function switchHandle(state) {
  63509. this.handleState = state;
  63510. //清空:
  63511. viewer.dispatchEvent({
  63512. type: "CursorChange",
  63513. action: "remove",
  63514. name: "movePointcloud"
  63515. });
  63516. viewer.dispatchEvent({
  63517. type: "CursorChange",
  63518. action: "remove",
  63519. name: "rotatePointcloud"
  63520. });
  63521. this.bus.dispatchEvent({
  63522. type: 'switchHandle',
  63523. state
  63524. });
  63525. },
  63526. save: function save() {
  63527. //保存所有数据集的位置和旋转
  63528. var callback = () => {
  63529. //保存成功后
  63530. this.originData = this.getTemp(); //this.saveTemp();
  63531. //需要修改 测量线的position。漫游点已经实时修改了
  63532. viewer.scene.measurements.forEach(e => e.transformByPointcloud());
  63533. viewer.images360.updateCube(viewer.bound);
  63534. };
  63535. var data = viewer.scene.pointclouds.map(e => {
  63536. var pos = viewer.transform.lonlatToLocal.inverse(e.translateUser.clone());
  63537. var initialPointcloud = viewer.scene.pointclouds.find(e => e.dataset_id == Potree.settings.originDatasetId);
  63538. return {
  63539. id: e.dataset_id,
  63540. orientation: e.orientationUser,
  63541. location: [pos.x, pos.y, pos.z + initialPointcloud.datasetData.location[2]]
  63542. //transformMatrix: e.transformMatrix.elements,
  63543. };
  63544. });
  63545. //data = JSON.stringify(data)
  63546. //test: 退出后保留结果
  63547. if (!Potree.settings.isOfficial) {
  63548. callback();
  63549. }
  63550. return {
  63551. data,
  63552. callback
  63553. };
  63554. }
  63555. };
  63556. var texLoader$9 = new TextureLoader();
  63557. var markerMats$2;
  63558. var markerSizeInfo$2 = {
  63559. width2d: 35
  63560. };
  63561. var color$2 = new Color('#FFF');
  63562. var faceMats;
  63563. var getFaceMat = name => {
  63564. if (!faceMats) {
  63565. //navvis材质可以搜gridTexture
  63566. var gridTex = texLoader$9.load(Potree.resourcePath + '/textures/gridmap.png');
  63567. gridTex.wrapS = gridTex.wrapT = RepeatWrapping;
  63568. //gridTex.repeat.set(0.5,0.5)//放大一些
  63569. faceMats = {
  63570. dataset: new MeshStandardMaterial({
  63571. color: 812922,
  63572. side: DoubleSide,
  63573. opacity: 0.2,
  63574. transparent: true,
  63575. depthTest: false,
  63576. wireframe: true
  63577. }),
  63578. building: new MeshStandardMaterial({
  63579. color: 812922,
  63580. metalness: 0.2,
  63581. roughness: 0.8,
  63582. side: DoubleSide,
  63583. opacity: 0.1,
  63584. transparent: true,
  63585. depthTest: true
  63586. }),
  63587. buildingSelect: new MeshStandardMaterial({
  63588. color: 36582,
  63589. metalness: 0,
  63590. roughness: 1,
  63591. side: DoubleSide,
  63592. opacity: 0.1,
  63593. transparent: true,
  63594. depthTest: true
  63595. }),
  63596. floor: new MeshStandardMaterial({
  63597. color: 11708469,
  63598. metalness: 0.1,
  63599. roughness: 1,
  63600. side: DoubleSide,
  63601. //BackSide,
  63602. opacity: 0.05,
  63603. transparent: true,
  63604. depthTest: true
  63605. }),
  63606. floorSelect: new DepthBasicMaterial({
  63607. map: gridTex,
  63608. color: 16707151,
  63609. side: DoubleSide,
  63610. //BackSide,
  63611. opacity: 1,
  63612. transparent: true,
  63613. useDepth: true,
  63614. clipDistance: 1,
  63615. occlusionDistance: 1,
  63616. /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  63617. maxClipFactor: 0.9,
  63618. backColor: '#efe' //backColor:"#669988" ,
  63619. }),
  63620. room: new MeshStandardMaterial({
  63621. color: "#ff44ee",
  63622. metalness: 0,
  63623. roughness: 1,
  63624. side: DoubleSide,
  63625. //BackSide,
  63626. opacity: 0.08,
  63627. transparent: true,
  63628. depthTest: false
  63629. }),
  63630. roomSelect: new DepthBasicMaterial({
  63631. map: gridTex,
  63632. color: "#ff44ee",
  63633. side: DoubleSide,
  63634. //BackSide,
  63635. opacity: 1,
  63636. transparent: true,
  63637. useDepth: true,
  63638. clipDistance: 1,
  63639. occlusionDistance: 0.5,
  63640. /* occlusionDistance:变为backColor距离, clipDistance:opacity到达0或者1-maxClipFactor时的距离 */
  63641. maxClipFactor: 0.8,
  63642. backColor: '#ff88dd' //"#cc99c2" ,
  63643. })
  63644. };
  63645. }
  63646. return faceMats[name];
  63647. };
  63648. class BuildingBox extends ctrlPolygon {
  63649. //建筑实体,包括building, floor, room
  63650. constructor(prop) {
  63651. prop.dimension = '3d';
  63652. //prop.name = Potree.config.siteModel.names[prop.buildType] +
  63653. super('siteModel_' + prop.buildType, prop);
  63654. this.midMarkers = [];
  63655. this.buildChildren = []; //子实体
  63656. this.holes = []; //在这创建的hole
  63657. this.parentHoles = []; //floor从building那得到的当层holes
  63658. this.mats = {}; //材质
  63659. this.panos = this.panos || [];
  63660. this.center; //中心点
  63661. if (this.buildType == 'floor') {
  63662. this.points = prop.points = this.buildParent.points; //完全等于建筑的点
  63663. this.buildParent.holes.forEach(hole => {
  63664. //从building获取holes
  63665. var floorHole = new BuildingBox({
  63666. buildType: 'hole',
  63667. buildParent: this,
  63668. originHole: hole,
  63669. //整栋大楼在当层的hole
  63670. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  63671. });
  63672. this.parentHoles.push(floorHole);
  63673. this.add(floorHole);
  63674. floorHole.points = hole.points; //完全等于建筑的点
  63675. });
  63676. }
  63677. if (this.buildType == 'room' || this.buildType == 'hole') {
  63678. this.restrictArea = this.buildParent; //不能超出的区域
  63679. }
  63680. if (this.buildParent) this.dontDragFloorHeight = this.buildParent.dontDragFloorHeight;
  63681. if (this.buildType != 'hole') {
  63682. this.box = this.createBox(); //无论是否edit都绘制的原因:为了将在外的点移到在内,需要用mesh来获取intersect
  63683. this.add(this.box);
  63684. this.box.visible = !!this.ifDraw;
  63685. }
  63686. if (this.ifDraw) {
  63687. //只存储空间模型信息,不绘制
  63688. {
  63689. this.createPrismLines(color$2);
  63690. this.lineMesh.visible = false;
  63691. Potree.Utils.setObjectLayers(this.lineMesh, 'bothMapAndScene');
  63692. }
  63693. this.addEventListener('dragChange', e => {
  63694. //修改中点
  63695. this.updateTwoMidMarker(e.index);
  63696. });
  63697. }
  63698. this.initData(prop);
  63699. }
  63700. initData(prop) {
  63701. if (prop.ifDraw) {
  63702. super.initData(prop);
  63703. } else {
  63704. if (prop.points) {
  63705. this.points = prop.points;
  63706. }
  63707. }
  63708. }
  63709. intersectPointcloudVolume(pointcloud) {
  63710. //和pointcloud的重叠体积
  63711. return this.intersectPointcloudArea(pointcloud) * this.coverPointcloudHeight(pointcloud);
  63712. }
  63713. coverPointcloudHeight(pointcloud, getPercent) {
  63714. var bound2 = pointcloud.bound;
  63715. var {
  63716. zMin,
  63717. zMax
  63718. } = this.getRealZ();
  63719. var min = Math.min(zMin, bound2.min.z);
  63720. var max = Math.max(zMax, bound2.max.z);
  63721. var height1 = zMax - zMin;
  63722. var height2 = bound2.max.z - bound2.min.z;
  63723. var coverHeight = height1 + height2 - (max - min); //重叠高度 <=0是没重叠
  63724. if (getPercent) {
  63725. return coverHeight / height1;
  63726. }
  63727. return coverHeight;
  63728. }
  63729. intersectPointcloudArea(pointcloud, getPercent) {
  63730. //和pointcloud的重叠面积
  63731. var bound = this.getBound();
  63732. var bound2 = pointcloud.bound;
  63733. if (!bound.intersectsBox(bound2)) return 0;
  63734. var boxPoints = pointcloud.getUnrotBoundPoint(); //获取tightBound的四个点。 如果是有旋转角度的点云,这个和pointcloud.bound的四个点是不一致的,覆盖面积小于pointcloud.bound
  63735. var areaWhole = 0;
  63736. var area1 = this.getArea();
  63737. var area2 = Math.abs(math.getArea(boxPoints));
  63738. {
  63739. //计算points与点云总面积 (但是把hole也加入了面积)(并集,重叠部分只算一次)
  63740. var rings = math.getPolygonsMixedRings([this.points, boxPoints]);
  63741. rings.forEach(e => {
  63742. areaWhole += e.area;
  63743. });
  63744. }
  63745. var coverHoleArea = 0; //holes与数据集重叠的部分
  63746. var holes = this.holes.concat(this.parentHoles);
  63747. var holesArea = 0; //所有holes面积相加
  63748. var areaHoleWithPointcloud = 0; //hole和点云的面积并集
  63749. if (holes.length > 0) {
  63750. //还要再扣除holes与数据集重叠的部分。其中holes为mix轮廓
  63751. var outHoles = []; //没有重合的holes的外轮廓
  63752. /* if(holes.length>=2){//合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  63753. let holes_ = holes.map(e=>e.points)
  63754. outHoles = math.getPolygonsMixedRings(holes_, true )
  63755. outHoles.forEach(e=>{
  63756. holesArea+=e.area
  63757. })
  63758. outHoles = outHoles.map(e=>e.points)
  63759. }else{
  63760. outHoles = holes.map(e=>e.points)
  63761. outHoles.forEach(e=> holesArea += Math.abs(math.getArea(e)))
  63762. } */
  63763. holesArea = this.getHolesArea();
  63764. //holes与数据集重叠的部分
  63765. {
  63766. var polygons = outHoles.concat([boxPoints]);
  63767. var _rings = math.getPolygonsMixedRings(polygons);
  63768. _rings.forEach(e => {
  63769. areaHoleWithPointcloud += e.area;
  63770. });
  63771. coverHoleArea = holesArea + area2 - areaHoleWithPointcloud; //hole和点云的交集
  63772. }
  63773. }
  63774. var coverArea = area1 + area2 - areaWhole - coverHoleArea; //重叠面积
  63775. if (getPercent) {
  63776. return {
  63777. toEntity: coverArea / this.getArea(true),
  63778. //占entity
  63779. toPointcloud: coverArea / area2 //占点云
  63780. };
  63781. }
  63782. return coverArea;
  63783. }
  63784. addHole() {
  63785. var points = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  63786. var prop = {
  63787. buildType: 'hole',
  63788. zMin: this.zMin,
  63789. zMax: this.zMax,
  63790. points,
  63791. buildParent: this,
  63792. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  63793. };
  63794. //hole的zMin zMax跟随buildParent
  63795. var hole = new BuildingBox(prop);
  63796. this.holes.push(hole);
  63797. if (this.buildType == 'building') {
  63798. //为每一层添加对应的hole
  63799. this.buildChildren.forEach(floor => {
  63800. var floorHole = new BuildingBox({
  63801. buildType: 'hole',
  63802. zMin: this.zMin,
  63803. zMax: this.zMax,
  63804. buildParent: floor,
  63805. originHole: hole,
  63806. //整栋大楼在当层的hole
  63807. ifDraw: this.ifDraw || Potree.settings.drawEntityData
  63808. });
  63809. floor.parentHoles.push(floorHole);
  63810. floor.add(floorHole);
  63811. floorHole.points = hole.points; //完全等于建筑的点
  63812. });
  63813. }
  63814. this.add(hole); //直接加在这,不加meshGroup了
  63815. this.update(); //update box mesh
  63816. return hole;
  63817. //hole不创建box,只有它的buildParent需要更新box。 但有线条和marker. hole不在buildChildren里,但有buildParent
  63818. }
  63819. removeHole(hole) {
  63820. // 这个hole不会是parentHoles里的。
  63821. hole.dispose();
  63822. if (this.buildType == 'building') {
  63823. //若是整栋大楼的hole,在每层去除它的对应hole
  63824. this.buildChildren.forEach(floor => {
  63825. var holeAtFloor = floor.parentHoles.find(e => e.originHole == this);
  63826. var index = floor.parentHoles.indexOf(holeAtFloor);
  63827. index > -1 && floor.parentHoles.splice(index, 1);
  63828. holeAtFloor.dispose();
  63829. });
  63830. }
  63831. var index = this.holes.indexOf(hole);
  63832. if (index > -1) {
  63833. this.holes.splice(index, 1);
  63834. }
  63835. this.remove(hole);
  63836. this.update();
  63837. }
  63838. createBox() {
  63839. var geometry = new Geometry();
  63840. this.mats.boxDefault = getFaceMat(this.buildType);
  63841. this.mats.boxSelected = getFaceMat(this.buildType + 'Select');
  63842. var mesh = new Mesh(geometry, this.mats.boxDefault);
  63843. mesh.name = 'buildingBox';
  63844. if (this.buildType == 'floor') {
  63845. Potree.Utils.setObjectLayers(mesh, 'siteModelMapUnvisi'); //楼层默认在地图不显示,为了不会叠加透明度
  63846. //mesh.renderOrder = 1
  63847. } else {
  63848. /* if(this.buildType == 'room'){
  63849. mesh.renderOrder = 2
  63850. } */
  63851. Potree.Utils.setObjectLayers(mesh, 'bothMapAndScene');
  63852. }
  63853. //mesh.frustumCulled = false;
  63854. return mesh;
  63855. }
  63856. addMarker() {
  63857. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  63858. if (this.buildType == 'floor') return; //楼层不需要marker
  63859. var marker = new Sprite$2({
  63860. mat: this.getMarkerMaterial('default'),
  63861. renderOrder: 3,
  63862. sizeInfo: markerSizeInfo$2,
  63863. dontFixOrient: true,
  63864. name: "building_marker"
  63865. });
  63866. Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi');
  63867. o.marker = marker;
  63868. super.addMarker(o);
  63869. if (!this.selected) Potree.Utils.updateVisible(marker, 'select', false);
  63870. var addClickEvent = e => {
  63871. var click = e => {
  63872. this.dispatchEvent({
  63873. type: 'clickMarker',
  63874. marker
  63875. }); //由entity发送给sitemodel统一处理
  63876. };
  63877. marker.addEventListener('click', click);
  63878. marker.addEventListener('clickSelect', e => {
  63879. this.setMarkerSelected(marker, e.state ? 'select' : 'unselect');
  63880. });
  63881. marker.removeEventListener('addHoverEvent', addClickEvent);
  63882. };
  63883. marker.addEventListener('addHoverEvent', addClickEvent); //当非isNew时才添加事件
  63884. if (!this.isNew) {
  63885. marker.dispatchEvent('addHoverEvent');
  63886. }
  63887. return marker;
  63888. }
  63889. removeMarker(index) {
  63890. super.removeMarker(index);
  63891. if (!this.isNew) {
  63892. //重新添加midMarkers
  63893. this.midMarkers.forEach(e => this.remove(e));
  63894. this.midMarkers = [];
  63895. this.addMidMarkers();
  63896. }
  63897. this.update();
  63898. if (this.points.length == 2 && this.box) {
  63899. //清除原先length>=3时候的
  63900. this.box.geometry = new Geometry();
  63901. }
  63902. }
  63903. addMidMarker(index, point) {
  63904. if (this.buildType == 'floor') return; //楼层不需要marker
  63905. var marker = new Sprite$2({
  63906. mat: this.getMarkerMaterial('midPrepare'),
  63907. sizeInfo: markerSizeInfo$2,
  63908. dontFixOrient: true,
  63909. name: "building_midMarker"
  63910. });
  63911. this.midMarkers = [...this.midMarkers.slice(0, index), marker, ...this.midMarkers.slice(index, this.midMarkers.length)];
  63912. marker.renderOrder = 3;
  63913. Potree.Utils.setObjectLayers(marker, 'siteModeOnlyMapVisi');
  63914. {
  63915. // Event Listeners
  63916. var mouseover = e => {
  63917. this.setMarkerSelected(e.object, 'hover', 'single');
  63918. viewer.dispatchEvent({
  63919. type: "CursorChange",
  63920. action: "add",
  63921. name: "markerMove"
  63922. });
  63923. };
  63924. var mouseleave = e => {
  63925. this.setMarkerSelected(e.object, 'unhover', 'single');
  63926. viewer.dispatchEvent({
  63927. type: "CursorChange",
  63928. action: "remove",
  63929. name: "markerMove"
  63930. });
  63931. };
  63932. var drag = e => {
  63933. this.dispatchEvent('startDragging');
  63934. var index = this.midMarkers.indexOf(marker);
  63935. var newMarker = this.addMarker({
  63936. index: index + 1,
  63937. point: marker.position.clone()
  63938. });
  63939. this.addMidMarker(index + 1, new Vector3());
  63940. this.updateTwoMidMarker(index + 1);
  63941. this.setMarkerSelected(marker, 'unhover');
  63942. viewer.inputHandler.startDragging(newMarker, {/* dragViewport:viewer.mapViewer.viewports[0], */}); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  63943. };
  63944. marker.addEventListener('drag', drag);
  63945. marker.addEventListener('mouseover', mouseover);
  63946. marker.addEventListener('mouseleave', mouseleave);
  63947. }
  63948. this.add(marker);
  63949. this.updateMarker(marker, point);
  63950. if (!this.selected) Potree.Utils.updateVisible(marker, 'select', false);
  63951. return marker;
  63952. }
  63953. addMidMarkers() {
  63954. //第一次画好所有marker后,一次性为线段增加中点marker
  63955. var length = this.points.length;
  63956. this.points.forEach((point, index) => {
  63957. var nextPoint = this.points[(index + 1) % length];
  63958. var midPoint = new Vector3().addVectors(point, nextPoint).multiplyScalar(0.5);
  63959. this.addMidMarker(index, midPoint);
  63960. });
  63961. }
  63962. updateTwoMidMarker(index) {
  63963. //更新第index个marker两边的midMarker
  63964. if (!this.midMarkers.length) return;
  63965. var length = this.points.length;
  63966. var last = this.points[(index - 1 + length) % length]; //它之前的marker位置
  63967. var next = this.points[(index + 1) % length]; //它之后的marker位置
  63968. var current = this.points[index]; //当前位置
  63969. var lastMid = new Vector3().addVectors(last, current).multiplyScalar(0.5); //上一个中点
  63970. var nextMid = new Vector3().addVectors(next, current).multiplyScalar(0.5); //下一个中点
  63971. var lastMidMarker = this.midMarkers[(index - 1 + length) % length];
  63972. var nextMidMarker = this.midMarkers[index];
  63973. this.updateMarker(lastMidMarker, lastMid);
  63974. this.updateMarker(nextMidMarker, nextMid);
  63975. }
  63976. dispose() {
  63977. //销毁geo、remove from parent
  63978. super.dispose();
  63979. this.box && this.box.geometry.dispose();
  63980. this.lineMesh && this.lineMesh.geometry.dispose();
  63981. this.holes.forEach(e => e.dispose());
  63982. this.parentHoles.forEach(e => e.dispose());
  63983. //this.buildChildren.forEach(e=>e.dispose())
  63984. this.dispatchEvent('dispose');
  63985. }
  63986. updateBox() {
  63987. if (!this.box) return;
  63988. this.box.geometry.dispose();
  63989. var shrink = this.buildType == 'room' ? 0.11 : this.buildType == 'floor' ? 0.082 : 0.2; //防止mesh重叠冲突(给一个不寻常的数字) 但离远了还是会有点闪烁
  63990. if (this.points.length >= 3) {
  63991. var holes = this.holes.concat(this.parentHoles);
  63992. var holesPoints = holes.filter(e => e.points.length > 2).map(e => e.points);
  63993. this.box.geometry = MeshDraw.getExtrudeGeo(this.points, holesPoints, {
  63994. depth: this.zMax - this.zMin - shrink,
  63995. UVGenerator: new MetricUVGenerator()
  63996. });
  63997. if (this.buildType == 'building') {
  63998. this.box.position.z = this.zMin - shrink / 2;
  63999. } else {
  64000. this.box.position.z = this.zMin + shrink / 2;
  64001. }
  64002. }
  64003. }
  64004. update() {
  64005. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  64006. super.update(this.buildType != 'floor' && options.ifUpdateMarkers);
  64007. var length = this.points.length;
  64008. {
  64009. //确保一下一样
  64010. if (this.originHole) {
  64011. this.points = this.originHole.points; //完全等于building的hole
  64012. }
  64013. if (this.buildType == 'hole') {
  64014. this.zMin = this.buildParent.zMin;
  64015. this.zMax = this.buildParent.zMax;
  64016. }
  64017. }
  64018. if (!options.dontUpdateBox) {
  64019. var boxOwner;
  64020. if (this.buildType == 'hole') {
  64021. if (this.buildParent.buildType == 'building') {
  64022. //若是整栋大楼的hole,在每层都要更新下它的对应hole
  64023. this.buildParent.buildChildren.forEach(floor => {
  64024. var holeAtFloor = floor.parentHoles.find(e => e.originHole == this);
  64025. holeAtFloor && holeAtFloor.update(); //刚开始创建时还没创建对应的 holeAtFloor会为null
  64026. });
  64027. }
  64028. boxOwner = this.buildParent;
  64029. } else {
  64030. boxOwner = this;
  64031. }
  64032. boxOwner.updateBox();
  64033. }
  64034. this.updatePrismLines(); //update lines
  64035. if (!options.dontUpdateChildren) {
  64036. if (this.buildType == 'building') {
  64037. this.buildChildren.forEach(floor => {
  64038. floor.points = this.points;
  64039. floor.update();
  64040. });
  64041. }
  64042. {
  64043. var holes = this.holes.concat(this.parentHoles);
  64044. holes.forEach(hole => {
  64045. hole.update({
  64046. dontUpdateBox: true
  64047. }); //父级更新了box,hole就不需要更新box了
  64048. });
  64049. }
  64050. }
  64051. }
  64052. getHolesArea() {
  64053. var holes = this.holes.concat(this.parentHoles);
  64054. var outHoles,
  64055. holesArea = 0;
  64056. if (holes.length >= 2) {
  64057. //合并holes。如果能在绘制时直接合并holes就好啦,这步就转移到那去,但是要删除hole好麻烦
  64058. var holes_ = holes.map(e => e.points);
  64059. outHoles = math.getPolygonsMixedRings(holes_, true);
  64060. outHoles.forEach(e => {
  64061. holesArea += e.area;
  64062. });
  64063. outHoles = outHoles.map(e => e.points);
  64064. } else {
  64065. outHoles = holes.map(e => e.points);
  64066. outHoles.forEach(e => holesArea += Math.abs(math.getArea(e)));
  64067. }
  64068. return holesArea;
  64069. }
  64070. getArea(ifRidOfHoles) {
  64071. //面积
  64072. //不排除hole
  64073. return Math.abs(math.getArea(this.points)) - (ifRidOfHoles ? this.getHolesArea() : 0);
  64074. }
  64075. getVolume(ifRidOfHoles) {
  64076. //体积
  64077. var {
  64078. zMin,
  64079. zMax
  64080. } = this.getRealZ();
  64081. var height = zMax - zMin;
  64082. if (isNaN(height)) height = 0;
  64083. return this.getArea(ifRidOfHoles) * height;
  64084. }
  64085. getRealZ() {
  64086. //求真实高度时用到的
  64087. var zMin, zMax;
  64088. if (this.buildType == 'building') {
  64089. //因为building只有一个地基平面 所以自身的zMin == 自身的zMax 所以要算
  64090. var top = this.buildChildren[this.buildChildren.length - 1];
  64091. var btm = this.buildChildren[0];
  64092. zMin = btm ? btm.zMin : 0; //建好的建筑不加楼的话是0。
  64093. zMax = top ? top.zMax : 0;
  64094. } else if (this.buildType == 'hole') {
  64095. return this.buildParent.getRealZ();
  64096. } else {
  64097. zMin = this.zMin, zMax = this.zMax;
  64098. }
  64099. return {
  64100. zMin,
  64101. zMax
  64102. };
  64103. }
  64104. //架站式多楼层SG-t-ihjV2cDVFlE 有初始的z, 但是总高度范围小于数据集。 不允许修改高度。
  64105. /* getDrawZ(){ //画线和box时用到的z
  64106. let zMin , zMax
  64107. if(this.buildType == 'hole'){
  64108. if(this.buildParent.buildType == 'building' && atFloor){
  64109. zMin = atFloor.zMin, zMax = atFloor.zMax
  64110. }else{
  64111. zMin = this.buildParent.zMin, zMax = this.buildParent.zMax
  64112. }
  64113. }else{
  64114. zMin = this.zMin, zMax = this.zMax
  64115. }
  64116. return {zMin, zMax}
  64117. } */
  64118. getBound() {
  64119. var bound = new Box3();
  64120. var {
  64121. zMin,
  64122. zMax
  64123. } = this.getRealZ();
  64124. var points = this.buildType == 'floor' ? this.buildParent.points : this.points;
  64125. points.forEach(p => {
  64126. bound.expandByPoint(p.clone().setZ(zMin));
  64127. bound.expandByPoint(p.clone().setZ(zMax));
  64128. });
  64129. return bound;
  64130. }
  64131. getMarkerMaterial(type) {
  64132. if (!markerMats$2) {
  64133. markerMats$2 = {
  64134. default: new MeshBasicMaterial({
  64135. transparent: !0,
  64136. color: color$2,
  64137. opacity: 0.8,
  64138. map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'),
  64139. depthTest: false
  64140. }),
  64141. midPrepare: new MeshBasicMaterial({
  64142. //线中心的半透明点
  64143. transparent: !0,
  64144. color: color$2,
  64145. opacity: 0.4,
  64146. map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'),
  64147. depthTest: false
  64148. }),
  64149. hover: new MeshBasicMaterial({
  64150. transparent: !0,
  64151. color: color$2,
  64152. opacity: 1,
  64153. map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'),
  64154. depthTest: false
  64155. }),
  64156. select: new MeshBasicMaterial({
  64157. transparent: !0,
  64158. color: new Color('#00C8AF'),
  64159. opacity: 1,
  64160. map: texLoader$9.load(Potree.resourcePath + '/textures/whiteCircle.png'),
  64161. depthTest: false
  64162. })
  64163. };
  64164. }
  64165. return markerMats$2[type];
  64166. }
  64167. setMarkerSelected(marker, state, hoverObject) {
  64168. //console.warn(marker.id , state, hoverObject)
  64169. if (state == 'select') {
  64170. marker.selected = true;
  64171. marker.material = this.getMarkerMaterial('select');
  64172. } else if (state == 'unselect') {
  64173. marker.selected = false;
  64174. marker.material = this.getMarkerMaterial('default');
  64175. } else {
  64176. if (marker.selected) return; //选中时不允许修改为除了'unselect'以外的状态
  64177. if (state == 'hover') {
  64178. marker.material = this.getMarkerMaterial('hover');
  64179. } else if (state == 'unhover') {
  64180. if (marker.name.includes('mid')) {
  64181. marker.material = this.getMarkerMaterial('midPrepare');
  64182. } else {
  64183. marker.material = this.getMarkerMaterial('default');
  64184. }
  64185. }
  64186. }
  64187. }
  64188. select() {
  64189. //最多再显示一层子级的线,如building不会显示room中的hole的线
  64190. //box是一直显示的,但会切换材质
  64191. /*
  64192. 选中 box 线
  64193. building 自己(底盘)选中 自己, floor不带hole
  64194. floor 自己选中 自己, room不带hole
  64195. room 自己选中 自己
  64196. */ //注:自己的就代表定包括hole,如果有parentHoles的也(building上的hole的对应)
  64197. //console.log('select '+this.name, this.selected)
  64198. if (this.selected) return;
  64199. if (this.box) {
  64200. this.box.material = this.mats.boxSelected;
  64201. }
  64202. if (this.buildType == 'building' || this.buildType == 'floor') {
  64203. this.buildChildren.forEach(e => {
  64204. e.lineMesh.visible = true;
  64205. });
  64206. if (this.buildType == 'floor') {
  64207. Potree.Utils.setObjectLayers(this.box, 'bothMapAndScene');
  64208. Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi'); //当选中floor或room时,building在地图不可见
  64209. }
  64210. } else if (this.buildType == 'room') {
  64211. Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene');
  64212. Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'siteModelMapUnvisi');
  64213. }
  64214. this.lineMesh.visible = true;
  64215. this.markers && this.markers.forEach(e => Potree.Utils.updateVisible(e, 'select', true));
  64216. this.midMarkers && this.midMarkers.forEach(e => Potree.Utils.updateVisible(e, 'select', true));
  64217. var holes = this.holes.concat(this.parentHoles);
  64218. holes.forEach(e => e.select());
  64219. this.selected = true;
  64220. this.dispatchEvent({
  64221. type: 'select'
  64222. });
  64223. }
  64224. unselect() {
  64225. if (!this.selected) return;
  64226. //console.log('unselect '+this.name )
  64227. if (this.box) {
  64228. this.box.material = this.mats.boxDefault;
  64229. }
  64230. if (this.buildType == 'building' || this.buildType == 'floor') {
  64231. this.buildChildren.forEach(e => {
  64232. //(这里要保证选中前要先取消选中,否则如选中房间后取消了楼层,房间线就隐藏了)
  64233. e.lineMesh.visible = false;
  64234. });
  64235. if (this.buildType == 'floor') {
  64236. Potree.Utils.setObjectLayers(this.box, 'siteModelMapUnvisi');
  64237. Potree.Utils.setObjectLayers(this.buildParent.box, 'bothMapAndScene');
  64238. }
  64239. } else if (this.buildType == 'room') {
  64240. Potree.Utils.setObjectLayers(this.buildParent.box, 'siteModelMapUnvisi');
  64241. Potree.Utils.setObjectLayers(this.buildParent.buildParent.box, 'bothMapAndScene');
  64242. }
  64243. this.lineMesh.visible = false;
  64244. this.markers && this.markers.forEach(e => Potree.Utils.updateVisible(e, 'select', false));
  64245. this.midMarkers && this.midMarkers.forEach(e => Potree.Utils.updateVisible(e, 'select', false));
  64246. var holes = this.holes.concat(this.parentHoles);
  64247. holes.forEach(e => e.unselect());
  64248. this.selected = false;
  64249. this.dispatchEvent({
  64250. type: 'unselect'
  64251. });
  64252. }
  64253. ifContainsPoint(position) {
  64254. //看它所定义的空间是否包含某个坐标(要排除hole)
  64255. var {
  64256. zMin,
  64257. zMax
  64258. } = this.getRealZ();
  64259. if (position.z < zMin || position.z > zMax) return;
  64260. var holes = this.holes.concat(this.parentHoles);
  64261. var holesPoints = holes.filter(e => e != this && e.points.length > 2).map(e => e.points);
  64262. var inShape = math.isPointInArea(this.points, holesPoints, position);
  64263. return !!inShape;
  64264. }
  64265. }
  64266. class MetricUVGenerator {
  64267. constructor() {
  64268. this.a = new Vector3(), this.b = new Vector3(), this.c = new Vector3(), this.d = new Vector3();
  64269. }
  64270. generateTopUV(t, e, n, r, o) {
  64271. return [new Vector2(e[3 * n], e[3 * n + 1]), new Vector2(e[3 * r], e[3 * r + 1]), new Vector2(e[3 * o], e[3 * o + 1])];
  64272. }
  64273. generateSideWallUV(t, e, n, r, o, a) {
  64274. var s = e;
  64275. this.a.set(s[3 * n], s[3 * n + 1], s[3 * n + 2]), this.b.set(s[3 * r], s[3 * r + 1], s[3 * r + 2]), this.c.set(s[3 * o], s[3 * o + 1], s[3 * o + 2]), this.d.set(s[3 * a], s[3 * a + 1], s[3 * a + 2]);
  64276. var c = this.a.x !== this.b.x,
  64277. l = c ? this.b : this.d,
  64278. u = this.a.distanceTo(l),
  64279. d = l.distanceTo(this.c);
  64280. return [new Vector2(this.a.x, 0), c ? new Vector2(this.a.x + u, 0) : new Vector2(this.a.x, d), new Vector2(this.a.x + u, d), c ? new Vector2(this.a.x, d) : new Vector2(this.a.x + u, 0)];
  64281. }
  64282. }
  64283. var minFloorHeight = 0.5;
  64284. var ifDrawDatasetBound = true; //显示一下数据集的tightBound线框
  64285. var minMarkers = 3;
  64286. var Limit = {
  64287. zMin: -config$1.map.cameraHeight,
  64288. zMax: config$1.map.cameraHeight
  64289. }; //不能超过camera的高度,为了对称所以也限制了最低
  64290. var SiteModel = {
  64291. bus: new EventDispatcher(),
  64292. entities: [],
  64293. //所有实体
  64294. buildings: [],
  64295. //所有建筑父集
  64296. meshGroup: new Object3D(),
  64297. inEntity: null,
  64298. lastPos: new Vector3(Infinity, Infinity, Infinity),
  64299. init: function init() {
  64300. viewer.scene.scene.add(this.meshGroup);
  64301. this.meshGroup.name = 'siteModel';
  64302. this.SplitScreen = SplitScreen4Views;
  64303. if (Potree.settings.editType == 'pano') {
  64304. return;
  64305. }
  64306. this.createHeightPull();
  64307. this.history = new History({
  64308. applyData: data => {
  64309. if (data.entity.parent && data.entity.selected) {
  64310. data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用
  64311. data.entity.reDraw();
  64312. data.entity.initData(data);
  64313. data.isNew || data.entity.addMidMarkers();
  64314. data.entity.isNew = data.isNew;
  64315. data.entity.dispatchEvent('changeByHistory');
  64316. return true;
  64317. }
  64318. },
  64319. getData: entity => {
  64320. //if(entity.isNew)return
  64321. return {
  64322. entity,
  64323. points: entity.points.map(e => e.clone()),
  64324. ifDraw: true,
  64325. isNew: entity.isNew
  64326. };
  64327. }
  64328. });
  64329. if (Potree.settings.isTest && ifDrawDatasetBound) {
  64330. viewer.addEventListener('allLoaded', () => {
  64331. viewer.scene.pointclouds.forEach(pointcloud => {
  64332. var boxPoints = pointcloud.getUnrotBoundPoint();
  64333. var boundingBox = new BuildingBox({
  64334. name: '数据集tightBound_' + pointcloud.dataset_id,
  64335. points: boxPoints,
  64336. buildType: 'dataset',
  64337. zMax: pointcloud.bound.max.z,
  64338. zMin: pointcloud.bound.min.z,
  64339. ifDraw: true
  64340. });
  64341. this.meshGroup.add(boundingBox);
  64342. //boundingBox.markers.forEach(e=>e.visible = false)
  64343. });
  64344. });
  64345. }
  64346. if (Potree.settings.isOfficial) {
  64347. viewer.addEventListener('camera_changed', e => {
  64348. if (e.changeInfo && e.changeInfo.positionChanged) {
  64349. this.updateEntityAt();
  64350. }
  64351. });
  64352. }
  64353. {
  64354. var pressDelete = e => {
  64355. if (e.keyCode == KeyCodes.BACKSPACE || e.keyCode == KeyCodes.DELETE) {
  64356. if (this.selectedMarker) {
  64357. var entity = this.selectedMarker.parent;
  64358. var index = entity.markers.indexOf(this.selectedMarker);
  64359. entity.removeMarker(index);
  64360. if (entity.points.length < 2) {
  64361. //删到只剩一个点时重新画(如果是hole的点,直接删除hole吧?)
  64362. this.startInsertion('resume', entity);
  64363. }
  64364. }
  64365. }
  64366. };
  64367. viewer.inputHandler.addEventListener('keydown', pressDelete);
  64368. }
  64369. {
  64370. var updated = false;
  64371. this.bus.addEventListener('updated', () => {
  64372. Common.intervalTool.isWaiting('siteModelUpdated', () => {
  64373. this.changedCallback();
  64374. }, 500);
  64375. });
  64376. }
  64377. },
  64378. changedCallback() {
  64379. this.findPanos();
  64380. this.findEntityForDataset();
  64381. this.updateEntityAt(true); //更新所在建筑,更新marker显示
  64382. //console.log('changedCallback')
  64383. },
  64384. updateEntityAt(force) {
  64385. var {
  64386. measure
  64387. } = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  64388. //if(!this.entities.length || this.editing) return //编辑时也要根据位置显示不同楼层的漫游点与cad
  64389. var fun = () => {
  64390. //延时update,防止卡顿
  64391. var currPos = viewer.mainViewport.view.position;
  64392. if (this.pauseUpdateEntity) return; // console.error('pauseUpdateEntity')
  64393. //if(force || !currPos.equals(this.lastPos) ){
  64394. //console.log('currPos ', currPos.toArray())
  64395. this.lastPos.copy(currPos);
  64396. var entity;
  64397. if (measure) {
  64398. //因为测量线的点可能在多个房间,所以干脆直接找在哪个楼层
  64399. var list = [];
  64400. measure.points.forEach(e => {
  64401. var entity = this.pointInWhichEntity(e, 'floor'); //每个点都找到其所在楼层
  64402. var item = list.find(e => e.entity == entity);
  64403. if (item) {
  64404. item.count++;
  64405. } else {
  64406. list.push({
  64407. entity,
  64408. count: 1
  64409. });
  64410. }
  64411. });
  64412. list.sort((a, b) => {
  64413. return b.count - a.count;
  64414. }); //找出出现次数最多的楼层
  64415. if (list[0]) {
  64416. entity = list[0].entity;
  64417. }
  64418. } else {
  64419. var searchPos = Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : currPos;
  64420. entity = this.pointInWhichEntity(searchPos, 'room');
  64421. }
  64422. if (force || this.inEntity != entity) {
  64423. var oldEntity = this.inEntity;
  64424. this.inEntity = entity;
  64425. //console.log('buildingChange', entity)
  64426. this.bus.dispatchEvent({
  64427. type: 'buildingChange',
  64428. entity
  64429. });
  64430. //this.updatePanosVisible(oldEntity, this.inEntity)
  64431. var lastFloor = this.currentFloor; //oldEntity ? oldEntity.buildType == 'floor' ? oldEntity : oldEntity.buildType == 'room' ? oldEntity.buildParent : null : null; //基本只会是floor或room
  64432. var currentFloor = entity ? entity.buildType == 'floor' ? entity : entity.buildType == 'room' ? entity.buildParent : null : null; //基本只会是floor或room
  64433. if (force || currentFloor != lastFloor) {
  64434. //console.log('改变了floor',lastFloor,currentFloor)
  64435. this.currentFloor = currentFloor;
  64436. this.bus.dispatchEvent({
  64437. type: 'FloorChange',
  64438. currentFloor
  64439. });
  64440. }
  64441. }
  64442. force = false;
  64443. //}
  64444. };
  64445. if (force) fun();else Common.intervalTool.isWaiting('sitemodelCameraInterval', fun, 500);
  64446. },
  64447. enter: function enter() {
  64448. Potree.Log('sitemodel enter');
  64449. this.clear(); //确保全部清空
  64450. this.editing = true;
  64451. //this.updatePanosVisible(null, null, true)//show all
  64452. viewer.updateFpVisiDatasets();
  64453. var mapViewport = viewer.mapViewer.viewports[0];
  64454. this.SplitScreen.split({
  64455. siteModel: true /* , viewports:[{name:'Top',viewport : mapViewport }] */
  64456. });
  64457. viewer.viewports.forEach(e => {
  64458. if (e.name != 'mapViewport') {
  64459. e.layersAdd('siteModelMapUnvisi');
  64460. }
  64461. if (e.name == 'right' || e.name == 'back') {
  64462. e.layersAdd('siteModeSideVisi');
  64463. }
  64464. });
  64465. viewer.images360.panos.forEach(pano => {
  64466. Potree.Utils.setObjectLayers(pano.marker, 'siteModelMapUnvisi');
  64467. //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene')
  64468. });
  64469. mapViewport.layersAdd('siteModeOnlyMapVisi'); //只有mapViewport能看到marker
  64470. },
  64471. leave: function leave() {
  64472. Potree.Log('sitemodel leave');
  64473. var mapViewport = viewer.mapViewer.viewports[0];
  64474. this.SplitScreen.recover();
  64475. viewer.viewports.forEach(e => {
  64476. if (e.name != 'mapViewport') {
  64477. e.layersRemove('siteModelMapUnvisi');
  64478. }
  64479. if (e.name == 'right' || e.name == 'back') {
  64480. e.layersRemove('siteModeSideVisi');
  64481. }
  64482. });
  64483. viewer.images360.panos.forEach(pano => {
  64484. Potree.Utils.setObjectLayers(pano.marker, 'sceneObjects');
  64485. //Potree.Utils.setObjectLayers(pano.label2, 'bothMapAndScene')
  64486. });
  64487. mapViewport.layersRemove('siteModeOnlyMapVisi');
  64488. this.clear();
  64489. this.editing = false;
  64490. this.updateEntityAt(true);
  64491. viewer.updateFpVisiDatasets();
  64492. },
  64493. addFloor: function addFloor(parent, dirType, sid, name) {
  64494. //dirType:'top'|'bottom'在上方建还是下方。如果建筑中没有楼层,默认在基底建一个
  64495. var buildType = 'floor';
  64496. var zMin, zMax;
  64497. if (parent.buildChildren.length == 0) {
  64498. zMin = parent.zMin;
  64499. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  64500. } else {
  64501. if (dirType == 'bottom') {
  64502. //var btm = Common.find(parent.buildChildren,null,[e=>e.zMin])
  64503. var btm = parent.buildChildren[0];
  64504. zMax = btm.zMin;
  64505. zMin = zMax - Potree.config.siteModel.floorHeightDefault;
  64506. } else {
  64507. //var top = Common.find(parent.buildChildren,null,[e=>e.zMax])
  64508. var top = parent.buildChildren[parent.buildChildren.length - 1];
  64509. zMin = top.zMax;
  64510. zMax = zMin + Potree.config.siteModel.floorHeightDefault;
  64511. }
  64512. }
  64513. var prop = {
  64514. buildType,
  64515. //name : Potree.config.siteModel.names[buildType],
  64516. zMin,
  64517. zMax,
  64518. buildParent: parent,
  64519. sid,
  64520. name,
  64521. ifDraw: true
  64522. };
  64523. var floor = new BuildingBox(prop);
  64524. /* parent.buildChildren.push(floor)
  64525. this.meshGroup.add(floor);
  64526. this.entities.push(floor) */
  64527. floor.update();
  64528. this.addEntity(floor, parent);
  64529. //this.selectEntity(floor)
  64530. if (this.selected == parent) {
  64531. //重新选择下,为了显示新楼层线框
  64532. parent.unselect();
  64533. parent.select();
  64534. }
  64535. this.bus.dispatchEvent('updated');
  64536. return floor;
  64537. },
  64538. startInsertion: function startInsertion(buildType, parent, sid, name, callback, cancelFun) {
  64539. var _this = this;
  64540. var zMin, zMax, entity, resume;
  64541. var mapViewport = viewer.mapViewer.viewports[0];
  64542. if (buildType == 'resume') {
  64543. //继续画(使用最后一个点或者新加的点)
  64544. resume = true;
  64545. entity = parent;
  64546. buildType = parent.buildType;
  64547. //删除原先所有的点,因为它们已经添加了事件,会很麻烦:
  64548. entity.reDraw(0);
  64549. entity.isNew = true; //当作新的来画
  64550. }
  64551. if (!resume) {
  64552. if (buildType == 'hole' || buildType == 'room') {
  64553. zMin = parent.zMin;
  64554. zMax = parent.zMax;
  64555. } else if (buildType == 'building') {
  64556. parent = null;
  64557. zMin = viewer.bound.boundingBox.min.z;
  64558. zMax = viewer.bound.boundingBox.min.z;
  64559. }
  64560. if (buildType == 'hole') {
  64561. entity = parent.addHole();
  64562. entity.isNew = true;
  64563. this.selectEntity(parent);
  64564. entity.select();
  64565. console.log('挖洞 ', entity.uuid);
  64566. } else {
  64567. var prop = {
  64568. buildType,
  64569. //name : Potree.config.siteModel.names[buildType],//'building',
  64570. zMin,
  64571. zMax,
  64572. buildParent: parent,
  64573. sid,
  64574. name,
  64575. ifDraw: true
  64576. };
  64577. entity = new BuildingBox(prop);
  64578. entity.isNew = true;
  64579. this.selectEntity(entity);
  64580. }
  64581. this.addEntity(entity, parent);
  64582. }
  64583. var timer;
  64584. var endDragFun = e => {
  64585. if (e.button == MOUSE.LEFT) {
  64586. this.history.beforeChange(entity);
  64587. var marker = entity.addMarker({
  64588. point: entity.points[entity.points.length - 1].clone()
  64589. });
  64590. this.history.afterChange(entity);
  64591. //entity.editStateChange(true) //重新激活reticule状态
  64592. entity.continueDrag(marker, e);
  64593. } else if (e.button === MOUSE.RIGHT) {
  64594. if (e.pressDistance < Potree.config.clickMaxDragDis) end(e); //非拖拽的话
  64595. else entity.continueDrag(null, e /* .drag.object */);
  64596. }
  64597. };
  64598. var finish = () => {
  64599. //结束绘画
  64600. viewer.removeEventListener('cancel_insertions', Exit);
  64601. entity.removeEventListener('unselect', Exit);
  64602. clearTimeout(timer);
  64603. entity.editStateChange(false);
  64604. //pressExit && viewer.inputHandler.removeEventListener('keydown', pressExit);
  64605. callback && callback(entity);
  64606. viewer.dispatchEvent('endBuildEntity');
  64607. };
  64608. var end = function end() {
  64609. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  64610. //尝试结束
  64611. /* 退出的三种形式:
  64612. 1 普通:如果大于三个marker,结束且保留;否则重新画。()
  64613. 2 删除:直接结束且删除。(remove)
  64614. 3 结束:如果大于三个marker,结束且保留;否则结束且删除。 (finish)
  64615. 4 保留:无论几个marker,都保留着,结束。(remain)
  64616. */
  64617. if (e.remove) {
  64618. finish();
  64619. return _this.removeEntity(entity);
  64620. }
  64621. if (!e.remain && !e.finish && !e.remove && entity.markers.length <= minMarkers) {
  64622. //右键 当个数不够时取消
  64623. //重新开始画
  64624. entity.reDraw(1);
  64625. Potree.Utils.updateVisible(entity.markers[0], 'unMove', false);
  64626. var f = () => {
  64627. Potree.Utils.updateVisible(entity.markers[0], 'unMove', true);
  64628. entity.removeEventListener('dragChange', f);
  64629. };
  64630. entity.addEventListener('dragChange', f);
  64631. //console.log('waitcontinue')
  64632. entity.continueDrag(entity.markers[0], e);
  64633. return;
  64634. }
  64635. finish();
  64636. if (e.remain || !e.remove && entity.markers.length > 3) {
  64637. //保留
  64638. entity.removeMarker(entity.points.length - 1);
  64639. entity.markers.forEach(marker => {
  64640. marker.dispatchEvent('addHoverEvent');
  64641. });
  64642. if (buildType == 'room') {
  64643. _this.fitPullBox();
  64644. }
  64645. entity.isNew = false;
  64646. entity.addMidMarkers();
  64647. var boundingBox = entity.getBound();
  64648. var center = boundingBox.getCenter(new Vector3());
  64649. viewer.controls.setTarget(center, 2);
  64650. } else {
  64651. _this.removeEntity(entity); //直接删除没画好的,比较简单。这样就不用担心旧的continueDrag仍旧触发了
  64652. }
  64653. return entity;
  64654. };
  64655. var Exit = e => {
  64656. //强制结束
  64657. entity.removeEventListener('unselect', Exit);
  64658. if (viewer.inputHandler.drag) {
  64659. //还未触发drop的话
  64660. viewer.inputHandler.drag.object.dispatchEvent({
  64661. type: 'drop',
  64662. drag: viewer.inputHandler.drag,
  64663. viewer: viewer,
  64664. pressDistance: 0,
  64665. button: MOUSE.RIGHT
  64666. });
  64667. viewer.inputHandler.drag.object.isDragging = false;
  64668. } else {
  64669. end({
  64670. remain: true
  64671. });
  64672. }
  64673. viewer.inputHandler.drag = null;
  64674. };
  64675. viewer.dispatchEvent('cancel_insertions'); //取消之前的
  64676. viewer.addEventListener('cancel_insertions', Exit);
  64677. setTimeout(() => {
  64678. entity.isNew && entity.addEventListener('unselect', Exit);
  64679. }, 1); //因为刚创建会unselect一下所以延迟
  64680. var marker = entity.addMarker({
  64681. point: new Vector3(0, 0, 0)
  64682. });
  64683. Potree.Utils.updateVisible(marker, 'unMove', false); //这时候的位置是假的(0,0,0)所以先不可见
  64684. var f = () => {
  64685. Potree.Utils.updateVisible(marker, 'unMove', true);
  64686. entity.removeEventListener('dragChange', f);
  64687. };
  64688. entity.addEventListener('dragChange', f);
  64689. marker.isDragging = true;
  64690. viewer.inputHandler.startDragging(marker, {
  64691. dragViewport: mapViewport,
  64692. endDragFun,
  64693. notPressMouse: true
  64694. }); //notPressMouse代表不是通过按下鼠标来拖拽. dragViewport指定了只能在地图上拖拽
  64695. viewer.dispatchEvent('startBuildEntity');
  64696. var changeByHistory = e => {
  64697. if (!entity.isNew) return;
  64698. var marker = entity.markers[entity.points.length - 1];
  64699. viewer.inputHandler.startDragging(marker, {
  64700. dragViewport: mapViewport,
  64701. endDragFun,
  64702. notPressMouse: true
  64703. });
  64704. var I = viewer.inputHandler.intersect && (viewer.inputHandler.intersect.orthoIntersect || viewer.inputHandler.intersect.location);
  64705. if (I) {
  64706. entity.dragChange(I.clone(), entity.points.length - 1); //使最后一个点在鼠标处
  64707. }
  64708. };
  64709. entity.addEventListener('changeByHistory', changeByHistory);
  64710. return entity;
  64711. },
  64712. getPreDealData(points, zMin, zMax, initial, buildType, parent) {
  64713. /* if( buildType == 'building' ){
  64714. zMax = zMin //强制变得一样,作为基底。如果有必要,保存时再算真实的zMax。目前zMin没有保存所以数据是错的,会直接根据floor计算
  64715. } */
  64716. var bound = viewer.bound.boundingBox;
  64717. if (buildType == 'building' && initial) {
  64718. //初始数据错的,要自己建(只有一个building和floor) 原posIsLonlat
  64719. console.log('空间模型未编辑过, 初始化了一个');
  64720. points = [new Vector3(bound.min.x, bound.min.y, 0), new Vector3(bound.max.x, bound.min.y, 0), new Vector3(bound.max.x, bound.max.y, 0), new Vector3(bound.min.x, bound.max.y, 0)];
  64721. zMin = bound.min.z;
  64722. zMax = bound.max.z;
  64723. /* points = points.map(e=>{
  64724. return viewer.transform.lonlatToLocal.forward(e)
  64725. }) */
  64726. } else {
  64727. //相对于初始数据集的模型内坐标
  64728. points = points.map(e => this.transform(e, 'fromDataset'));
  64729. if (buildType == 'floor' && initial) {
  64730. zMin = bound.min.z;
  64731. zMax = bound.max.z;
  64732. }
  64733. }
  64734. return {
  64735. points,
  64736. zMax,
  64737. zMin
  64738. };
  64739. },
  64740. resetFromData: function resetFromData(entity) {
  64741. var _this2 = this;
  64742. var points = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
  64743. var holes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  64744. var zMin = arguments.length > 3 ? arguments[3] : undefined;
  64745. var zMax = arguments.length > 4 ? arguments[4] : undefined;
  64746. return function (points, zMin, zMax) {
  64747. var {
  64748. points,
  64749. zMax,
  64750. zMin
  64751. } = _this2.getPreDealData(points, zMin, zMax, _this2.autoBuild, entity.buildType, entity.buildParent);
  64752. if (entity.buildType != 'floor') entity.points = points;
  64753. if (entity.buildType == 'room') {
  64754. entity.zMin = zMin;
  64755. entity.zMax = zMax;
  64756. } else if (entity.buildType == 'floor') {
  64757. //改楼高
  64758. var height = zMax - zMin;
  64759. var zMax2 = entity.zMin + height;
  64760. SiteModel.changeZ(entity, 'zMax', zMax2);
  64761. }
  64762. {
  64763. //删除旧的holes重新添加
  64764. var holesOld = entity.holes;
  64765. holesOld.forEach(e => {
  64766. entity.removeHole(e);
  64767. });
  64768. holes.forEach(points => {
  64769. var ps = points.map(e => _this2.transform(e, 'fromDataset'));
  64770. var hole = entity.addHole(ps);
  64771. hole.addMidMarkers();
  64772. });
  64773. }
  64774. entity.update();
  64775. return entity;
  64776. }(points, zMin, zMax);
  64777. },
  64778. createFromData: function createFromData(buildType, parent, sid, name) {
  64779. var _this3 = this;
  64780. var points = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];
  64781. var holes = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : [];
  64782. var zMin = arguments.length > 6 ? arguments[6] : undefined;
  64783. var zMax = arguments.length > 7 ? arguments[7] : undefined;
  64784. var initial = arguments.length > 8 ? arguments[8] : undefined;
  64785. var panos_ = arguments.length > 9 ? arguments[9] : undefined;
  64786. var flagPano = arguments.length > 10 ? arguments[10] : undefined;
  64787. return function (points, zMin, zMax) {
  64788. if (buildType != 'building' && buildType != 'floor' && buildType != 'room') return;
  64789. var {
  64790. points,
  64791. zMax,
  64792. zMin
  64793. } = _this3.getPreDealData(points, zMin, zMax, initial, buildType, parent);
  64794. var panos = [];
  64795. {
  64796. if (panos_) {
  64797. panos_.forEach(sid => {
  64798. var pano = viewer.images360.getPano(sid, 'sid');
  64799. if (pano) panos.push(pano);
  64800. });
  64801. }
  64802. flagPano = flagPano != void 0 ? viewer.images360.getPano(flagPano, 'sid') : null; //最中心的pano 或者 最靠近该实体的pano(当panos为空时)
  64803. if (!_this3.editing && buildType == 'floor' && !flagPano) {
  64804. //没有的话可能是自动添加的floor,直接用parent的吧
  64805. panos = parent.panos;
  64806. flagPano = parent.flagPano;
  64807. }
  64808. }
  64809. var prop = {
  64810. buildType,
  64811. points,
  64812. name,
  64813. sid,
  64814. zMin,
  64815. zMax,
  64816. buildParent: parent,
  64817. ifDraw: _this3.editing || Potree.settings.drawEntityData,
  64818. panos,
  64819. flagPano,
  64820. autoBuild: initial
  64821. };
  64822. var entity = new BuildingBox(prop);
  64823. SiteModel.addEntity(entity, parent);
  64824. if (_this3.editing) {
  64825. if (buildType == 'building' || buildType == 'room') {
  64826. entity.addMidMarkers();
  64827. }
  64828. }
  64829. holes.forEach(points => {
  64830. var ps = points.map(e => _this3.transform(e, 'fromDataset'));
  64831. var hole = entity.addHole(ps);
  64832. _this3.editing && hole.addMidMarkers();
  64833. });
  64834. /* if(buildType == 'floor'){
  64835. this.updateBuildingZ(parent)
  64836. } */
  64837. return entity;
  64838. }(points, zMin, zMax);
  64839. },
  64840. transform: function transform(pos, type) {
  64841. if (Potree.settings.editType == 'pano') {
  64842. // 模型不经转换
  64843. return new Vector3().copy(pos).setZ(0);
  64844. }
  64845. if (type == 'toDataset') {
  64846. var point = Potree.Utils.datasetPosTransform({
  64847. toDataset: true,
  64848. position: pos.clone(),
  64849. datasetId: Potree.settings.originDatasetId
  64850. });
  64851. return new Vector2().copy(point);
  64852. } else {
  64853. var position = new Vector3().copy(pos).setZ(0);
  64854. return Potree.Utils.datasetPosTransform({
  64855. fromDataset: true,
  64856. position,
  64857. datasetId: Potree.settings.originDatasetId
  64858. });
  64859. }
  64860. },
  64861. addEntity: function addEntity(entity, parent) {
  64862. if (entity.buildType != 'hole') {
  64863. this.meshGroup.add(entity);
  64864. this.entities.push(entity);
  64865. if (entity.buildType == 'building') {
  64866. this.buildings.push(entity);
  64867. } else {
  64868. parent.buildChildren.push(entity);
  64869. }
  64870. }
  64871. if (entity.buildType == 'room') {
  64872. entity.addEventListener('marker_dropped', () => {
  64873. this.fitPullBox();
  64874. });
  64875. } else if (entity.buildType == 'floor') {
  64876. this.updateBuildingZ(parent);
  64877. parent.dispatchEvent({
  64878. type: 'addFloor'
  64879. });
  64880. }
  64881. {
  64882. //仅能存在一个marker被选中。选中的点可以被删除
  64883. entity.addEventListener('clickMarker', e => {
  64884. if (this.selectedMarker == e.marker) {
  64885. this.selectedMarker.dispatchEvent({
  64886. type: 'clickSelect',
  64887. state: false
  64888. });
  64889. this.selectedMarker = null;
  64890. } else {
  64891. if (this.selectedMarker) {
  64892. this.selectedMarker.dispatchEvent({
  64893. type: 'clickSelect',
  64894. state: false
  64895. });
  64896. }
  64897. this.selectedMarker = e.marker;
  64898. this.selectedMarker.dispatchEvent({
  64899. type: 'clickSelect',
  64900. state: true
  64901. });
  64902. }
  64903. });
  64904. entity.addEventListener('removeMarker', e => {
  64905. if (this.selectedMarker == e.marker) {
  64906. this.selectedMarker = null;
  64907. }
  64908. });
  64909. var unselect = e => {
  64910. //取消选中实体或删除后
  64911. if (this.selectedMarker && entity.markers.includes(this.selectedMarker)) {
  64912. this.selectedMarker.dispatchEvent({
  64913. type: 'clickSelect',
  64914. state: false
  64915. });
  64916. this.selectedMarker = null;
  64917. }
  64918. };
  64919. entity.addEventListener('dispose', unselect);
  64920. entity.addEventListener('unselect', unselect);
  64921. }
  64922. //console.log('添加实体:', entity.buildType, entity.sid, entity.uuid)
  64923. this.bus.dispatchEvent('updated');
  64924. entity.addEventListener('startDragging', () => {
  64925. this.history.beforeChange(entity);
  64926. });
  64927. entity.addEventListener('marker_dropped', () => {
  64928. this.bus.dispatchEvent('updated');
  64929. this.history.afterChange(entity);
  64930. });
  64931. },
  64932. removeEntity: function removeEntity(entity) {
  64933. if (!this.entities.includes(entity)) return;
  64934. console.log('删除实体:', entity.buildType, entity.sid);
  64935. if (this.selected == entity) {
  64936. this.height_pull_box && (this.height_pull_box.visible = false);
  64937. this.selectEntity(null);
  64938. }
  64939. if (entity.buildType == 'building') {
  64940. var index = this.buildings.indexOf(entity);
  64941. if (index > -1) {
  64942. this.buildings.splice(index, 1);
  64943. }
  64944. } else {
  64945. var index = entity.buildParent.buildChildren.indexOf(entity);
  64946. if (index > -1) {
  64947. entity.buildParent.buildChildren.splice(index, 1);
  64948. if (entity.buildType == 'floor' && index == 0) {
  64949. this.updateBuildingZ(entity.buildParent);
  64950. }
  64951. }
  64952. }
  64953. var index = this.entities.indexOf(entity);
  64954. if (index > -1) {
  64955. this.entities.splice(index, 1);
  64956. }
  64957. entity.dispose();
  64958. var buildChildren = entity.buildChildren.slice();
  64959. buildChildren.forEach(e => this.removeEntity(e));
  64960. this.bus.dispatchEvent('updated');
  64961. },
  64962. updateBuildingZ: function updateBuildingZ(building) {
  64963. building.buildChildren = building.buildChildren.sort((e, a) => e.zMin - a.zMin); //从低到高排序
  64964. building.buildChildren[0] && (building.zMin = building.zMax = building.buildChildren[0].zMin); //基底高度
  64965. //building.zMax = building.buildChildren[building.buildChildren.length-1].zMax
  64966. if (this.editing) building.update({
  64967. dontUpdateChildren: true
  64968. });
  64969. building.dispatchEvent('updateBuildingZ');
  64970. },
  64971. selectEntity: function selectEntity(entity) {
  64972. var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  64973. viewer.dispatchEvent('content_changed');
  64974. if (state === false) {
  64975. entity.unselect();
  64976. if (this.selected == entity) this.selected = null;
  64977. viewer.controls.setTarget(null, 2);
  64978. return;
  64979. }
  64980. if (this.selected == entity || entity && entity.buildType == 'hole') return;
  64981. //this.buildings.forEach(e=>e.unselect())
  64982. this.selected && this.selected.unselect();
  64983. this.height_pull_box && (this.height_pull_box.visible = false);
  64984. if (entity) {
  64985. entity.select();
  64986. if (!entity.isNew) {
  64987. var boundingBox = entity.getBound();
  64988. var center = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  64989. viewer.controls.setTarget(center, 2);
  64990. }
  64991. } else {
  64992. viewer.controls.setTarget(null, 2);
  64993. }
  64994. this.selected = entity;
  64995. if (entity && !entity.dontDragFloorHeight && (entity.buildType == 'floor' || entity.buildType == 'room')) {
  64996. this.height_pull_box && (this.height_pull_box.visible = true);
  64997. this.fitPullBox();
  64998. }
  64999. if (entity && !entity.isNew && (entity.buildType == 'building' || entity.buildType == 'room') && entity.points.length < 2) {
  65000. this.startInsertion('resume', entity); //继续画
  65001. }
  65002. },
  65003. fitPullBox: function fitPullBox() {
  65004. //自适应拖拽楼层的pullMesh
  65005. if (!this.height_pull_box || !this.selected || this.selected.buildType != 'floor' && this.selected.buildType != 'room') return;
  65006. var bound = new Box3();
  65007. bound.expandByObject(this.selected.box);
  65008. var center = bound.getCenter(new Vector3());
  65009. var size = bound.getSize(new Vector3());
  65010. this.height_pull_box.scale.copy(size);
  65011. this.height_pull_box.position.copy(center);
  65012. },
  65013. changeZ: function changeZ(entity, dirType, value) {
  65014. // floor or room 修改zMin or zMax
  65015. var max, min; //limit
  65016. if (entity.buildType == 'floor') {
  65017. //楼层
  65018. var index = entity.buildParent.buildChildren.indexOf(entity);
  65019. if (dirType == 'zMax') {
  65020. var upper = entity.buildParent.buildChildren[index + 1];
  65021. entity.zMax = Math.min(Limit.zMax, value);
  65022. min = entity.zMin + minFloorHeight;
  65023. if (entity.zMax < min) {
  65024. entity.zMax = min;
  65025. } else {
  65026. if (upper) {
  65027. max = upper.zMax - minFloorHeight;
  65028. if (entity.zMax > max) {
  65029. entity.zMax = max;
  65030. }
  65031. }
  65032. }
  65033. if (upper) {
  65034. upper.zMin = entity.zMax;
  65035. upper.update();
  65036. upper.dispatchEvent({
  65037. type: 'changeHeight'
  65038. });
  65039. }
  65040. } else {
  65041. var lower = entity.buildParent.buildChildren[index - 1];
  65042. entity.zMin = Math.max(Limit.zMin, value);
  65043. max = entity.zMax - minFloorHeight;
  65044. if (entity.zMin > max) {
  65045. entity.zMin = max;
  65046. } else {
  65047. if (lower) {
  65048. min = lower.zMin + minFloorHeight;
  65049. if (entity.zMin < min) {
  65050. entity.zMin = min;
  65051. }
  65052. }
  65053. }
  65054. if (lower) {
  65055. lower.zMax = entity.zMin;
  65056. lower.update();
  65057. lower.dispatchEvent({
  65058. type: 'changeHeight'
  65059. });
  65060. }
  65061. if (index == 0) this.updateBuildingZ(entity.buildParent);
  65062. }
  65063. } else if (entity.buildType == 'room') {
  65064. //房间
  65065. //按照navvis的是不一定限制在当前楼层,只要高度不超过当前楼层即可。
  65066. var maxHeight = entity.buildParent.zMax - entity.buildParent.zMin;
  65067. if (dirType == 'zMax') {
  65068. min = entity.zMin + minFloorHeight;
  65069. max = entity.zMin + maxHeight;
  65070. entity.zMax = MathUtils.clamp(value, min, max);
  65071. } else {
  65072. min = entity.zMax - maxHeight;
  65073. max = entity.zMax - minFloorHeight;
  65074. entity.zMin = MathUtils.clamp(value, min, max);
  65075. }
  65076. }
  65077. entity.update();
  65078. entity.dispatchEvent({
  65079. type: 'changeHeight'
  65080. });
  65081. //this.selected.emit('update')
  65082. this.fitPullBox();
  65083. this.bus.dispatchEvent('updated');
  65084. },
  65085. createHeightPull: function createHeightPull() {
  65086. //拖拽楼层的bounding box
  65087. var boxGeo = new BoxBufferGeometry(1, 1, 1 / 4);
  65088. var boxMat = new MeshBasicMaterial({
  65089. color: "#F00",
  65090. opacity: 0,
  65091. transparent: true,
  65092. depthTest: false,
  65093. side: 2
  65094. });
  65095. var height_pull_box_up = new Mesh(boxGeo, boxMat);
  65096. var height_pull_box_down = new Mesh(boxGeo, boxMat);
  65097. height_pull_box_up.name = 'height_pull_box_up';
  65098. height_pull_box_down.name = 'height_pull_box_down';
  65099. this.height_pull_box = new Object3D();
  65100. this.height_pull_box.name = 'height_pull_box';
  65101. this.height_pull_box.add(height_pull_box_up);
  65102. this.height_pull_box.add(height_pull_box_down);
  65103. this.height_pull_box.visible = false;
  65104. this.meshGroup.add(this.height_pull_box);
  65105. height_pull_box_up.position.set(0, 0, 1 / 2 /* 3/8 */);
  65106. height_pull_box_down.position.set(0, 0, -1 / 2 /* -3/8 */);
  65107. Potree.Utils.setObjectLayers(this.height_pull_box, 'siteModeSideVisi');
  65108. var mouseover = e => {
  65109. viewer.dispatchEvent({
  65110. type: "CursorChange",
  65111. action: "add",
  65112. name: "siteModelFloorDrag"
  65113. });
  65114. };
  65115. var mouseleave = e => {
  65116. viewer.dispatchEvent({
  65117. type: "CursorChange",
  65118. action: "remove",
  65119. name: "siteModelFloorDrag"
  65120. });
  65121. };
  65122. var firstZ, firstIntersect;
  65123. var drag = e => {
  65124. var intersect = e.intersect.orthoIntersect; //不要点云的intersect,只要orthocamera算出的平面intersect
  65125. if (firstIntersect != void 0) {
  65126. var moveZ = intersect.z - firstIntersect;
  65127. if (this.selected.buildType == 'floor') {
  65128. //楼层
  65129. //限制高度不能超过上下
  65130. if (e.target == height_pull_box_up) {
  65131. if (firstZ == void 0) firstZ = this.selected.zMax;
  65132. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  65133. } else {
  65134. if (firstZ == void 0) firstZ = this.selected.zMin;
  65135. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  65136. }
  65137. } else if (this.selected.buildType == 'room') {
  65138. //房屋
  65139. if (e.target == height_pull_box_up) {
  65140. if (firstZ == void 0) firstZ = this.selected.zMax;
  65141. this.changeZ(this.selected, 'zMax', firstZ + moveZ);
  65142. } else {
  65143. if (firstZ == void 0) firstZ = this.selected.zMin;
  65144. this.changeZ(this.selected, 'zMin', firstZ + moveZ);
  65145. }
  65146. }
  65147. } else {
  65148. firstIntersect = intersect.z;
  65149. }
  65150. };
  65151. var drop = e => {
  65152. firstZ = firstIntersect = null;
  65153. };
  65154. height_pull_box_up.addEventListener('mousemove', mouseover);
  65155. height_pull_box_down.addEventListener('mousemove', mouseover);
  65156. height_pull_box_up.addEventListener('mouseleave', mouseleave);
  65157. height_pull_box_down.addEventListener('mouseleave', mouseleave);
  65158. height_pull_box_up.addEventListener('drag', drag);
  65159. height_pull_box_down.addEventListener('drag', drag);
  65160. height_pull_box_up.addEventListener('drop', drop);
  65161. height_pull_box_down.addEventListener('drop', drop);
  65162. },
  65163. pointInWhichEntity(location, buildType, ifIgnoreHole) {
  65164. //buildType是要找的建筑类型
  65165. //location 可以是pano或者坐标
  65166. //由于房间可能在building外,所以房间要另外单独识别。
  65167. var lastResult; //最接近的上一层结果,如果没有result返回这个
  65168. var result;
  65169. var level = {
  65170. building: 0,
  65171. floor: 1,
  65172. room: 2
  65173. };
  65174. var traverse = (parent, buildType) => {
  65175. //返回第一个符合标准的实体
  65176. var contains;
  65177. if (location instanceof Vector3) {
  65178. contains = parent.ifContainsPoint(location);
  65179. } else {
  65180. //is pano
  65181. contains = parent.panos.includes(location);
  65182. }
  65183. if (contains) {
  65184. if (!lastResult || level[lastResult.buildType] < level[parent.buildType]) lastResult = parent;
  65185. if (parent.buildType == buildType) {
  65186. return parent;
  65187. } else {
  65188. for (var i = 0, len = parent.buildChildren.length; i < len; i++) {
  65189. var result1 = traverse(parent.buildChildren[i]);
  65190. if (result1) return result1;
  65191. }
  65192. }
  65193. }
  65194. };
  65195. //因为建筑可能重叠,所以需要先找到最接近其中心的建筑物
  65196. result = Common.sortByScore(this.buildings, [building => {
  65197. return traverse(building, 'building'); //在building中
  65198. }], [building => {
  65199. //写法类似pointInWhichPointcloud
  65200. var boundingBox = building.getBound();
  65201. var center = boundingBox.getCenter(new Vector3());
  65202. var position = location instanceof Vector3 ? location : location.position;
  65203. var dis = position.distanceTo(center);
  65204. var size = boundingBox.getSize(new Vector3());
  65205. var length = size.length() / 2;
  65206. return length / dis;
  65207. }]);
  65208. var building = result && result[0] && result[0].score > 1 && result[0].item;
  65209. if (buildType == 'building' || !building) return building;
  65210. result = traverse(building, buildType);
  65211. /* if(!result && buildType == 'room'){//如果要找的是room, 且按刚才的顺序找不到的话,就单独从所有rooms中找一遍。因为room可能不在floor和building内。
  65212. let rooms = this.entities.filter(e=>e.buildType == 'room');
  65213. result = rooms.find(e=>e.ifContainsPoint(position))
  65214. }*/
  65215. //虽然房间可以画到上级之外,但是为了方便起见,假定房间绝对在楼层之内。找不到的话要调整空间模型了。
  65216. return result || lastResult;
  65217. },
  65218. findPanos: function findPanos() {
  65219. {
  65220. this.entities.forEach(entity => {
  65221. //清空:
  65222. entity.panos = [];
  65223. entity.flagPano = null;
  65224. viewer.images360.panos.forEach(pano => {
  65225. if (entity.ifContainsPoint(pano.position)) {
  65226. entity.panos.push(pano);
  65227. }
  65228. });
  65229. });
  65230. }
  65231. /* viewer.images360.panos.forEach(pano=>{ //一个漫游点只对应一个实体的话
  65232. let result = this.pointInWhichEntity(pano.position, 'room');
  65233. {//get panos for every entities
  65234. let entity = result
  65235. while(entity){
  65236. entity.panos.push(pano);
  65237. entity = entity.buildParent
  65238. }
  65239. }
  65240. }) */
  65241. {
  65242. //search center pano
  65243. this.entities.forEach(entity => {
  65244. var panos = entity.panos;
  65245. if (panos.length == 0) return;
  65246. var bound = entity.getBound();
  65247. var center = bound.getCenter(new Vector3());
  65248. var request = [];
  65249. var rank = [Images360.scoreFunctions.distanceSquared({
  65250. position: center
  65251. })];
  65252. //let panos = entity.panos && entity.panos.length ? entity.panos : viewer.images360.panos //entity没有panos的话,就扩大到所有panos
  65253. var r = Common.sortByScore(panos, request, rank);
  65254. if (r && r.length) {
  65255. entity.flagPano = r[0].item;
  65256. } else {
  65257. console.error('no flagPano??');
  65258. }
  65259. });
  65260. }
  65261. },
  65262. findEntityForDataset: function findEntityForDataset() {
  65263. //为每一个数据集寻找它所属的最小实体
  65264. /* var entities = this.entities.filter(e=>e.buildType == 'room' || e.buildType == 'floor' && e.buildChildren.length == 0)
  65265. viewer.scene.pointclouds.forEach(pointcloud=>{
  65266. let cloudVolume = pointcloud.getVolume()
  65267. let scores = []
  65268. entities.forEach(entity=>{
  65269. let volume = entity.intersectPointcloudVolume(pointcloud)
  65270. //注:默认已经findPanos过
  65271. let panos = entity.panos.filter(e=>pointcloud.panos.includes(e));
  65272. let panoCount = panos.length
  65273. let score = volume / cloudVolume + panoCount / pointcloud.panos.length
  65274. scores.push({entity, volume, panoCount, score})
  65275. })
  65276. scores.sort((a,b)=>{ return b.score-a.score })
  65277. if(scores.length == 0 || scores[0].volume/cloudVolume < 0.0001 && scores[0].volume < 3 ){//如果约等于0
  65278. pointcloud.belongToEntity = null
  65279. }else{
  65280. pointcloud.belongToEntity = scores[0].entity;
  65281. }
  65282. }) */
  65283. var getScores = (pointcloud, entities, cloudVolume) => {
  65284. var scores = [];
  65285. entities.forEach(entity => {
  65286. var volume = entity.intersectPointcloudVolume(pointcloud);
  65287. //注:默认已经findPanos过
  65288. var panos = entity.panos.filter(e => pointcloud.panos.includes(e));
  65289. var panoCount = panos.length;
  65290. var score = volume / cloudVolume;
  65291. if (pointcloud.panos.length > 0) {
  65292. score += panoCount / pointcloud.panos.length;
  65293. } else {
  65294. //score += 1
  65295. }
  65296. scores.push({
  65297. entity,
  65298. volume,
  65299. panoCount,
  65300. score
  65301. });
  65302. });
  65303. scores.sort((a, b) => {
  65304. return b.score - a.score;
  65305. });
  65306. return scores;
  65307. };
  65308. viewer.scene.pointclouds.forEach(pointcloud => {
  65309. //先判断父级,如果父集不通过就不判断子级。
  65310. var cloudVolume = pointcloud.getVolume();
  65311. var entities = this.buildings;
  65312. while (1) {
  65313. var scores = getScores(pointcloud, entities, cloudVolume);
  65314. if (scores.length == 0 || scores[0].volume / cloudVolume < 0.0001 && scores[0].volume < 3) {
  65315. //如果约等于0
  65316. if (scores[0] && scores[0].entity.buildType == 'room') {
  65317. pointcloud.belongToEntity = scores[0].entity; //当该数据集在楼层中,但不在楼层中的任意一个房间时,任意挂载在其中一个房间上。
  65318. break;
  65319. }
  65320. pointcloud.belongToEntity = null;
  65321. break;
  65322. } else {
  65323. entities = scores[0].entity.buildChildren;
  65324. if (entities.length == 0) {
  65325. pointcloud.belongToEntity = scores[0].entity;
  65326. break;
  65327. }
  65328. }
  65329. }
  65330. });
  65331. /*
  65332. 旧版:
  65333. 只需要考虑 floor 和 room, 因为building的只有一个基底没高度
  65334. floor 和 room 在空间中没有完全的从属关系,因为room可以超出floor之外。所以直接混在一起来查找,但要排除有房间的楼层。
  65335. (现在改为层层递进查找,否则数据集包含entity多的,会直接挂载到体积最大的房间里,即使看起来主体点云并不在该房间)
  65336. 有的数据集虽然很高,但只有近地面的部分才是主体,这部分一般含有全部漫游点。为了防止上层的实体因体积较大而分数高,就把包含漫游点的个数也加入考虑。
  65337. 重叠体积大、且包含漫游点最多的最小实体将会拥有该点云。
  65338. 期望: 最好不挂载到最小子级,因为现在有房间都到房间里了。
  65339. */
  65340. },
  65341. clear: function clear() {
  65342. //清空
  65343. /* entities:[], //所有实体
  65344. buildings:[], //所有建筑父集
  65345. meshGroup: new THREE.Object3D, */
  65346. this.selectEntity(null);
  65347. var length = this.entities.length;
  65348. for (var i = 0; i < length; i++) {
  65349. this.entities[i].dispose();
  65350. }
  65351. this.entities = [];
  65352. this.buildings = [];
  65353. this.inEntity = null;
  65354. },
  65355. gotoEntity(id, isNearBy) {
  65356. var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1000;
  65357. var entity = this.entities.find(e => e.sid == id);
  65358. var aimPano;
  65359. if (!entity) {
  65360. return console.error('没找到entity ');
  65361. }
  65362. if (Potree.settings.displayMode == 'showPanos') {
  65363. if (isNearBy && entity.panos.length) {
  65364. if (entity.panos.includes(viewer.images360.currentPano)) return 'posNoChange'; //已在当前实体中
  65365. var position = viewer.scene.getActiveCamera().position;
  65366. var request = [];
  65367. var rank = [Images360.scoreFunctions.distanceSquared({
  65368. position
  65369. })];
  65370. var r = Common.sortByScore(entity.panos, request, rank);
  65371. aimPano = r[0].item;
  65372. } else {
  65373. if (!entity.flagPano) {
  65374. return console.log('没有flagPano');
  65375. }
  65376. aimPano = entity.flagPano;
  65377. }
  65378. if (aimPano == viewer.images360.currentPano) return 'posNoChange';
  65379. viewer.images360.flyToPano(aimPano);
  65380. } else {
  65381. if (isNearBy && entity.ifContainsPoint(viewer.images360.position)) {
  65382. return 'posNoChange'; //已在当前实体中
  65383. }
  65384. var boundingBox = entity.getBound();
  65385. var _position = boundingBox.getCenter(new Vector3()); //中心点不一定在entity中,比如半环形建筑(所以要不要改成到漫游点呢)
  65386. var size = boundingBox.getSize(new Vector3());
  65387. if (viewer.modules.Clip && viewer.modules.Clip.editing) {
  65388. viewer.modules.Clip.bus.dispatchEvent({
  65389. type: 'flyToPos',
  65390. position: _position
  65391. });
  65392. } else {
  65393. if (math.closeTo(_position, viewer.images360.position)) return 'posNoChange';
  65394. viewer.scene.view.setView({
  65395. position: _position,
  65396. duration
  65397. });
  65398. }
  65399. viewer.mapViewer.moveTo(_position, size, duration);
  65400. }
  65401. return true;
  65402. },
  65403. focusEntity(id) {
  65404. var entity = this.entities.find(e => e.sid == id);
  65405. var boundingBox = entity.getBound();
  65406. //let boundSize = boundingBox.getSize(new THREE.Vector3())
  65407. var center = boundingBox.getCenter(new Vector3());
  65408. this.SplitScreen.focusOnObject(boundingBox, center);
  65409. this.gotoEntity(id, false, 0);
  65410. },
  65411. removeIlligalArchi() {
  65412. //删除marker数量小于3个的建筑,当保存时
  65413. var needDelete = [];
  65414. this.entities.forEach(e => {
  65415. if (e.points.length < 3) {
  65416. needDelete.push(e);
  65417. }
  65418. });
  65419. needDelete.forEach(e => this.removeEntity(e));
  65420. }
  65421. };
  65422. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  65423. class InfiniteGridHelper extends Mesh {
  65424. constructor(size1, size2, color, distance) {
  65425. var opacity1 = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0.2;
  65426. var opacity2 = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1;
  65427. color = color || new Color('white');
  65428. size1 = size1 || 10;
  65429. size2 = size2 || 100;
  65430. distance = distance || 8000; //可视距离?越远越模糊
  65431. var geometry = new PlaneBufferGeometry(2, 2, 1, 1);
  65432. var material = new ShaderMaterial({
  65433. side: DoubleSide,
  65434. uniforms: {
  65435. uSize1: {
  65436. value: size1
  65437. },
  65438. uSize2: {
  65439. value: size2
  65440. },
  65441. opacity1: {
  65442. //线条1的 小格子
  65443. value: opacity1
  65444. },
  65445. opacity2: {
  65446. //线条2的
  65447. value: opacity2
  65448. },
  65449. uColor: {
  65450. value: color
  65451. },
  65452. uDistance: {
  65453. value: distance
  65454. }
  65455. },
  65456. transparent: true,
  65457. vertexShader: "\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xyz * uDistance;\n pos.xy += cameraPosition.xy;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",
  65458. fragmentShader: "\n \n varying vec3 worldPosition;\n \n uniform float uSize1;\n uniform float uSize2;\n uniform float opacity1;\n uniform float opacity2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xy / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n //\u4E3A\u4F55\u4FA7\u9762\u770B\u4E0D\u5230\u7EBF\uFF0C\u56E0\u4E3Amesh\u7684\u6B63\u4FA7\u9762\u90FD\u770B\u4E0D\u5230\uFF1F\n\n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));\n //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);\n gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);\n \n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",
  65459. extensions: {
  65460. derivatives: true
  65461. }
  65462. });
  65463. super(geometry, material);
  65464. this.frustumCulled = false;
  65465. }
  65466. }
  65467. ;
  65468. /*
  65469. THREE.InfiniteGridHelper.prototype = {
  65470. ...THREE.Mesh.prototype,
  65471. ...THREE.Object3D.prototype,
  65472. ...THREE.EventDispatcher.prototype
  65473. };
  65474. */
  65475. var TransformControls = function TransformControls(camera, domElement, options) {
  65476. if (domElement === undefined) {
  65477. console.warn('THREE.TransformControls: The second parameter "domElement" is now mandatory.');
  65478. domElement = document;
  65479. }
  65480. Object3D.call(this);
  65481. this.visible = false;
  65482. this.domElement = domElement;
  65483. var _gizmo = new TransformControlsGizmo(options);
  65484. this.add(_gizmo);
  65485. this._gizmo = _gizmo;
  65486. var _plane = new TransformControlsPlane(options);
  65487. this.add(_plane);
  65488. /* this.linesAssistance = new TransformControlsLines(options); //水平 垂直 辅助
  65489. this.add( this.linesAssistance ); */
  65490. var scope = this;
  65491. //this.player = options.player;//xzw add
  65492. this.options = options; //xzw add
  65493. // Define properties with getters/setter
  65494. // Setting the defined property will automatically trigger change event
  65495. // Defined properties are passed down to gizmo and plane
  65496. defineProperty("camera", camera);
  65497. defineProperty("object", undefined);
  65498. defineProperty("enabled", true);
  65499. defineProperty("axis", null);
  65500. defineProperty("mode", "translate");
  65501. defineProperty("translationSnap", null);
  65502. defineProperty("rotationSnap", null);
  65503. defineProperty("scaleSnap", null);
  65504. defineProperty("space", "world");
  65505. defineProperty("size", 1);
  65506. defineProperty("dragging", false);
  65507. defineProperty("showX", true);
  65508. defineProperty("showY", true);
  65509. defineProperty("showZ", true);
  65510. var changeEvent = {
  65511. type: "change"
  65512. };
  65513. var mouseDownEvent = {
  65514. type: "mouseDown"
  65515. };
  65516. var mouseUpEvent = {
  65517. type: "mouseUp",
  65518. mode: scope.mode
  65519. };
  65520. var objectChangeEvent = {
  65521. type: "objectChange"
  65522. };
  65523. // Reusable utility variables
  65524. var ray = new Raycaster();
  65525. var _tempVector = new Vector3();
  65526. var _tempVector2 = new Vector3();
  65527. var _tempQuaternion = new Quaternion();
  65528. var _unit = {
  65529. X: new Vector3(1, 0, 0),
  65530. Y: new Vector3(0, 1, 0),
  65531. Z: new Vector3(0, 0, 1)
  65532. };
  65533. var pointStart = new Vector3();
  65534. var pointEnd = new Vector3();
  65535. var offset = new Vector3();
  65536. var rotationAxis = new Vector3();
  65537. var startNorm = new Vector3();
  65538. var endNorm = new Vector3();
  65539. var rotationAngle = 0;
  65540. var cameraPosition = new Vector3();
  65541. var cameraQuaternion = new Quaternion();
  65542. var cameraScale = new Vector3();
  65543. var parentPosition = new Vector3();
  65544. var parentQuaternion = new Quaternion();
  65545. var parentQuaternionInv = new Quaternion();
  65546. var parentScale = new Vector3();
  65547. var worldPositionStart = new Vector3();
  65548. var worldQuaternionStart = new Quaternion();
  65549. var worldScaleStart = new Vector3();
  65550. var worldPosition = new Vector3();
  65551. var worldQuaternion = new Quaternion();
  65552. var worldQuaternionInv = new Quaternion();
  65553. var worldScale = new Vector3();
  65554. var eye = new Vector3();
  65555. var positionStart = new Vector3();
  65556. var quaternionStart = new Quaternion();
  65557. var scaleStart = new Vector3();
  65558. // TODO: remove properties unused in plane and gizmo
  65559. defineProperty("worldPosition", worldPosition);
  65560. defineProperty("worldPositionStart", worldPositionStart);
  65561. defineProperty("worldQuaternion", worldQuaternion);
  65562. defineProperty("worldQuaternionStart", worldQuaternionStart);
  65563. defineProperty("cameraPosition", cameraPosition);
  65564. defineProperty("cameraQuaternion", cameraQuaternion);
  65565. defineProperty("pointStart", pointStart);
  65566. defineProperty("pointEnd", pointEnd);
  65567. defineProperty("rotationAxis", rotationAxis);
  65568. defineProperty("rotationAngle", rotationAngle);
  65569. defineProperty("eye", eye);
  65570. {
  65571. domElement.addEventListener("mousedown", onPointerDown, false);
  65572. domElement.addEventListener("touchstart", onPointerDown, false);
  65573. domElement.addEventListener("mousemove", onPointerHover, false);
  65574. domElement.addEventListener("touchmove", onPointerHover, false);
  65575. domElement.addEventListener("touchmove", onPointerMove, false);
  65576. document.addEventListener("mouseup", onPointerUp, false);
  65577. domElement.addEventListener("touchend", onPointerUp, false);
  65578. domElement.addEventListener("touchcancel", onPointerUp, false);
  65579. domElement.addEventListener("touchleave", onPointerUp, false);
  65580. var drag = () => {
  65581. if (this.dragging) {
  65582. this.pointerMove();
  65583. return {
  65584. stopContinue: true
  65585. };
  65586. }
  65587. };
  65588. this.addEventListener('dragging', drag, {
  65589. importance: 10
  65590. });
  65591. viewer.addEventListener('global_drag', drag, {
  65592. importance: 10
  65593. });
  65594. }
  65595. this.setRotateMethod = function (number) {
  65596. //add 注意为2时 旋转期间不能改变位置 space可能不能为local ._gizmo.hideAxis = { rotate:[这里必须包含'e' ] }
  65597. this.rotateMethod = number;
  65598. };
  65599. this.dispose = function () {
  65600. domElement.removeEventListener("mousedown", onPointerDown);
  65601. domElement.removeEventListener("touchstart", onPointerDown);
  65602. domElement.removeEventListener("mousemove", onPointerHover);
  65603. domElement.removeEventListener("mousemove", onPointerMove);
  65604. domElement.removeEventListener("touchmove", onPointerHover);
  65605. domElement.removeEventListener("touchmove", onPointerMove);
  65606. document.removeEventListener("mouseup", onPointerUp);
  65607. domElement.removeEventListener("touchend", onPointerUp);
  65608. domElement.removeEventListener("touchcancel", onPointerUp);
  65609. domElement.removeEventListener("touchleave", onPointerUp);
  65610. this.traverse(function (child) {
  65611. if (child.geometry) child.geometry.dispose();
  65612. if (child.material) child.material.dispose();
  65613. });
  65614. };
  65615. // Set current object
  65616. this.attach = function (object) {
  65617. this.object = object;
  65618. this.visible = true;
  65619. //Config.keyCon = false;//add
  65620. //this.linesAssistance.setVisible(true)
  65621. viewer.dispatchEvent('content_changed');
  65622. return this;
  65623. };
  65624. // Detatch from object
  65625. this.detach = function () {
  65626. this.object = undefined;
  65627. this.visible = false;
  65628. this.axis = null;
  65629. //Config.keyCon = true;//add
  65630. //this.linesAssistance.setVisible(false)
  65631. viewer.dispatchEvent('content_changed');
  65632. return this;
  65633. };
  65634. //this.space = 'local'
  65635. /* this.hideAxis = function ( mode, axis=[] ) {//xzw add 设置不可见的axis
  65636. var handles = [];
  65637. handles = handles.concat( this._gizmo.picker[ mode ].children );
  65638. handles = handles.concat( this._gizmo.gizmo[ mode ].children );
  65639. handles = handles.concat( this._gizmo.helper[ mode ].children );
  65640. handles.forEach(e=>e.visible = false)
  65641. axis.forEach(name=>{
  65642. handles.filter(handle =>!handle.name.includes(name))
  65643. })
  65644. handles.forEach(e=>e.visible = true)
  65645. }; */
  65646. // Defined getter, setter and store for a property
  65647. function defineProperty(propName, defaultValue) {
  65648. var propValue = defaultValue;
  65649. Object.defineProperty(scope, propName, {
  65650. get: function get() {
  65651. return propValue !== undefined ? propValue : defaultValue;
  65652. },
  65653. set: function set(value) {
  65654. if (propValue !== value) {
  65655. propValue = value;
  65656. _plane[propName] = value;
  65657. _gizmo[propName] = value;
  65658. scope.dispatchEvent({
  65659. type: propName + "-changed",
  65660. value: value
  65661. });
  65662. scope.dispatchEvent(changeEvent);
  65663. }
  65664. }
  65665. });
  65666. scope[propName] = defaultValue;
  65667. _plane[propName] = defaultValue;
  65668. _gizmo[propName] = defaultValue;
  65669. }
  65670. // updateMatrixWorld updates key transformation variables
  65671. this.updateMatrixWorld = function () {
  65672. if (!this.visible) return; //add
  65673. if (this.object !== undefined) {
  65674. this.object.updateMatrixWorld();
  65675. this.object.parent.matrixWorld.decompose(parentPosition, parentQuaternion, parentScale);
  65676. this.object.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);
  65677. //add
  65678. if (this.object.boundingBox) {
  65679. var boundingBox = this.object.boundingBox.clone().applyMatrix4(this.object.matrixWorld);
  65680. boundingBox.getCenter(worldPosition); //bound中心
  65681. if (this.pivotOnBottom) {
  65682. worldPosition.setZ(boundingBox.min.z); //中心点居于模型bound底部,因固定离地高度,旋转时旋转中心在地面上就不会变位置
  65683. }
  65684. }
  65685. parentQuaternionInv.copy(parentQuaternion).invert();
  65686. worldQuaternionInv.copy(worldQuaternion).invert();
  65687. }
  65688. this.camera.updateMatrixWorld();
  65689. this.camera.matrixWorld.decompose(cameraPosition, cameraQuaternion, cameraScale);
  65690. if (this.camera.type == "OrthographicCamera") {
  65691. //xzw add
  65692. eye.copy(this.view.direction);
  65693. } else {
  65694. eye.copy(cameraPosition).sub(worldPosition).normalize();
  65695. }
  65696. Object3D.prototype.updateMatrixWorld.call(this);
  65697. };
  65698. this.pointerHover = function () {
  65699. var pointer = viewer.inputHandler.pointer;
  65700. if (this.object === undefined) return;
  65701. //if(this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  65702. if (!this.dragging) {
  65703. var oldAxis = this.axis;
  65704. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  65705. var {
  65706. origin,
  65707. direction
  65708. } = viewer.inputHandler.getMouseDirection();
  65709. ray.set(origin, direction);
  65710. Potree.Utils.setCameraLayers(ray,
  65711. //设置能识别到的layers
  65712. ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers);
  65713. var intersect = ray.intersectObjects(_gizmo.picker[this.mode].children.filter(e => e.visible), true)[0] || false;
  65714. if (intersect) {
  65715. this.axis = intersect.object.name;
  65716. } else {
  65717. this.axis = null;
  65718. }
  65719. if (oldAxis != this.axis) {
  65720. viewer.dispatchEvent('content_changed');
  65721. }
  65722. } else {
  65723. //this.pointerMove()
  65724. }
  65725. };
  65726. this.pointerDown = function /* pointer */
  65727. () {
  65728. var pointer = viewer.inputHandler.pointer;
  65729. if (this.object === undefined || this.dragging === true /* || ( pointer.button !== undefined && pointer.button !== 0 ) */) return;
  65730. if ( /* ( pointer.button === 0 || pointer.button === undefined ) && */this.axis !== null) {
  65731. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  65732. var {
  65733. origin,
  65734. direction
  65735. } = viewer.inputHandler.getMouseDirection();
  65736. ray.set(origin, direction);
  65737. Potree.Utils.setCameraLayers(ray,
  65738. //设置能识别到的layers
  65739. ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers);
  65740. var planeIntersect = ray.intersectObjects([_plane], true)[0] || false;
  65741. if (planeIntersect) {
  65742. var space = this.space;
  65743. if (this.mode === 'scale') {
  65744. space = 'local';
  65745. } else if (this.axis === 'E' || this.axis === 'XYZE' || this.axis === 'XYZ') {
  65746. space = 'world';
  65747. }
  65748. if (space === 'local' && this.mode === 'rotate') {
  65749. var snap = this.rotationSnap;
  65750. if (this.axis === 'X' && snap) this.object.rotation.x = Math.round(this.object.rotation.x / snap) * snap;
  65751. if (this.axis === 'Y' && snap) this.object.rotation.y = Math.round(this.object.rotation.y / snap) * snap;
  65752. if (this.axis === 'Z' && snap) this.object.rotation.z = Math.round(this.object.rotation.z / snap) * snap;
  65753. }
  65754. this.object.updateMatrixWorld();
  65755. this.object.parent.updateMatrixWorld();
  65756. positionStart.copy(this.object.position);
  65757. quaternionStart.copy(this.object.quaternion);
  65758. scaleStart.copy(this.object.scale);
  65759. this.object.matrixWorld.decompose(worldPositionStart, worldQuaternionStart, worldScaleStart);
  65760. //add: 使坐标轴在boundingBox中心
  65761. this.object.boundingBox && this.object.boundingBox.getCenter(worldPositionStart).applyMatrix4(this.object.matrixWorld);
  65762. pointStart.copy(planeIntersect.point).sub(worldPositionStart);
  65763. /* if(this.player.cameraControls.activeControl){
  65764. //this.player.cameraControls.activeControl.locked = true; //add
  65765. this.player.cameraControls.activeControl.enabled = false; //add
  65766. } */
  65767. }
  65768. this.dragging = true;
  65769. mouseDownEvent.mode = this.mode;
  65770. this.dispatchEvent(mouseDownEvent);
  65771. }
  65772. };
  65773. this.pointerMove = function /* pointer */
  65774. () {
  65775. var pointer = viewer.inputHandler.pointer;
  65776. var axis = this.axis;
  65777. var mode = this.mode;
  65778. var object = this.object;
  65779. var space = this.space;
  65780. if (mode === 'scale') {
  65781. space = 'local';
  65782. } else if (axis === 'E' || axis === 'XYZE' || axis === 'XYZ') {
  65783. space = 'world';
  65784. }
  65785. if (object === undefined || axis === null || this.dragging === false || pointer.button !== undefined && pointer.button !== 0) return;
  65786. //ray.setFromCamera( pointer, this.camera ); //这句会在floorplan模式get不到intersect
  65787. var {
  65788. origin,
  65789. direction
  65790. } = viewer.inputHandler.getMouseDirection();
  65791. ray.set(origin, direction);
  65792. Potree.Utils.setCameraLayers(ray,
  65793. //设置能识别到的layers
  65794. ['sceneObjects', 'mapObjects', 'measure', 'transformationTool', 'model'], viewer.inputHandler.hoverViewport && viewer.inputHandler.hoverViewport.extraEnableLayers);
  65795. var planeIntersect = ray.intersectObjects([_plane], true)[0] || false;
  65796. if (planeIntersect === false) return;
  65797. pointEnd.copy(planeIntersect.point).sub(worldPositionStart);
  65798. if (mode === 'translate') {
  65799. // Apply translate
  65800. offset.copy(pointEnd).sub(pointStart);
  65801. if (space === 'local' && axis !== 'XYZ') {
  65802. offset.applyQuaternion(worldQuaternionInv);
  65803. }
  65804. if (axis.indexOf('X') === -1) offset.x = 0;
  65805. if (axis.indexOf('Y') === -1) offset.y = 0;
  65806. if (axis.indexOf('Z') === -1) offset.z = 0;
  65807. if (space === 'local' && axis !== 'XYZ') {
  65808. //xzw 加,否则会反向---------------
  65809. object.scale.x < 0 && (offset.x *= -1);
  65810. object.scale.y < 0 && (offset.y *= -1);
  65811. object.scale.z < 0 && (offset.z *= -1);
  65812. //---------------------------------
  65813. offset.applyQuaternion(quaternionStart).divide(parentScale);
  65814. } else {
  65815. offset.applyQuaternion(parentQuaternionInv).divide(parentScale);
  65816. }
  65817. object.position.copy(offset).add(positionStart);
  65818. // Apply translation snap
  65819. if (this.translationSnap) {
  65820. if (space === 'local') {
  65821. object.position.applyQuaternion(_tempQuaternion.copy(quaternionStart).invert());
  65822. if (axis.search('X') !== -1) {
  65823. object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap;
  65824. }
  65825. if (axis.search('Y') !== -1) {
  65826. object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap;
  65827. }
  65828. if (axis.search('Z') !== -1) {
  65829. object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap;
  65830. }
  65831. object.position.applyQuaternion(quaternionStart);
  65832. }
  65833. if (space === 'world') {
  65834. if (object.parent) {
  65835. object.position.add(_tempVector.setFromMatrixPosition(object.parent.matrixWorld));
  65836. }
  65837. if (axis.search('X') !== -1) {
  65838. object.position.x = Math.round(object.position.x / this.translationSnap) * this.translationSnap;
  65839. }
  65840. if (axis.search('Y') !== -1) {
  65841. object.position.y = Math.round(object.position.y / this.translationSnap) * this.translationSnap;
  65842. }
  65843. if (axis.search('Z') !== -1) {
  65844. object.position.z = Math.round(object.position.z / this.translationSnap) * this.translationSnap;
  65845. }
  65846. if (object.parent) {
  65847. object.position.sub(_tempVector.setFromMatrixPosition(object.parent.matrixWorld));
  65848. }
  65849. }
  65850. }
  65851. //add:
  65852. object.dispatchEvent({
  65853. type: "position_changed"
  65854. });
  65855. } else if (mode === 'scale') {
  65856. if (axis.search('XYZ') !== -1) {
  65857. var d = pointEnd.length() / pointStart.length();
  65858. if (pointEnd.dot(pointStart) < 0) d *= -1;
  65859. if (options.NoScaleZ) {
  65860. //xzw add
  65861. _tempVector2.set(d, d, 1);
  65862. } else {
  65863. _tempVector2.set(d, d, d);
  65864. }
  65865. } else if (axis.search('XY') !== -1) {
  65866. //add 等比例for plane
  65867. var d = pointEnd.length() / pointStart.length();
  65868. if (pointEnd.dot(pointStart) < 0) d *= -1;
  65869. _tempVector2.set(d, d, 1);
  65870. } else {
  65871. _tempVector.copy(pointStart);
  65872. _tempVector2.copy(pointEnd);
  65873. _tempVector.applyQuaternion(worldQuaternionInv);
  65874. _tempVector2.applyQuaternion(worldQuaternionInv);
  65875. _tempVector2.divide(_tempVector);
  65876. if (axis.search('X') === -1) {
  65877. _tempVector2.x = 1;
  65878. }
  65879. if (axis.search('Y') === -1) {
  65880. _tempVector2.y = 1;
  65881. }
  65882. if (axis.search('Z') === -1) {
  65883. _tempVector2.z = 1;
  65884. }
  65885. }
  65886. // Apply scale
  65887. object.scale.copy(scaleStart).multiply(_tempVector2);
  65888. if (this.scaleSnap) {
  65889. if (axis.search('X') !== -1) {
  65890. object.scale.x = Math.round(object.scale.x / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
  65891. }
  65892. if (axis.search('Y') !== -1) {
  65893. object.scale.y = Math.round(object.scale.y / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
  65894. }
  65895. if (axis.search('Z') !== -1) {
  65896. object.scale.z = Math.round(object.scale.z / this.scaleSnap) * this.scaleSnap || this.scaleSnap;
  65897. }
  65898. }
  65899. //add:
  65900. object.dispatchEvent({
  65901. type: "scale_changed"
  65902. });
  65903. } else if (mode === 'rotate') {
  65904. if (this.rotateMethod == 2) {
  65905. //新版参照transfromTool的写法,更跟手,但是有bug,在同时移动位置时或e轴上有问题
  65906. if (axis === 'E') {
  65907. //绕着视线转
  65908. rotationAxis.copy(eye); //旋转轴
  65909. rotationAngle = pointEnd.angleTo(pointStart);
  65910. startNorm.copy(pointStart).normalize();
  65911. endNorm.copy(pointEnd).normalize();
  65912. rotationAngle *= endNorm.cross(startNorm).dot(eye) < 0 ? 1 : -1; //角度
  65913. } else {
  65914. if (axis === 'XYZE') {
  65915. //像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  65916. offset.copy(pointEnd).sub(pointStart);
  65917. rotationAxis.copy(offset).cross(eye).normalize();
  65918. } else {
  65919. rotationAxis.copy(_unit[axis]);
  65920. }
  65921. var center = new Vector3(); //坐标轴位置
  65922. /* if(this.object.boundingBox){
  65923. center.copy(worldPosition) //center设置为boundingbox的中心。但center一直更改会导致虽然在按某个时针旋转,但v2相对v1可能会时不时逆向,导致闪烁。所以固定住center,虽然这样计算的角度和绕模型中心的感觉偏颇
  65924. }else{ */
  65925. center.copy(worldPositionStart);
  65926. //}
  65927. var rotationAxis_ = space === 'local' ? rotationAxis.clone().applyQuaternion(worldQuaternion) : rotationAxis;
  65928. var plane = new Plane().setFromNormalAndCoplanarPoint(rotationAxis_, center); //旋转过程中rotationAxis不会变化,但center可能会
  65929. var {
  65930. origin: _origin,
  65931. direction: _direction
  65932. } = viewer.inputHandler.getMouseDirection();
  65933. ray.set(_origin, _direction);
  65934. var I = ray.ray.intersectPlane(plane, new Vector3());
  65935. if (I) {
  65936. var v2 = I.clone().sub(center); //.normalize();
  65937. if (!this.rotateStart) {
  65938. this.rotateStart = {
  65939. v1: v2
  65940. };
  65941. return;
  65942. }
  65943. var v1 = this.rotateStart.v1;
  65944. rotationAngle = math.getAngle(v1, v2, rotationAxis_);
  65945. //console.log('rot', rotationAngle, center.toArray())
  65946. if (Number.isNaN(rotationAngle)) {
  65947. return;
  65948. }
  65949. this.rotateStart.v1 = v2;
  65950. }
  65951. }
  65952. } else {
  65953. //pointStart 是起始intersect - object中心的向量
  65954. //pointEnd 是当前intersect - object中心的向量
  65955. offset.copy(pointEnd).sub(pointStart);
  65956. var ROTATION_SPEED = 2 / worldPosition.distanceTo(_tempVector.setFromMatrixPosition(this.camera.matrixWorld));
  65957. if (axis === 'E') {
  65958. //绕着视线转
  65959. rotationAxis.copy(eye); //旋转轴
  65960. rotationAngle = pointEnd.angleTo(pointStart);
  65961. startNorm.copy(pointStart).normalize();
  65962. endNorm.copy(pointEnd).normalize();
  65963. rotationAngle *= endNorm.cross(startNorm).dot(eye) < 0 ? 1 : -1; //角度
  65964. } else if (axis === 'XYZE') {
  65965. //像滚球一样拨动,鼠标滑动方向为拨动方向,在plane面上滚动
  65966. rotationAxis.copy(offset).cross(eye).normalize();
  65967. rotationAngle = offset.dot(_tempVector.copy(rotationAxis).cross(this.eye)) * ROTATION_SPEED;
  65968. } else if (axis === 'X' || axis === 'Y' || axis === 'Z') {
  65969. rotationAxis.copy(_unit[axis]);
  65970. _tempVector.copy(_unit[axis]);
  65971. if (space === 'local') {
  65972. _tempVector.applyQuaternion(worldQuaternion);
  65973. }
  65974. rotationAngle = offset.dot(_tempVector.cross(eye).normalize()) * ROTATION_SPEED;
  65975. }
  65976. // Apply rotation snap
  65977. if (this.rotationSnap) rotationAngle = Math.round(rotationAngle / this.rotationSnap) * this.rotationSnap;
  65978. this.rotationAngle = rotationAngle;
  65979. }
  65980. // Apply rotate
  65981. if (space === 'local' && axis !== 'E' && axis !== 'XYZE') {
  65982. object.scale[axis.toLowerCase()] < 0 && (rotationAngle *= -1); //xzw 加,否则会反向
  65983. object.quaternion.copy(quaternionStart);
  65984. object.quaternion.multiply(_tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle)).normalize();
  65985. } else {
  65986. rotationAxis.applyQuaternion(parentQuaternionInv);
  65987. object.quaternion.copy(_tempQuaternion.setFromAxisAngle(rotationAxis, rotationAngle));
  65988. object.quaternion.multiply(quaternionStart).normalize();
  65989. }
  65990. if (this.rotateMethod == 2 && axis != 'E') {
  65991. quaternionStart.copy(object.quaternion);
  65992. }
  65993. //add:
  65994. object.dispatchEvent({
  65995. type: "rotation_changed"
  65996. });
  65997. }
  65998. this.dispatchEvent(changeEvent);
  65999. this.dispatchEvent(objectChangeEvent);
  66000. viewer.dispatchEvent('content_changed');
  66001. };
  66002. this.pointerUp = function (pointer) {
  66003. //if ( pointer.button !== undefined && pointer.button !== 0 ) return;
  66004. if (this.dragging && this.axis !== null) {
  66005. mouseUpEvent.mode = this.mode;
  66006. this.dispatchEvent(mouseUpEvent);
  66007. /* if(this.player.cameraControls.activeControl){
  66008. //this.player.cameraControls.activeControl.locked = false; //add
  66009. this.player.cameraControls.activeControl.pointerDragOn = false //add
  66010. this.player.cameraControls.activeControl.enabled = true
  66011. } */
  66012. this.rotateStart = null; //add
  66013. }
  66014. this.dragging = false;
  66015. //if ( pointer.button === undefined ) this.axis = null;
  66016. /* if(this.player.cameraControls.activeControl){
  66017. //this.player.cameraControls.activeControl.locked = false; //add
  66018. this.player.cameraControls.activeControl.pointerDragOn = false //add
  66019. this.player.cameraControls.activeControl.enabled = true
  66020. } */
  66021. };
  66022. // normalize mouse / touch pointer and remap {x,y} to view space.
  66023. function getPointer(event) {
  66024. if (!event) {
  66025. console.log('hhahhhahah');
  66026. return;
  66027. }
  66028. if (document.pointerLockElement) {
  66029. return {
  66030. x: 0,
  66031. y: 0,
  66032. button: event.button
  66033. };
  66034. } else {
  66035. var pointer = event.changedTouches ? event.changedTouches[0] : event;
  66036. var rect = domElement.getBoundingClientRect();
  66037. return {
  66038. x: (pointer.clientX - rect.left) / rect.width * 2 - 1,
  66039. y: -(pointer.clientY - rect.top) / rect.height * 2 + 1,
  66040. button: event.button
  66041. };
  66042. }
  66043. }
  66044. // mouse / touch event handlers
  66045. function onPointerHover(event) {
  66046. if (!scope.enabled) return;
  66047. //scope.pointerHover( getPointer( event ) );
  66048. scope.pointerHover();
  66049. }
  66050. function onPointerDown(event) {
  66051. if (!scope.enabled) return;
  66052. //document.addEventListener( "mousemove", onPointerMove, false );
  66053. /* scope.pointerHover( getPointer( event ) );
  66054. scope.pointerDown( getPointer( event ) ); */
  66055. scope.pointerHover();
  66056. scope.pointerDown();
  66057. }
  66058. this.onPointerDown = onPointerDown;
  66059. function onPointerMove(event) {
  66060. if (!scope.enabled || !this.dragging) return; //xzw change
  66061. //scope.pointerMove( getPointer( event ) );
  66062. scope.pointerMove();
  66063. }
  66064. this.onPointerMove = onPointerMove;
  66065. function onPointerUp(event) {
  66066. if (!scope.enabled) return;
  66067. //document.removeEventListener( "mousemove", onPointerMove, false );
  66068. //scope.pointerUp( getPointer( event ) );
  66069. scope.pointerUp();
  66070. }
  66071. this.onPointerUp = onPointerUp;
  66072. // TODO: deprecate
  66073. this.getMode = function () {
  66074. return scope.mode;
  66075. };
  66076. this.setMode = function (mode) {
  66077. scope.mode = mode;
  66078. };
  66079. this.setTranslationSnap = function (translationSnap) {
  66080. scope.translationSnap = translationSnap;
  66081. };
  66082. this.setRotationSnap = function (rotationSnap) {
  66083. scope.rotationSnap = rotationSnap;
  66084. };
  66085. this.setScaleSnap = function (scaleSnap) {
  66086. scope.scaleSnap = scaleSnap;
  66087. };
  66088. this.setSize = function (size) {
  66089. scope.size = size;
  66090. };
  66091. this.setSpace = function (space) {
  66092. scope.space = space;
  66093. };
  66094. this.update = function () {
  66095. console.warn('THREE.TransformControls: update function has no more functionality and therefore has been deprecated.');
  66096. };
  66097. };
  66098. var TransformControlsGizmo = function TransformControlsGizmo(options) {
  66099. 'use strict';
  66100. Object3D.call(this);
  66101. this.type = 'TransformControlsGizmo';
  66102. // shared materials
  66103. this.hideAxis = {};
  66104. var gizmoMaterial = new MeshBasicMaterial({
  66105. depthTest: false,
  66106. depthWrite: false,
  66107. transparent: true,
  66108. side: DoubleSide,
  66109. fog: false
  66110. });
  66111. var gizmoLineMaterial = new LineBasicMaterial({
  66112. depthTest: false,
  66113. depthWrite: false,
  66114. transparent: true,
  66115. fog: false
  66116. });
  66117. // Make unique material for each axis/color
  66118. var matInvisible = gizmoMaterial.clone();
  66119. matInvisible.opacity = 0.15;
  66120. var matHelper = gizmoMaterial.clone();
  66121. matHelper.opacity = 0.1;
  66122. var matRed = gizmoMaterial.clone();
  66123. matRed.color.set(0xff0000);
  66124. var matGreen = gizmoMaterial.clone();
  66125. matGreen.color.set(0x00ff00);
  66126. var matBlue = gizmoMaterial.clone();
  66127. matBlue.color.set(0x0000ff);
  66128. var matWhiteTransparent = gizmoMaterial.clone();
  66129. matWhiteTransparent.opacity = 0.35;
  66130. matWhiteTransparent.color.set(0x00d0fd); //xzw add
  66131. var matYellowTransparent = matWhiteTransparent.clone();
  66132. matYellowTransparent.color.set(0xffff00);
  66133. var matCyanTransparent = matWhiteTransparent.clone();
  66134. matCyanTransparent.color.set(0x00ffff);
  66135. var matMagentaTransparent = matWhiteTransparent.clone();
  66136. matMagentaTransparent.color.set(0xff00ff);
  66137. var matYellow = gizmoMaterial.clone();
  66138. matYellow.color.set(0xffff00);
  66139. var matLineRed = gizmoLineMaterial.clone();
  66140. matLineRed.color.set(0xff0000);
  66141. var matLineGreen = gizmoLineMaterial.clone();
  66142. matLineGreen.color.set(0x00ff00);
  66143. var matLineBlue = gizmoLineMaterial.clone();
  66144. matLineBlue.color.set(0x0000ff);
  66145. var matLineCyan = gizmoLineMaterial.clone();
  66146. matLineCyan.color.set(0x00ffff);
  66147. var matLineMagenta = gizmoLineMaterial.clone();
  66148. matLineMagenta.color.set(0xff00ff);
  66149. var matLineYellow = gizmoLineMaterial.clone();
  66150. matLineYellow.color.set(0xffff00);
  66151. var matLineGray = gizmoLineMaterial.clone();
  66152. matLineGray.color.set(0x787878);
  66153. var matLineYellowTransparent = matLineYellow.clone();
  66154. matLineYellowTransparent.opacity = 0.25;
  66155. // reusable geometry
  66156. var arrowGeometry = new CylinderBufferGeometry(0, 0.05, 0.2, 12, 1, false);
  66157. var scaleHandleGeometry = new BoxBufferGeometry(0.125, 0.125, 0.125);
  66158. var lineGeometry = new BufferGeometry();
  66159. //lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 0, 0 ], 3 ) );
  66160. lineGeometry.setAttribute("position", new BufferAttribute(new Float32Array([0, 0, 0, 1, 0, 0]), 3));
  66161. var CircleGeometry = function CircleGeometry(radius, arc) {
  66162. var geometry = new BufferGeometry();
  66163. var vertices = [];
  66164. for (var i = 0; i <= 64 * arc; ++i) {
  66165. vertices.push(0, Math.cos(i / 32 * Math.PI) * radius, Math.sin(i / 32 * Math.PI) * radius);
  66166. }
  66167. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  66168. geometry.setAttribute("position", new BufferAttribute(new Float32Array(vertices), 3));
  66169. return geometry;
  66170. };
  66171. // Special geometry for transform helper. If scaled with position vector it spans from [0,0,0] to position
  66172. var TranslateHelperGeometry = function TranslateHelperGeometry() {
  66173. var geometry = new BufferGeometry();
  66174. //geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 1, 1, 1 ], 3 ) );
  66175. geometry.setAttribute("position", new BufferAttribute(new Float32Array([0, 0, 0, 1, 1, 1]), 3));
  66176. return geometry;
  66177. };
  66178. // Gizmo definitions - custom hierarchy definitions for setupGizmo() function
  66179. var gizmoTranslate = {
  66180. X: [[new Mesh(arrowGeometry, matRed), [1, 0, 0], [0, 0, -Math.PI / 2], null, 'fwd'],
  66181. //[ new THREE.Mesh( arrowGeometry, matRed ), [ 1, 0, 0 ], [ 0, 0, Math.PI / 2 ], null, 'bwd' ],
  66182. [new Line(lineGeometry, matLineRed)]],
  66183. Y: [[new Mesh(arrowGeometry, matGreen), [0, 1, 0], null, null, 'fwd'],
  66184. //[ new THREE.Mesh( arrowGeometry, matGreen ), [ 0, 1, 0 ], [ Math.PI, 0, 0 ], null, 'bwd' ],
  66185. [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2]]],
  66186. Z: [[new Mesh(arrowGeometry, matBlue), [0, 0, 1], [Math.PI / 2, 0, 0], null, 'fwd'],
  66187. //[ new THREE.Mesh( arrowGeometry, matBlue ), [ 0, 0, 1 ], [ - Math.PI / 2, 0, 0 ], null, 'bwd' ],
  66188. [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0]]],
  66189. /* XYZ: [
  66190. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.1, 0 ), matWhiteTransparent.clone() ), [ 0, 0, 0 ], [ 0, 0, 0 ]]
  66191. ], */
  66192. XY: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matYellowTransparent.clone()), [0.15, 0.15, 0]], [new Line(lineGeometry, matLineYellow), [0.18, 0.3, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.3, 0.18, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]]],
  66193. YZ: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matCyanTransparent.clone()), [0, 0.15, 0.15], [0, Math.PI / 2, 0]], [new Line(lineGeometry, matLineCyan), [0, 0.18, 0.3], [0, 0, Math.PI / 2], [0.125, 1, 1]], [new Line(lineGeometry, matLineCyan), [0, 0.3, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]]],
  66194. XZ: [[new Mesh(new PlaneBufferGeometry(0.295, 0.295), matMagentaTransparent.clone()), [0.15, 0, 0.15], [-Math.PI / 2, 0, 0]], [new Line(lineGeometry, matLineMagenta), [0.18, 0, 0.3], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineMagenta), [0.3, 0, 0.18], [0, -Math.PI / 2, 0], [0.125, 1, 1]]]
  66195. };
  66196. var pickerTranslate = {
  66197. X: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0.6, 0, 0], [0, 0, -Math.PI / 2]]],
  66198. Y: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0.6, 0]]],
  66199. Z: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 1, 4, 1, false), matInvisible), [0, 0, 0.6], [Math.PI / 2, 0, 0]]],
  66200. /* XYZ: [
  66201. [ new THREE.Mesh( new THREE.OctahedronBufferGeometry( 0.2, 0 ), matInvisible ) ]
  66202. ], */
  66203. XY: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0.2, 0]]],
  66204. YZ: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0, 0.2, 0.2], [0, Math.PI / 2, 0]]],
  66205. XZ: [[new Mesh(new PlaneBufferGeometry(0.4, 0.4), matInvisible), [0.2, 0, 0.2], [-Math.PI / 2, 0, 0]]]
  66206. };
  66207. var helperTranslate = {
  66208. START: [[new Mesh(new OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, 'helper']],
  66209. END: [[new Mesh(new OctahedronBufferGeometry(0.01, 2), matHelper), null, null, null, 'helper']],
  66210. DELTA: [[new Line(TranslateHelperGeometry(), matHelper), null, null, null, 'helper']],
  66211. X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']],
  66212. Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']],
  66213. Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']]
  66214. };
  66215. var arc = options.rotFullCircle ? 1 : 0.5; //add
  66216. var gizmoRotate = {
  66217. X: [[new Line(CircleGeometry(1, arc), matLineRed)], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matRed), [0, 0, 0.99], null, [1, 3, 1]]],
  66218. Y: [[new Line(CircleGeometry(1, arc), matLineGreen), null, [0, 0, -Math.PI / 2]], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matGreen), [0, 0, 0.99], null, [3, 1, 1]]],
  66219. Z: [[new Line(CircleGeometry(1, arc), matLineBlue), null, [0, Math.PI / 2, 0]], [new Mesh(new OctahedronBufferGeometry(0.04, 0), matBlue), [0.99, 0, 0], null, [1, 3, 1]]],
  66220. E: [[new Line(CircleGeometry(1.25, 1), matLineYellowTransparent), null, [0, Math.PI / 2, 0]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [1.17, 0, 0], [0, 0, -Math.PI / 2], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [-1.17, 0, 0], [0, 0, Math.PI / 2], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, -1.17, 0], [Math.PI, 0, 0], [1, 1, 0.001]], [new Mesh(new CylinderBufferGeometry(0.03, 0, 0.15, 4, 1, false), matLineYellowTransparent), [0, 1.17, 0], [0, 0, 0], [1, 1, 0.001]]],
  66221. XYZE: [[new Line(CircleGeometry(1, 1), matLineGray), null, [0, Math.PI / 2, 0]]]
  66222. };
  66223. var helperRotate = {
  66224. AXIS: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']]
  66225. };
  66226. var pickerRotate = {
  66227. X: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, -Math.PI / 2, -Math.PI / 2]]],
  66228. Y: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [Math.PI / 2, 0, 0]]],
  66229. Z: [[new Mesh(new TorusBufferGeometry(1, 0.1, 4, 24), matInvisible), [0, 0, 0], [0, 0, -Math.PI / 2]]],
  66230. E: [[new Mesh(new TorusBufferGeometry(1.25, 0.1, 2, 24), matInvisible)]],
  66231. XYZE: [[new Mesh(new SphereBufferGeometry(0.7, 10, 8), matInvisible)]]
  66232. };
  66233. var gizmoScale = {
  66234. X: [[new Mesh(scaleHandleGeometry, matRed), [0.8, 0, 0], [0, 0, -Math.PI / 2]], [new Line(lineGeometry, matLineRed), null, null, [0.8, 1, 1]]],
  66235. Y: [[new Mesh(scaleHandleGeometry, matGreen), [0, 0.8, 0]], [new Line(lineGeometry, matLineGreen), null, [0, 0, Math.PI / 2], [0.8, 1, 1]]],
  66236. Z: [[new Mesh(scaleHandleGeometry, matBlue), [0, 0, 0.8], [Math.PI / 2, 0, 0]], [new Line(lineGeometry, matLineBlue), null, [0, -Math.PI / 2, 0], [0.8, 1, 1]]],
  66237. XY: [[new Mesh(scaleHandleGeometry, matYellowTransparent), [0.85, 0.85, 0], null, [2, 2, 0.2]], [new Line(lineGeometry, matLineYellow), [0.855, 0.98, 0], null, [0.125, 1, 1]], [new Line(lineGeometry, matLineYellow), [0.98, 0.855, 0], [0, 0, Math.PI / 2], [0.125, 1, 1]]],
  66238. /* YZ: [
  66239. [ new THREE.Mesh( scaleHandleGeometry, matCyanTransparent ), [ 0, 0.85, 0.85 ], null, [ 0.2, 2, 2 ]],
  66240. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.855, 0.98 ], [ 0, 0, Math.PI / 2 ], [ 0.125, 1, 1 ]],
  66241. [ new THREE.Line( lineGeometry, matLineCyan ), [ 0, 0.98, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  66242. ],
  66243. XZ: [
  66244. [ new THREE.Mesh( scaleHandleGeometry, matMagentaTransparent ), [ 0.85, 0, 0.85 ], null, [ 2, 0.2, 2 ]],
  66245. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.855, 0, 0.98 ], null, [ 0.125, 1, 1 ]],
  66246. [ new THREE.Line( lineGeometry, matLineMagenta ), [ 0.98, 0, 0.855 ], [ 0, - Math.PI / 2, 0 ], [ 0.125, 1, 1 ]]
  66247. ],
  66248. XYZX: [
  66249. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 1.1, 0, 0 ]],
  66250. ],*/
  66251. XYZY: [[new Mesh(new BoxBufferGeometry(0.125, 0.125, 0.125), matWhiteTransparent.clone()), [0, 1.1, 0]]] /* ,
  66252. XYZZ: [
  66253. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.125, 0.125, 0.125 ), matWhiteTransparent.clone() ), [ 0, 0, 1.1 ]],
  66254. ] */
  66255. };
  66256. var pickerScale = {
  66257. X: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0.5, 0, 0], [0, 0, -Math.PI / 2]]],
  66258. Y: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0.5, 0]]],
  66259. Z: [[new Mesh(new CylinderBufferGeometry(0.2, 0, 0.8, 4, 1, false), matInvisible), [0, 0, 0.5], [Math.PI / 2, 0, 0]]],
  66260. XY: [[new Mesh(scaleHandleGeometry, matInvisible), [0.85, 0.85, 0], null, [3, 3, 0.2]]],
  66261. /*YZ: [
  66262. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0, 0.85, 0.85 ], null, [ 0.2, 3, 3 ]],
  66263. ],
  66264. XZ: [
  66265. [ new THREE.Mesh( scaleHandleGeometry, matInvisible ), [ 0.85, 0, 0.85 ], null, [ 3, 0.2, 3 ]],
  66266. ],
  66267. XYZX: [
  66268. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 1.1, 0, 0 ]],
  66269. ],*/
  66270. XYZY: [[new Mesh(new BoxBufferGeometry(0.2, 0.2, 0.2), matInvisible), [0, 1.1, 0]]] /* ,
  66271. XYZZ: [
  66272. [ new THREE.Mesh( new THREE.BoxBufferGeometry( 0.2, 0.2, 0.2 ), matInvisible ), [ 0, 0, 1.1 ]],
  66273. ] */
  66274. };
  66275. var helperScale = {
  66276. X: [[new Line(lineGeometry, matHelper.clone()), [-1e3, 0, 0], null, [1e6, 1, 1], 'helper']],
  66277. Y: [[new Line(lineGeometry, matHelper.clone()), [0, -1e3, 0], [0, 0, Math.PI / 2], [1e6, 1, 1], 'helper']],
  66278. Z: [[new Line(lineGeometry, matHelper.clone()), [0, 0, -1e3], [0, -Math.PI / 2, 0], [1e6, 1, 1], 'helper']]
  66279. };
  66280. // Creates an THREE.Object3D with gizmos described in custom hierarchy definition.
  66281. var setupGizmo = function setupGizmo(gizmoMap) {
  66282. var gizmo = new Object3D();
  66283. for (var name in gizmoMap) {
  66284. for (var i = gizmoMap[name].length; i--;) {
  66285. var object = gizmoMap[name][i][0].clone();
  66286. var position = gizmoMap[name][i][1];
  66287. var rotation = gizmoMap[name][i][2];
  66288. var scale = gizmoMap[name][i][3];
  66289. var tag = gizmoMap[name][i][4];
  66290. // name and tag properties are essential for picking and updating logic.
  66291. object.name = name;
  66292. object.tag = tag;
  66293. if (position) {
  66294. object.position.set(position[0], position[1], position[2]);
  66295. }
  66296. if (rotation) {
  66297. object.rotation.set(rotation[0], rotation[1], rotation[2]);
  66298. }
  66299. if (scale) {
  66300. object.scale.set(scale[0], scale[1], scale[2]);
  66301. }
  66302. object.updateMatrix();
  66303. var tempGeometry = object.geometry.clone();
  66304. tempGeometry.applyMatrix4(object.matrix);
  66305. object.geometry = tempGeometry;
  66306. object.renderOrder = Infinity;
  66307. object.position.set(0, 0, 0);
  66308. object.rotation.set(0, 0, 0);
  66309. object.scale.set(1, 1, 1);
  66310. gizmo.add(object);
  66311. }
  66312. }
  66313. return gizmo;
  66314. };
  66315. // Reusable utility variables
  66316. var tempVector = new Vector3(0, 0, 0);
  66317. var tempEuler = new Euler();
  66318. var alignVector = new Vector3(0, 1, 0);
  66319. var zeroVector = new Vector3(0, 0, 0);
  66320. var lookAtMatrix = new Matrix4();
  66321. var tempQuaternion = new Quaternion();
  66322. var tempQuaternion2 = new Quaternion();
  66323. var identityQuaternion = new Quaternion();
  66324. var unitX = new Vector3(1, 0, 0);
  66325. var unitY = new Vector3(0, 1, 0);
  66326. var unitZ = new Vector3(0, 0, 1);
  66327. // Gizmo creation
  66328. this.gizmo = {};
  66329. this.picker = {};
  66330. this.helper = {};
  66331. this.add(this.gizmo["translate"] = setupGizmo(gizmoTranslate));
  66332. this.add(this.gizmo["rotate"] = setupGizmo(gizmoRotate));
  66333. this.add(this.gizmo["scale"] = setupGizmo(gizmoScale));
  66334. this.add(this.picker["translate"] = setupGizmo(pickerTranslate));
  66335. this.add(this.picker["rotate"] = setupGizmo(pickerRotate));
  66336. this.add(this.picker["scale"] = setupGizmo(pickerScale));
  66337. this.add(this.helper["translate"] = setupGizmo(helperTranslate));
  66338. this.add(this.helper["rotate"] = setupGizmo(helperRotate));
  66339. this.add(this.helper["scale"] = setupGizmo(helperScale));
  66340. // Pickers should be hidden always
  66341. this.picker["translate"].visible = false;
  66342. this.picker["rotate"].visible = false;
  66343. this.picker["scale"].visible = false;
  66344. // updateMatrixWorld will update transformations and appearance of individual handles
  66345. this.updateMatrixWorld = function () {
  66346. if (!this.parent.visible) return; //add
  66347. var space = this.space;
  66348. if (this.mode === 'scale') space = 'local'; // scale always oriented to local rotation
  66349. var quaternion = space === "local" ? this.worldQuaternion : identityQuaternion;
  66350. // Show only gizmos for current transform mode
  66351. this.gizmo["translate"].visible = this.mode === "translate";
  66352. this.gizmo["rotate"].visible = this.mode === "rotate";
  66353. this.gizmo["scale"].visible = this.mode === "scale";
  66354. this.helper["translate"].visible = this.mode === "translate";
  66355. this.helper["rotate"].visible = this.mode === "rotate";
  66356. this.helper["scale"].visible = this.mode === "scale";
  66357. var handles = [];
  66358. handles = handles.concat(this.picker[this.mode].children);
  66359. handles = handles.concat(this.gizmo[this.mode].children);
  66360. handles = handles.concat(this.helper[this.mode].children);
  66361. for (var i = 0; i < handles.length; i++) {
  66362. var handle = handles[i];
  66363. //add
  66364. if (this.hideAxis[this.mode] && this.hideAxis[this.mode].some(e => handle.name.includes(e.toUpperCase()))) {
  66365. Potree.Utils.updateVisible(handle, 'hidden', false);
  66366. continue;
  66367. }
  66368. var visible = true;
  66369. // hide aligned to camera
  66370. handle.rotation.set(0, 0, 0);
  66371. handle.position.copy(this.worldPosition);
  66372. if (this.camera.type == "OrthographicCamera") {
  66373. var eyeDistance = 800 / this.camera.zoom;
  66374. } else {
  66375. var eyeDistance = this.worldPosition.distanceTo(this.cameraPosition);
  66376. }
  66377. handle.scale.set(1, 1, 1).multiplyScalar(eyeDistance * this.size / 7);
  66378. // TODO: simplify helpers and consider decoupling from gizmo
  66379. if (handle.tag === 'helper') {
  66380. visible = false;
  66381. if (handle.name === 'AXIS') {
  66382. handle.position.copy(this.worldPositionStart);
  66383. visible = !!this.axis;
  66384. if (this.axis === 'X') {
  66385. tempQuaternion.setFromEuler(tempEuler.set(0, 0, 0));
  66386. handle.quaternion.copy(quaternion).multiply(tempQuaternion);
  66387. if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
  66388. visible = false;
  66389. }
  66390. }
  66391. if (this.axis === 'Y') {
  66392. tempQuaternion.setFromEuler(tempEuler.set(0, 0, Math.PI / 2));
  66393. handle.quaternion.copy(quaternion).multiply(tempQuaternion);
  66394. if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
  66395. visible = false;
  66396. }
  66397. }
  66398. if (this.axis === 'Z') {
  66399. tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0));
  66400. handle.quaternion.copy(quaternion).multiply(tempQuaternion);
  66401. if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) > 0.9) {
  66402. visible = false;
  66403. }
  66404. }
  66405. if (this.axis === 'XYZE') {
  66406. tempQuaternion.setFromEuler(tempEuler.set(0, Math.PI / 2, 0));
  66407. alignVector.copy(this.rotationAxis);
  66408. handle.quaternion.setFromRotationMatrix(lookAtMatrix.lookAt(zeroVector, alignVector, unitY));
  66409. handle.quaternion.multiply(tempQuaternion);
  66410. visible = this.dragging;
  66411. }
  66412. if (this.axis === 'E') {
  66413. visible = false;
  66414. }
  66415. } else if (handle.name === 'START') {
  66416. handle.position.copy(this.worldPositionStart);
  66417. visible = this.dragging;
  66418. } else if (handle.name === 'END') {
  66419. handle.position.copy(this.worldPosition);
  66420. visible = this.dragging;
  66421. } else if (handle.name === 'DELTA') {
  66422. handle.position.copy(this.worldPositionStart);
  66423. handle.quaternion.copy(this.worldQuaternionStart);
  66424. tempVector.set(1e-10, 1e-10, 1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1);
  66425. tempVector.applyQuaternion(this.worldQuaternionStart.clone().invert());
  66426. handle.scale.copy(tempVector);
  66427. visible = this.dragging;
  66428. } else {
  66429. handle.quaternion.copy(quaternion);
  66430. if (this.dragging) {
  66431. handle.position.copy(this.worldPositionStart);
  66432. } else {
  66433. handle.position.copy(this.worldPosition);
  66434. }
  66435. if (this.axis) {
  66436. visible = this.axis.search(handle.name) !== -1;
  66437. }
  66438. }
  66439. // If updating helper, skip rest of the loop
  66440. Potree.Utils.updateVisible(handle, 'hidden', !!visible);
  66441. continue;
  66442. }
  66443. // Align handles to current local or world rotation
  66444. handle.quaternion.copy(quaternion);
  66445. if (this.mode === 'translate' || this.mode === 'scale') {
  66446. // Hide translate and scale axis facing the camera
  66447. var AXIS_HIDE_TRESHOLD = 0.99;
  66448. var PLANE_HIDE_TRESHOLD = 0.2;
  66449. var AXIS_FLIP_TRESHOLD = 0.0;
  66450. if (options.dontHideWhenFaceCamera) {//xzw add
  66451. //正对镜头时不隐藏箭头
  66452. } else {
  66453. if (handle.name === 'X' || handle.name === 'XYZX') {
  66454. if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) {
  66455. handle.scale.set(1e-10, 1e-10, 1e-10);
  66456. visible = false;
  66457. }
  66458. }
  66459. if (handle.name === 'Y' || handle.name === 'XYZY') {
  66460. if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) {
  66461. handle.scale.set(1e-10, 1e-10, 1e-10);
  66462. visible = false;
  66463. }
  66464. }
  66465. if (handle.name === 'Z' || handle.name === 'XYZZ') {
  66466. if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) > AXIS_HIDE_TRESHOLD) {
  66467. handle.scale.set(1e-10, 1e-10, 1e-10);
  66468. visible = false;
  66469. }
  66470. }
  66471. if (handle.name === 'XY') {
  66472. if (Math.abs(alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) {
  66473. handle.scale.set(1e-10, 1e-10, 1e-10);
  66474. visible = false;
  66475. }
  66476. }
  66477. if (handle.name === 'YZ') {
  66478. if (Math.abs(alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) {
  66479. handle.scale.set(1e-10, 1e-10, 1e-10);
  66480. visible = false;
  66481. }
  66482. }
  66483. if (handle.name === 'XZ') {
  66484. if (Math.abs(alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye)) < PLANE_HIDE_TRESHOLD) {
  66485. handle.scale.set(1e-10, 1e-10, 1e-10);
  66486. visible = false;
  66487. }
  66488. }
  66489. }
  66490. // Flip translate and scale axis ocluded behind another axis
  66491. //xzw 改 去掉反向箭头
  66492. if (handle.name.search('X') !== -1) {
  66493. if (alignVector.copy(unitX).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) {
  66494. /* if ( handle.tag === 'fwd' ) {
  66495. handle.visible = false;
  66496. } else {
  66497. handle.scale.x *= - 1;
  66498. }
  66499. } else if ( handle.tag === 'bwd' ) {
  66500. handle.visible = false;*/
  66501. handle.scale.x *= -1;
  66502. }
  66503. }
  66504. if (handle.name.search('Y') !== -1) {
  66505. if (alignVector.copy(unitY).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) {
  66506. /* if ( handle.tag === 'fwd' ) {
  66507. handle.visible = false;
  66508. } else {
  66509. handle.scale.y *= - 1;
  66510. }
  66511. } else if ( handle.tag === 'bwd' ) {
  66512. handle.visible = false;
  66513. */
  66514. handle.scale.y *= -1;
  66515. }
  66516. }
  66517. if (handle.name.search('Z') !== -1) {
  66518. if (alignVector.copy(unitZ).applyQuaternion(quaternion).dot(this.eye) < AXIS_FLIP_TRESHOLD) {
  66519. /* if ( handle.tag === 'fwd' ) {
  66520. handle.visible = false;
  66521. } else {
  66522. handle.scale.z *= - 1;
  66523. }
  66524. } else if ( handle.tag === 'bwd' ) {
  66525. handle.visible = false; */
  66526. handle.scale.z *= -1;
  66527. }
  66528. }
  66529. } else if (this.mode === 'rotate') {
  66530. // Align handles to current local or world rotation
  66531. tempQuaternion2.copy(quaternion);
  66532. alignVector.copy(this.eye).applyQuaternion(tempQuaternion.copy(quaternion).invert());
  66533. if (handle.name.search("E") !== -1) {
  66534. handle.quaternion.setFromRotationMatrix(lookAtMatrix.lookAt(this.eye, zeroVector, unitY));
  66535. }
  66536. if (handle.name === 'X') {
  66537. tempQuaternion.setFromAxisAngle(unitX, Math.atan2(-alignVector.y, alignVector.z));
  66538. tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion);
  66539. handle.quaternion.copy(tempQuaternion);
  66540. }
  66541. if (handle.name === 'Y') {
  66542. tempQuaternion.setFromAxisAngle(unitY, Math.atan2(alignVector.x, alignVector.z));
  66543. tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion);
  66544. handle.quaternion.copy(tempQuaternion);
  66545. }
  66546. if (handle.name === 'Z') {
  66547. tempQuaternion.setFromAxisAngle(unitZ, Math.atan2(alignVector.y, alignVector.x));
  66548. tempQuaternion.multiplyQuaternions(tempQuaternion2, tempQuaternion);
  66549. handle.quaternion.copy(tempQuaternion);
  66550. }
  66551. }
  66552. // Hide disabled axes
  66553. visible = visible && (handle.name.indexOf("X") === -1 || this.showX);
  66554. visible = visible && (handle.name.indexOf("Y") === -1 || this.showY);
  66555. visible = visible && (handle.name.indexOf("Z") === -1 || this.showZ);
  66556. visible = visible && (handle.name.indexOf("E") === -1 || this.showX && this.showY && this.showZ);
  66557. Potree.Utils.updateVisible(handle, 'hidden', !!visible);
  66558. // highlight selected axis
  66559. handle.material._opacity = handle.material._opacity || handle.material.opacity;
  66560. handle.material._color = handle.material._color || handle.material.color.clone();
  66561. handle.material.color.copy(handle.material._color);
  66562. handle.material.opacity = handle.material._opacity;
  66563. if (!this.enabled) {
  66564. handle.material.opacity *= 0.5;
  66565. handle.material.color.lerp(new Color(1, 1, 1), 0.5);
  66566. } else if (this.axis) {
  66567. if (handle.name === this.axis) {
  66568. handle.material.opacity = 1.0;
  66569. handle.material.color.lerp(new Color(1, 1, 1), 0.5);
  66570. } else if (this.axis.split('').some(function (a) {
  66571. return handle.name === a;
  66572. })) {
  66573. handle.material.opacity = 1.0;
  66574. handle.material.color.lerp(new Color(1, 1, 1), 0.5);
  66575. } else {
  66576. handle.material.opacity *= 0.25;
  66577. handle.material.color.lerp(new Color(1, 1, 1), 0.5);
  66578. }
  66579. }
  66580. }
  66581. Object3D.prototype.updateMatrixWorld.call(this);
  66582. };
  66583. };
  66584. /* var TransformControlsLines = function (options) {
  66585. THREE.Object3D.call( this)
  66586. let label1 = new Label2D({ innerHTML:`<div>与相机水平距离</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  66587. let label2 = new Label2D({ innerHTML:`<div>与相机高度差</div>` , domElement:$("#otherLabels")[0] ,autoUpdate:true })
  66588. let css = {'opacity': 0.7, 'color': '#07fceb', transform:'translate(-50%, -50%)'}
  66589. label1.elem.css(css);
  66590. label2.elem.css(css)
  66591. //for(let i=0;i<2;i++){
  66592. // let line = LineDraw.createLine([new THREE.THREE.Vector3, new THREE.THREE.Vector3],{color:'#07fceb', opacity:0.7 })
  66593. // this.add(line)
  66594. //}
  66595. this.updateTransform = function(object){
  66596. object = object || this.parent.object;
  66597. let A = player.position.clone(); //当前相机位置
  66598. let B = object.position //物体位置
  66599. let C = B.clone().setY(A.y); //物体在相机的高度的位置
  66600. let D = A.clone().setY(B.y); //相机在物体的高度的位置
  66601. //LineDraw.moveLine(this.children[0], [B, C]) // 垂直线
  66602. //LineDraw.moveLine(this.children[1], [D, B]) // 水平线
  66603. let dis1 = toPrecision(D.distanceTo(B),1)
  66604. let dis2 = C.y - B.y
  66605. label1.elem.text('与相机水平距离: '+dis1+'米')
  66606. label2.elem.text('在相机之'+ (dis2>0?'下' : '上') +' :'+ toPrecision(dis2 , 1) +'米')
  66607. label1.setPos(new THREE.THREE.Vector3().addVectors(D,B).multiplyScalar(0.5))
  66608. label2.setPos(new THREE.THREE.Vector3().addVectors(B,C).multiplyScalar(0.5))
  66609. }
  66610. this.setVisible = (v,reason)=>{
  66611. label1.setVisible(v, reason || 'unvisi')
  66612. label2.setVisible(v, reason || 'unvisi')
  66613. this.visible = label1.visible
  66614. if(this.visible){
  66615. this.updateTransform()
  66616. }
  66617. }
  66618. this.setVisible(false)
  66619. player.on("mode.changing",(currentMode, mode, pano, duration)=>{
  66620. if(mode != 'panorama'){
  66621. this.setVisible(false, 'isPanorama')
  66622. }else{
  66623. this.setVisible(true, 'isPanorama')
  66624. }
  66625. })
  66626. player.on("flying.started",( )=>{
  66627. this.setVisible(false, 'flying')
  66628. })
  66629. player.on("flying.ended",( )=>{
  66630. this.setVisible(true, 'flying')
  66631. })
  66632. }
  66633. */
  66634. var TransformControlsPlane = function TransformControlsPlane(options) {
  66635. 'use strict';
  66636. Mesh.call(this, new PlaneBufferGeometry(100000, 100000, 2, 2), new MeshBasicMaterial({
  66637. color: "#ff0000",
  66638. visible: false,
  66639. wireframe: false,
  66640. side: DoubleSide,
  66641. transparent: true,
  66642. opacity: 0.2
  66643. }));
  66644. this.type = 'TransformControlsPlane';
  66645. var unitX = new Vector3(1, 0, 0);
  66646. var unitY = new Vector3(0, 1, 0);
  66647. var unitZ = new Vector3(0, 0, 1);
  66648. var tempVector = new Vector3();
  66649. var dirVector = new Vector3();
  66650. var alignVector = new Vector3();
  66651. var tempMatrix = new Matrix4();
  66652. var identityQuaternion = new Quaternion();
  66653. this.updateMatrixWorld = function () {
  66654. if (!this.visible) return; //add
  66655. var space = this.space;
  66656. this.position.copy(this.worldPosition);
  66657. if (this.mode === 'scale') space = 'local'; // scale always oriented to local rotation
  66658. unitX.set(1, 0, 0).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion);
  66659. unitY.set(0, 1, 0).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion);
  66660. unitZ.set(0, 0, 1).applyQuaternion(space === "local" ? this.worldQuaternion : identityQuaternion);
  66661. // Align the plane for current transform mode, axis and space.
  66662. alignVector.copy(unitY);
  66663. switch (this.mode) {
  66664. case 'translate':
  66665. case 'scale':
  66666. switch (this.axis) {
  66667. case 'X':
  66668. alignVector.copy(this.eye).cross(unitX);
  66669. dirVector.copy(unitX).cross(alignVector);
  66670. break;
  66671. case 'Y':
  66672. alignVector.copy(this.eye).cross(unitY);
  66673. dirVector.copy(unitY).cross(alignVector);
  66674. break;
  66675. case 'Z':
  66676. alignVector.copy(this.eye).cross(unitZ);
  66677. dirVector.copy(unitZ).cross(alignVector);
  66678. break;
  66679. case 'XY':
  66680. dirVector.copy(unitZ);
  66681. break;
  66682. case 'YZ':
  66683. dirVector.copy(unitX);
  66684. break;
  66685. case 'XZ':
  66686. alignVector.copy(unitZ);
  66687. dirVector.copy(unitY);
  66688. break;
  66689. case 'XYZ':
  66690. case 'E':
  66691. default:
  66692. //xzw add for scale xyzz
  66693. dirVector.set(0, 0, 0);
  66694. break;
  66695. }
  66696. break;
  66697. case 'rotate':
  66698. default:
  66699. // special case for rotate
  66700. dirVector.set(0, 0, 0);
  66701. }
  66702. if (dirVector.length() === 0) {
  66703. //使物体在视线中平移
  66704. // If in rotate mode, make the plane parallel to camera
  66705. this.quaternion.copy(this.cameraQuaternion);
  66706. } else {
  66707. //方向滑动所在面
  66708. tempMatrix.lookAt(tempVector.set(0, 0, 0), dirVector, alignVector);
  66709. this.quaternion.setFromRotationMatrix(tempMatrix);
  66710. }
  66711. Object3D.prototype.updateMatrixWorld.call(this);
  66712. };
  66713. };
  66714. TransformControls.prototype = Object.assign(Object.create(Object3D.prototype), {
  66715. constructor: TransformControls,
  66716. isTransformControls: true
  66717. });
  66718. TransformControlsGizmo.prototype = Object.assign(Object.create(Object3D.prototype), {
  66719. constructor: TransformControlsGizmo,
  66720. isTransformControlsGizmo: true
  66721. });
  66722. TransformControlsPlane.prototype = Object.assign(Object.create(Mesh.prototype), {
  66723. constructor: TransformControlsPlane,
  66724. isTransformControlsPlane: true
  66725. });
  66726. /*
  66727. 备注:
  66728. //这里虽然 使坐标轴在boundingBox中心
  66729. boundingBox && this.object.boundingBox.getCenter(worldPosition).applyMatrix4(this.object.matrixWorld);
  66730. 但是旋转中心并不是这个坐标轴显示的位置,需要再执行 MergeEditor.maintainBoundXY()才能维持在这个中心
  66731. */
  66732. var texLoader$a = new TextureLoader();
  66733. texLoader$a.crossOrigin = "anonymous";
  66734. var edgeStrengths = {
  66735. pointcloud: 4,
  66736. glb: 100
  66737. };
  66738. var viewportProps$1 = [{
  66739. left: 0,
  66740. bottom: 0,
  66741. width: 0.5,
  66742. height: 1,
  66743. name: 'top',
  66744. axis: ["x", "y"],
  66745. direction: new Vector3(0, 0, -1),
  66746. //镜头朝向
  66747. active: true,
  66748. //相机位置在z轴正向
  66749. limitBound: new Box3(new Vector3(-Infinity, -Infinity, 1), new Vector3(Infinity, Infinity, 5000)),
  66750. //在地面以上
  66751. margin: {
  66752. x: 50,
  66753. y: 150
  66754. }
  66755. }, {
  66756. left: 0.5,
  66757. bottom: 0,
  66758. width: 0.5,
  66759. height: 1,
  66760. name: 'right',
  66761. axis: ["y", "z"],
  66762. direction: new Vector3(1, 0, 0),
  66763. active: true,
  66764. //相机位置在x轴负向 右下角屏
  66765. viewContainsPoints: [new Vector3(0, 0, 0)],
  66766. margin: {
  66767. x: 300,
  66768. y: 250
  66769. }
  66770. }];
  66771. var cylinderSkyGeo, oldSkyGeo;
  66772. var MergeEditor = {
  66773. bus: new EventDispatcher(),
  66774. SplitScreen: new SplitScreen(),
  66775. init() {
  66776. this.history = new History({
  66777. applyData: data => {
  66778. if (data.object.parent /* && data.object == this.selected */) {
  66779. data = Potree.Common.CloneObject(data); //避免使用后更改数据又被使用
  66780. data.matrix.decompose(data.object.position, data.object.quaternion, data.object.scale);
  66781. data.object.boundCenter.copy(data.boundCenter);
  66782. data.object.dispatchEvent('changeByHistory');
  66783. data.object.dispatchEvent('transformChanged');
  66784. viewer.dispatchEvent('content_changed');
  66785. return true;
  66786. }
  66787. },
  66788. getData: object => {
  66789. return {
  66790. object,
  66791. matrix: object.matrixWorld.clone(),
  66792. boundCenter: object.boundCenter.clone()
  66793. };
  66794. }
  66795. });
  66796. {
  66797. Potree.settings.notAdditiveBlending = true;
  66798. var ground = this.ground = new InfiniteGridHelper(1, 10000, new Color('#eee'), 10000, 0.2, 0.3);
  66799. viewer.scene.scene.add(ground);
  66800. //再加两条线否则在正侧边看不到
  66801. var line1 = LineDraw.createLine([new Vector3(-10000, 0, 0), new Vector3(10000, 0, 0)], {
  66802. color: '#aaa'
  66803. });
  66804. var line2 = LineDraw.createLine([new Vector3(0, -10000, 0), new Vector3(0, 10000, 0)], {
  66805. mat: line1.material
  66806. });
  66807. ground.renderOrder = Potree.config.renderOrders.model + 1; //line1.renderOrder + 1 //要比模型低,否则模型透明时效果不对
  66808. ground.add(line1);
  66809. ground.add(line2);
  66810. ground.material.opacity = 0.9; //为了滞后渲染,否则被rt遮住
  66811. ground.material.polygonOffset = true; //多边形偏移(视觉上没有移动模型位置),防止闪烁
  66812. ground.material.polygonOffsetFactor = 100; //多边形偏移因子
  66813. ground.material.polygonOffsetUnits = 10; //多边形偏移单位
  66814. ground.material.depthWrite = false;
  66815. //ground.material.depthTest = false
  66816. line1.material.polygonOffset = true;
  66817. line1.material.polygonOffsetFactor = 130;
  66818. line1.material.polygonOffsetUnits = 10;
  66819. line1.material.depthWrite = false;
  66820. //见笔记:透明物体的材质设置
  66821. }
  66822. var oriEdgeStrength = viewer.outlinePass.edgeStrength;
  66823. {
  66824. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, {
  66825. dontHideWhenFaceCamera: true
  66826. });
  66827. //this.transformControls.space = 'local'//为了在当前方向上平移
  66828. this.transformControls.setSize(1.5);
  66829. viewer.scene.scene.add(this.transformControls);
  66830. this.transformControls._gizmo.hideAxis = {
  66831. rotate: ['e']
  66832. };
  66833. this.transformControls.setRotateMethod(2);
  66834. //右屏
  66835. this.transformControls2 = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, {
  66836. dontHideWhenFaceCamera: true
  66837. });
  66838. this.transformControls2.setSize(1.5);
  66839. viewer.scene.scene.add(this.transformControls2);
  66840. Potree.Utils.setObjectLayers(this.transformControls2, 'layer2');
  66841. var mouseDown = e => {
  66842. viewer.outlinePass.edgeStrength = 0; //暂时消失线
  66843. };
  66844. var mouseUp = e => {
  66845. //this.updateEdgeStrength()
  66846. viewer.outlinePass.edgeStrength = oriEdgeStrength;
  66847. };
  66848. this.transformControls.addEventListener('mouseDown', mouseDown);
  66849. this.transformControls2.addEventListener('mouseDown', mouseDown);
  66850. this.transformControls.addEventListener('mouseUp', mouseUp);
  66851. this.transformControls2.addEventListener('mouseUp', mouseUp);
  66852. this.transformControls.addEventListener('mouseDown', () => {
  66853. //dragstart
  66854. this.history.beforeChange(this.selected);
  66855. });
  66856. this.transformControls.addEventListener('mouseUp', () => {
  66857. this.history.afterChange(this.selected);
  66858. });
  66859. }
  66860. {
  66861. this.secondCompass = new Compass(null);
  66862. }
  66863. viewer.setControls(viewer.orbitControls);
  66864. //viewer.mainViewport.view.fixZWhenPan = true
  66865. viewer.orbitControls.constantlyForward = true;
  66866. viewer.addEventListener('global_single_click', e => {
  66867. if (this.noNeedSelection //如模型查看页
  66868. || viewer.scene.cameraAnimations.some(c => c.onUpdate) //正在播放
  66869. || e.drag && e.drag.notPressMouse //在加测量线
  66870. || viewer.mainViewport.view.isFlying() //有其他校准
  66871. || this.split //分屏中
  66872. || e.clickElement //触发别的点击事件,如测量时click marker /* && e.clickElement != e.intersect.object */
  66873. ) {
  66874. return;
  66875. }
  66876. if (e.intersect) {
  66877. var object = e.intersect.object || e.intersect.pointcloud;
  66878. var objects = this.getAllObjects();
  66879. if (objects.includes(object) && this.selected != object) {
  66880. this.selectModel(object);
  66881. } else {
  66882. //if(!viewer.inputHandler.selection[0]){//正在平移和旋转,不允许取消
  66883. this.selectModel(null);
  66884. //}
  66885. }
  66886. } else {
  66887. //if(!viewer.inputHandler.selection[0]){
  66888. this.selectModel(null);
  66889. //}
  66890. }
  66891. });
  66892. viewer.inputHandler.addEventListener('keydown', e => {
  66893. if (e.event.key.toLowerCase() == "h") {
  66894. this.fadeOutlineAuto = !this.fadeOutlineAuto;
  66895. this.showModelOutline(this.selected, !!this.selected);
  66896. }
  66897. });
  66898. //viewer.fxaaPass.enabled = false//viewer.ssaaRenderPass.enabled = false
  66899. viewer.outlinePass.enabled = true;
  66900. //Potree.settings.intersectWhenHover = false
  66901. //Potree.Utils.updateVisible(viewer.reticule, 'force', false)
  66902. viewer.composer.scaleRatio = 1;
  66903. viewer.composer.readTarget = false;
  66904. viewer.mainViewport.camera.near = 0.05; // too small will result in z-fighting
  66905. viewer.addEventListener('updateModelBound', e => {
  66906. if (this.split) {
  66907. this.SplitScreen.updateCameraOutOfModel( /* this.selected && [this.selected] */);
  66908. }
  66909. });
  66910. {
  66911. //校准页面拖拽
  66912. //左右屏都可以拖拽模型,旋转只能左屏
  66913. var dragInfo;
  66914. var drag = e => {
  66915. if (this.split && this.selected && this.transformState && (e.dragViewport.name == 'top' || this.transformState == 'translate')) {
  66916. if (e.type == 'global_mousedown') {
  66917. //开始
  66918. //if((e.intersect.object || e.intersect.pointcloud) == this.selected){
  66919. if (e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e => e.object == this.selected)) {
  66920. dragInfo = {};
  66921. //if(this.selected.isPointcloud){
  66922. viewer.outlinePass.edgeStrength = 0; //暂时消失线
  66923. //}
  66924. }
  66925. }
  66926. if (e.type == 'global_drag' && dragInfo) {
  66927. if (this.transformState == 'translate') {
  66928. var moveVec = Potree.Utils.getOrthoCameraMoveVec(e.drag.pointerDelta, e.dragViewport.camera); //最近一次移动向量
  66929. this.selected.position.add(moveVec);
  66930. this.selected.dispatchEvent("position_changed");
  66931. } else if (this.transformState == 'rotate') {
  66932. var vec = new Vector3().subVectors(e.intersect.orthoIntersect || e.intersect.location, this.selected.boundCenter).setZ(0);
  66933. if (dragInfo.lastVec == void 0) {
  66934. //global_mousedown
  66935. dragInfo.lastVec = vec;
  66936. return;
  66937. }
  66938. var angle = math.getAngle(dragInfo.lastVec, vec, 'z');
  66939. dragInfo.lastVec = vec;
  66940. //this.selected.rotation.z += angle //局部
  66941. /* object.quaternion.copy( .setFromAxisAngle( new THREE.Vector3(0,0,1), angle ) );
  66942. object.quaternion.multiply( quaternionStart ).normalize(); */
  66943. var diffQua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), angle);
  66944. this.selected.quaternion.premultiply(diffQua); //世界
  66945. this.selected.dispatchEvent("rotation_changed");
  66946. }
  66947. return {
  66948. stopContinue: true
  66949. };
  66950. }
  66951. }
  66952. };
  66953. viewer.addEventListener('global_mousedown', drag);
  66954. viewer.addEventListener('global_drag', drag, {
  66955. importance: 10
  66956. });
  66957. viewer.addEventListener('global_mousemove', e => {
  66958. if (this.split && this.transformState && !e.drag && (e.hoverViewport.name == 'top' || this.transformState == 'translate')) {
  66959. /* if(this.lastHoverViewport != e.hoverViewport){
  66960. this.lastHoverViewport = e.hoverViewport
  66961. this.transformControls.view = e.hoverViewport.view
  66962. this.transformControls.camera = e.hoverViewport.camera
  66963. this.transformControls.hideAxis( this.transformState, e.hoverViewport.name == 'top' ? [z] : [x,y]);
  66964. } */
  66965. var mouseover = e.intersect.pointclouds.includes(this.selected) || e.intersect.allElements.some(e => e.object == this.selected);
  66966. //let mouseover = (e.intersect.object || e.intersect.pointcloud) == this.selected
  66967. if (mouseover) {
  66968. if (this.transformState == 'translate') {
  66969. viewer.dispatchEvent({
  66970. type: "CursorChange",
  66971. action: "add",
  66972. name: "movePointcloud"
  66973. });
  66974. } else {
  66975. viewer.dispatchEvent({
  66976. type: "CursorChange",
  66977. action: "add",
  66978. name: "rotatePointcloud"
  66979. });
  66980. }
  66981. } else {
  66982. this.clearTranCursor();
  66983. }
  66984. }
  66985. });
  66986. viewer.addEventListener('global_drop', e => {
  66987. dragInfo = null;
  66988. this.clearTranCursor();
  66989. //this.updateEdgeStrength()
  66990. viewer.outlinePass.edgeStrength = oriEdgeStrength;
  66991. });
  66992. }
  66993. /* viewer.addEventListener('background_changed',()=>{
  66994. }) */
  66995. viewer.addEventListener('camera_changed', () => {
  66996. Common.intervalTool.isWaiting('updateMemoryUsage', () => {
  66997. this.updateMemoryUsage();
  66998. }, 1000);
  66999. });
  67000. viewer.addEventListener('setDisplay', this.updateMemoryUsage.bind(this));
  67001. },
  67002. clearTranCursor() {
  67003. viewer.dispatchEvent({
  67004. type: "CursorChange",
  67005. action: "remove",
  67006. name: "movePointcloud"
  67007. });
  67008. viewer.dispatchEvent({
  67009. type: "CursorChange",
  67010. action: "remove",
  67011. name: "rotatePointcloud"
  67012. });
  67013. },
  67014. enterSplit() {
  67015. this.split = true;
  67016. if (this.selected) this.SplitScreen.focusCenter = this.selected.boundCenter; //旋转中心。注意 boundCenter不能直接赋值,否则改变后focusCenter也要改
  67017. else this.SplitScreen.focusCenter = null;
  67018. this.SplitScreen.splitStart(viewportProps$1);
  67019. this.beforeSplit = {
  67020. pointDensity: Potree.settings.pointDensity
  67021. };
  67022. Potree.settings.pointDensity = 'fourViewports'; //强制降低点云质量
  67023. viewer.setControls(viewer.fpControls);
  67024. var rightViewport = viewer.viewports.find(e => e.name == 'right');
  67025. var topViewport = viewer.viewports.find(e => e.name == 'top');
  67026. topViewport.alignment = true;
  67027. rightViewport.rotateSide = true;
  67028. rightViewport.skyboxFixPos = true;
  67029. rightViewport.skyboxMinZoom = 10;
  67030. rightViewport.skyboxRenderFun = () => {
  67031. // 使cube的一面永远正向镜头。 因侧视图的camera是ortho类型,需要平视mesh才不会拉伸
  67032. viewer.skybox.scene.children[0].rotation.copy(rightViewport.camera.rotation);
  67033. };
  67034. topViewport.skyboxRenderFun = () => {
  67035. viewer.skybox.scene.children[0].rotation.set(0, 0, 0);
  67036. };
  67037. viewer.viewports[1].layersAdd('layer2');
  67038. viewer.viewports[0].layersAdd('layer1');
  67039. Potree.Utils.setObjectLayers(this.transformControls, 'layer1');
  67040. this.transformControls.view = viewer.viewports[0].view;
  67041. this.transformControls.camera = viewer.viewports[0].camera;
  67042. this.transformControls._gizmo.hideAxis = {
  67043. translate: ['z'],
  67044. rotate: ['x', 'y', 'z']
  67045. };
  67046. this.transformControls2.view = viewer.viewports[1].view;
  67047. this.transformControls2.camera = viewer.viewports[1].camera;
  67048. this.transformControls2._gizmo.hideAxis = {
  67049. translate: ['x', 'y'],
  67050. rotate: ['x', 'y', 'z']
  67051. };
  67052. this.secondCompass.changeViewport(viewer.viewports[0]);
  67053. this.secondCompass.setDomPos();
  67054. this.secondCompass.setDisplay(true);
  67055. viewer.compass.changeViewport(viewer.viewports[1]);
  67056. viewer.compass.setDomPos();
  67057. //this.changeSkyboxGeo(true)
  67058. },
  67059. leaveSplit() {
  67060. this.split = false;
  67061. this.SplitScreen.unSplit();
  67062. viewer.setControls(viewer.orbitControls);
  67063. Potree.settings.pointDensity = this.beforeSplit.pointDensity;
  67064. /* if(this.selected && this.selected.isPointcloud){
  67065. this.showModelOutline(this.selected, true)
  67066. this.selected.material.activeAttributeName = "rgba"
  67067. } */
  67068. this.transformControls.camera = viewer.viewports[0].camera;
  67069. this.transformControls.view = viewer.viewports[0].view;
  67070. this.transformControls._gizmo.hideAxis = {
  67071. rotate: ['e']
  67072. };
  67073. Potree.Utils.setObjectLayers(this.transformControls, 'sceneObjects'); //恢复
  67074. viewer.compass.changeViewport(viewer.viewports[0]); //恢复
  67075. viewer.compass.setDomPos();
  67076. this.secondCompass.setDisplay(false);
  67077. },
  67078. rotateSideCamera(angle) {
  67079. this.SplitScreen.rotateSideCamera(viewer.viewports.find(e => e.name == 'right'), angle);
  67080. },
  67081. setTransformState(state) {
  67082. //校准时
  67083. this.transformState = state;
  67084. this.clearTranCursor();
  67085. },
  67086. //---------------------------
  67087. getAllObjects() {
  67088. return viewer.objs.children.concat(viewer.scene.pointclouds);
  67089. },
  67090. getModel(id) {
  67091. var models = this.getAllObjects();
  67092. return models.find(e => e.dataset_id == id);
  67093. },
  67094. removeModel(model) {
  67095. if (this.selected == model) this.selectModel(null);
  67096. var dispose = e => {
  67097. e.geometry && e.geometry.dispose();
  67098. e.material && e.material.dispose();
  67099. };
  67100. if (model.isPointcloud) {
  67101. dispose(model);
  67102. viewer.scene.removePointCloud(model);
  67103. } else {
  67104. model.traverse(e => {
  67105. dispose(e);
  67106. });
  67107. viewer.objs.remove(model);
  67108. this.updateMemoryUsage();
  67109. }
  67110. },
  67111. selectModel(model) {
  67112. var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  67113. var fitBound = arguments.length > 2 ? arguments[2] : undefined;
  67114. var by2d = arguments.length > 3 ? arguments[3] : undefined;
  67115. if (!model) {
  67116. model = this.selected;
  67117. state = false;
  67118. }
  67119. if (state) {
  67120. if (this.selected) {
  67121. if (this.selected == model) return;else {
  67122. var transToolAttached = !!this.transformControls.object;
  67123. this.selectModel(this.selected, false, fitBound, by2d);
  67124. transToolAttached && this.transformControls.attach(model);
  67125. }
  67126. }
  67127. this.selected = model;
  67128. MergeEditor.focusOn(model, 500, !!fitBound); //通过在场景里点击模型的话,不focus
  67129. this.showModelOutline(model);
  67130. //this.updateEdgeStrength()
  67131. //console.log('selectModel', model)
  67132. } else {
  67133. if (this.selected != model) return; //model本来就没选中,不需要处理(防止2d先选中新的再取消旧的)
  67134. this.showModelOutline(model, false);
  67135. this.selected = null;
  67136. this.transformControls.detach(); //viewer.transformObject(null);
  67137. //console.log('selectModel', null)
  67138. }
  67139. if (!by2d && model) {
  67140. model.dispatchEvent({
  67141. type: 'changeSelect',
  67142. selected: state
  67143. });
  67144. }
  67145. },
  67146. showModelOutline(model, state) {
  67147. if (this.fadeOutlineAuto) {
  67148. if (state === false) {
  67149. viewer.outlinePass.selectedObjects = [];
  67150. clearTimeout(this.timer);
  67151. return;
  67152. }
  67153. viewer.outlinePass.selectedObjects = [model];
  67154. if (this.timer) {
  67155. clearTimeout(this.timer);
  67156. }
  67157. this.timer = setTimeout(() => {
  67158. viewer.outlinePass.selectedObjects = [];
  67159. viewer.dispatchEvent('content_changed');
  67160. }, 1000);
  67161. } else {
  67162. if (state === false) {
  67163. viewer.outlinePass.selectedObjects = [];
  67164. } else {
  67165. viewer.outlinePass.selectedObjects = [model];
  67166. }
  67167. }
  67168. viewer.dispatchEvent('content_changed');
  67169. },
  67170. /*updateEdgeStrength(){
  67171. if(!this.selected)return
  67172. if(this.selected.isPointcloud){
  67173. viewer.outlinePass.edgeStrength = edgeStrengths.pointcloud// / this.selected.material.opacity
  67174. }else{
  67175. viewer.outlinePass.edgeStrength = edgeStrengths.glb
  67176. }
  67177. },*/
  67178. focusOn(objects) {
  67179. var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 400;
  67180. var fitBound = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  67181. var dontLookUp = arguments.length > 3 ? arguments[3] : undefined;
  67182. if (!(objects instanceof Array)) {
  67183. objects = [objects];
  67184. }
  67185. var boundingBox = new Box3();
  67186. objects.forEach(object => {
  67187. boundingBox.union(object.boundingBox.clone().applyMatrix4(object.matrixWorld));
  67188. });
  67189. var len = boundingBox.getSize(new Vector3()).length();
  67190. Potree.settings.cameraFar = Math.max(Potree.settings.cameraFar, len * 3);
  67191. if (fitBound) {
  67192. viewer.focusOnObject({
  67193. boundingBox
  67194. }, 'boundingBox', duration, {
  67195. dontLookUp,
  67196. dontChangeCamDir: true
  67197. });
  67198. } else {
  67199. /*
  67200. let position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new THREE.Vector3)
  67201. position && viewer.focusOnObject({position}, 'point', duration, {dontChangePos: true})
  67202. */
  67203. var position = viewer.inputHandler.intersect ? viewer.inputHandler.intersect.location : boundingBox.getCenter(new Vector3());
  67204. if (!position) return;
  67205. /* let targetOld = viewer.mainViewport.view.getPivot()
  67206. let projected1 = targetOld.clone().project(viewer.mainViewport.camera);
  67207. let projected2 = position.clone().project(viewer.mainViewport.camera); //使用其z
  67208. let targetNew = projected1.clone().setZ(projected2.z).unproject(viewer.mainViewport.camera);
  67209. viewer.mainViewport.view.lookAt(targetNew) */
  67210. viewer.mainViewport.view.radius = viewer.mainViewport.camera.position.distanceTo(position);
  67211. //为了不改画面,不调节方向了,只能调调radius,一定程度将target靠近model
  67212. }
  67213. },
  67214. moveBoundCenterTo(model, pos) {
  67215. //使boundCenter在所要的位置
  67216. var diff = new Vector3().subVectors(pos, model.boundCenter);
  67217. model.position.add(diff);
  67218. },
  67219. getBoundCenter(model) {
  67220. if (!model.boundCenter) model.boundCenter = new Vector3();
  67221. model.boundingBox.getCenter(model.boundCenter).applyMatrix4(model.matrixWorld);
  67222. },
  67223. setModelBtmHeight(model, z) {
  67224. //无论模型怎么缩放、旋转,都使最低点为z
  67225. if (z == void 0) z = model.btmHeight; //维持离地高度
  67226. else model.btmHeight = z;
  67227. if (model.btmHeight == void 0) return;
  67228. model.updateMatrixWorld();
  67229. var boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  67230. var size = boundingBox2.getSize(new Vector3());
  67231. var center = boundingBox2.getCenter(new Vector3());
  67232. var hopeZ = z + size.z / 2;
  67233. //model.position.z = z + size.z / 2 - center.z
  67234. model.position.z += hopeZ - center.z;
  67235. },
  67236. computeBtmHeight(model) {
  67237. //位移之后重新计算btmHeight
  67238. model.updateMatrixWorld();
  67239. var boundingBox2 = model.boundingBox.clone().applyMatrix4(model.matrixWorld);
  67240. var size = boundingBox2.getSize(new Vector3());
  67241. var center = boundingBox2.getCenter(new Vector3());
  67242. model.btmHeight = center.z - size.z / 2;
  67243. },
  67244. maintainBoundXY(model) {
  67245. //在旋转和缩放后,立即执行这个函数,使boundCenter保持原位
  67246. model.updateMatrixWorld();
  67247. var center1 = model.boundCenter.clone(); //还未更新的
  67248. this.getBoundCenter(model); //更新
  67249. var center2 = model.boundCenter.clone();
  67250. var diff = new Vector2().subVectors(center1, center2);
  67251. model.position.x += diff.x;
  67252. model.position.y += diff.y;
  67253. model.boundCenter.copy(center1);
  67254. },
  67255. maintainBoundCenter(model) {
  67256. model.updateMatrixWorld();
  67257. var center1 = model.boundCenter.clone(); //还未更新的
  67258. this.getBoundCenter(model); //更新
  67259. var center2 = model.boundCenter.clone();
  67260. var diff = new Vector3().subVectors(center1, center2);
  67261. model.position.add(diff);
  67262. model.boundCenter.copy(center1);
  67263. },
  67264. modelTransformCallback(model) {
  67265. model.updateMatrixWorld();
  67266. if (model.matrixWorld.equals(model.lastMatrixWorld)) return;
  67267. viewer.scene.measurements.forEach(measure => {
  67268. var changed;
  67269. measure.points_datasets.forEach((dataset_id, i) => {
  67270. if (dataset_id == model.dataset_id) {
  67271. changed = true;
  67272. measure.points[i] = Potree.Utils.datasetPosTransform({
  67273. fromDataset: true,
  67274. datasetId: dataset_id,
  67275. position: measure.dataset_points[i].clone()
  67276. });
  67277. measure.updateMarker(measure.markers[i], measure.points[i]);
  67278. }
  67279. });
  67280. if (changed) {
  67281. //仿transformByPointcloud
  67282. measure.getPoint2dInfo(measure.points);
  67283. measure.update();
  67284. measure.setSelected(false); //隐藏edgelabel
  67285. }
  67286. });
  67287. model.lastMatrixWorld = model.matrixWorld.clone();
  67288. viewer.dispatchEvent('content_changed');
  67289. viewer.mapViewer && Potree.settings.showObjectsOnMap && viewer.mapViewer.dispatchEvent('content_changed');
  67290. },
  67291. changeOpacity(model, opacity) {
  67292. var isRoot = model.dataset_id != void 0; //是否是最外层
  67293. if (model.isPointcloud) {
  67294. model.changePointOpacity(opacity);
  67295. //MergeEditor.updateEdgeStrength()
  67296. } else {
  67297. //model.traverse(e=>e.material && setOp(e, opacity))
  67298. model.traverse(mesh => {
  67299. if (mesh.material) {
  67300. if (mesh.material.originOpacity == void 0) {
  67301. mesh.material.originOpacity = mesh.material.opacity;
  67302. }
  67303. mesh.material.opacity = mesh.material.originOpacity * opacity;
  67304. if (mesh.material.opacity < 1) {
  67305. mesh.material.transparent = true;
  67306. /* if(model.isPointcloud){
  67307. mesh.changePointOpacity(realOpacity)
  67308. }else{
  67309. mesh.material.opacity = realOpacity
  67310. } */
  67311. mesh.renderOrder = Potree.config.renderOrders.model + 1;
  67312. //mesh.material.depthWrite = false
  67313. } else {
  67314. mesh.material.transparent = false;
  67315. mesh.renderOrder = Potree.config.renderOrders.model;
  67316. //mesh.material.depthWrite = true
  67317. }
  67318. mesh.material.depthWrite = mesh.material.opacity > 0.3;
  67319. }
  67320. });
  67321. }
  67322. isRoot && (model.opacity = opacity); //记录在最外层
  67323. viewer.dispatchEvent('content_changed');
  67324. },
  67325. modelAdded(model) {
  67326. model.addEventListener('isVisible', e => {
  67327. if (e.reason == "overlinePass") return;
  67328. //console.log(e)
  67329. viewer.addEventListener('update', () => {
  67330. //下一次更新结束后
  67331. this.updateMemoryUsage();
  67332. }, {
  67333. once: true
  67334. });
  67335. });
  67336. this.updateMemoryUsage();
  67337. },
  67338. updateMemoryUsage() {
  67339. //obj暂时不管其贴图大小, 因为顶点造成的不仅是内存还有卡顿所以先只看顶点
  67340. var maxMemory = Potree.config.tiles3DMaxMemory + 100; //M 实际估计是这个的10倍
  67341. var eachObjPosWeight = 100 / 1000 / 1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图
  67342. var eachCloudPointWeight = 12 / 1000 / 1000; //M 每个点 pos + 颜色 + 法线 大概
  67343. var eachVisiCPointWeight = eachCloudPointWeight * 5; // 或 maxMemory / (6*1000*1000) 大概值接近 (再除以一个数是因为显示的要比内存中的耗更多资源
  67344. var eachGltfPosWeight = 100 / 1000 / 1000; //M 每个顶点pos是3*4个字节?法线3*4和uv2*4 其实还有贴图
  67345. var posCount = 0;
  67346. viewer.objs.children.forEach(e => {
  67347. if (e.fileType == 'glb' || e.fileType == 'obj') {
  67348. e.traverse(mesh => {
  67349. if (mesh.geometry) {
  67350. posCount += mesh.geometry.attributes.position.count;
  67351. }
  67352. });
  67353. } else if (e.fileType == '3dTiles') {}
  67354. });
  67355. //获取点云的内存限制
  67356. var objWeight = posCount * eachObjPosWeight;
  67357. var laserWeight = Potree.numVisiblePoints * eachCloudPointWeight; //点云实际显示所占大小
  67358. var laserMemoryWeight = Potree.lru.numPoints * eachCloudPointWeight; //点云所使用内存大小
  67359. var tiles3DWeight = viewer.tiles3dVisiVCount * eachGltfPosWeight; //M 3dTiles所占内存大小
  67360. var tiles3DMemoryWeight = viewer.tiles3dMemoryUsage / 1000 / 1000; //M 3dTiles显示的所占内存大小
  67361. /* let min = 0.1, max = 6, minP = 100, maxP = 1000000;
  67362. let ratio = Math.round(math.linearClamp(score, minP, maxP, max, min )); */
  67363. var rest = maxMemory - objWeight - tiles3DWeight;
  67364. Potree.pointBudget = Math.max(30000, Math.round(rest / eachVisiCPointWeight));
  67365. //获取3dTiles的内存限制
  67366. var tiles3DMaxMemory = maxMemory - Math.round(objWeight + laserWeight);
  67367. Potree.settings.tiles3DMaxMemory = MathUtils.clamp(tiles3DMaxMemory, 30, Potree.config.tiles3DMaxMemory);
  67368. //还存在的问题:仍然有隐患,因为没用到真实缓存的大小: tiles3DMemoryWeight laserMemoryWeight, 它们比真实可见的要多。不使用是因为它们无法反应出实际需要的内存量,缓存是只增不减
  67369. //obj等普通mesh限制不了
  67370. //console.log('objWeight',objWeight.toFixed(1), 'laserMemoryWeight',laserMemoryWeight.toFixed(1), 'tiles3DWeight',tiles3DWeight.toFixed(1), 'pointBudget',Potree.pointBudget, 'tiles3DMaxMemory',tiles3DMaxMemory)
  67371. //总内存 = 内存占用空间+图片缓存 , obj的缓存比较多在图片中
  67372. },
  67373. setGroundPlaneImg(src, scale, angle) {
  67374. //设置地面图
  67375. this.goundScale = scale || 1, this.goundAngle = angle || 0;
  67376. var oldSrc = this.curGroundImgSrc;
  67377. this.curGroundImgSrc = src;
  67378. var ratio = 0.03;
  67379. if (src) {
  67380. if (oldSrc == src && this.groundPlane.material.map.image) {
  67381. //仅修改大小
  67382. var s = ratio * this.goundScale;
  67383. var {
  67384. width,
  67385. height
  67386. } = this.groundPlane.material.map.image;
  67387. this.groundPlane.scale.set(width * s, height * s);
  67388. viewer.dispatchEvent('content_changed');
  67389. this.groundPlane.rotation.z = MathUtils.degToRad(this.goundAngle);
  67390. return;
  67391. }
  67392. var map = texLoader$a.load(src, tex => {
  67393. if (this.curGroundImgSrc == src) {
  67394. var _s = ratio * this.goundScale;
  67395. this.groundPlane.scale.set(tex.image.width * _s, tex.image.height * _s);
  67396. this.groundPlane.rotation.z = MathUtils.degToRad(this.goundAngle);
  67397. viewer.dispatchEvent('content_changed');
  67398. }
  67399. });
  67400. Potree.Utils.makeTexDontResize(map);
  67401. if (!this.groundPlane) {
  67402. this.groundPlane = new Mesh(new PlaneBufferGeometry(1, 1, 1), new MeshBasicMaterial({
  67403. map,
  67404. side: 2
  67405. }));
  67406. viewer.scene.scene.add(this.groundPlane);
  67407. this.groundPlane.position.z = 0.1;
  67408. } else {
  67409. this.groundPlane.material.map = map;
  67410. }
  67411. Potree.Utils.updateVisible(this.groundPlane, 'show', true);
  67412. } else {
  67413. this.groundPlane && Potree.Utils.updateVisible(this.groundPlane, 'show', false);
  67414. }
  67415. }
  67416. };
  67417. /*
  67418. note:
  67419. 要注意getHoveredElements只在getIntersect时才使interactables包含加载的model, 也就是model上不能有使之成为interactables的事件,否则在鼠标hover到模型上开始转动的一瞬间很卡。
  67420. */
  67421. var texLoader$b = new TextureLoader();
  67422. var arrowSpacing = 1; //间隔
  67423. var arrowSize = arrowSpacing * 0.5;
  67424. var planeGeo$3 = new PlaneBufferGeometry(1, 1);
  67425. var sphereSizeInfo = {
  67426. nearBound: 0.1,
  67427. farBound: 25,
  67428. minSize: 50,
  67429. maxSize: 200 //scale:arrowSize, restricMeshScale : true,
  67430. };
  67431. //const arrowsShowingCount = 25; //场景里最多展示多少个箭头
  67432. var arrowShowMinDis = 10;
  67433. class RouteGuider extends EventDispatcher {
  67434. constructor() {
  67435. super();
  67436. this.route = [];
  67437. this.curve = [];
  67438. this.scenePoints = [];
  67439. this.sceneMeshGroup = new Object3D();
  67440. this.mapMeshGroup = new Object3D();
  67441. this.generateDeferred;
  67442. viewer.addEventListener('loadPointCloudDone', this.init.bind(this));
  67443. this.lastResult; //保存上一个的结果,以便于反向
  67444. this.datasetIds = []; //起始和终点的datasetId
  67445. }
  67446. init() {
  67447. if (this.inited) return;
  67448. var zoom,
  67449. resolution = new Vector2();
  67450. viewer.mapViewer.addEventListener('camera_changed', e => {
  67451. if (!this.routeStart || !this.routeEnd) return;
  67452. var camera = e.viewport.camera;
  67453. if (camera.zoom != zoom || !resolution.equals(e.viewport.resolution)) {
  67454. Common.intervalTool.isWaiting('routeCameraInterval', () => {
  67455. //延时update,防止卡顿
  67456. if (camera.zoom != zoom || !resolution.equals(e.viewport.resolution)) {
  67457. //console.log('updateMapArrows')
  67458. this.updateMapArrows(true);
  67459. zoom = camera.zoom;
  67460. resolution.copy(e.viewport.resolution);
  67461. }
  67462. }, browser.isMobile() ? 500 : 200);
  67463. }
  67464. });
  67465. viewer.addEventListener('camera_changed', e => {
  67466. if (!this.routeStart || !this.routeEnd || !e.changeInfo.positionChanged) return;
  67467. Common.intervalTool.isWaiting('routeCameraInterval2', () => {
  67468. //延时update,防止卡顿
  67469. this.updateArrowDisplay();
  67470. }, 1000);
  67471. });
  67472. var polesMats = {
  67473. shadowMat: new MeshBasicMaterial({
  67474. transparent: true,
  67475. depthTest: false,
  67476. map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_bottomMarker.png')
  67477. }),
  67478. sphereMat: new MeshBasicMaterial({
  67479. transparent: true,
  67480. depthTest: false,
  67481. map: texLoader$b.load(Potree.resourcePath + '/textures/whiteCircle.png')
  67482. }),
  67483. hatMats: {
  67484. start: new MeshBasicMaterial({
  67485. transparent: true,
  67486. depthTest: false,
  67487. map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_start_route.png')
  67488. }),
  67489. end: new MeshBasicMaterial({
  67490. transparent: true,
  67491. depthTest: false,
  67492. map: texLoader$b.load(Potree.resourcePath + '/textures/pano_instruction_target_reached.png')
  67493. })
  67494. }
  67495. };
  67496. polesMats.shadowMat.map.anisotropy = 4;
  67497. this.poleStart = this.createPole(polesMats, 'start');
  67498. this.poleEnd = this.createPole(polesMats, 'end');
  67499. this.sceneMeshGroup.add(this.poleStart);
  67500. this.sceneMeshGroup.add(this.poleEnd);
  67501. var map = texLoader$b.load(Potree.resourcePath + '/textures/routePoint_panorama.png');
  67502. map.anisotropy = 4; // 各向异性过滤 .防止倾斜模糊
  67503. this.arrow = new Mesh(planeGeo$3, new MeshBasicMaterial({
  67504. transparent: true,
  67505. depthTest: false,
  67506. map
  67507. }));
  67508. this.arrow.scale.set(arrowSize, arrowSize, arrowSize);
  67509. Potree.Utils.setObjectLayers(this.arrow, 'sceneObjects');
  67510. /* this.testArrow = this.arrow.clone();
  67511. this.testArrow.material = this.arrow.material.clone()
  67512. this.testArrow.material.color = 'red' */
  67513. this.arrows = new Object3D();
  67514. this.sceneMeshGroup.add(this.arrows);
  67515. Potree.Utils.setObjectLayers(this.sceneMeshGroup, 'sceneObjects');
  67516. //this.sceneMeshGroup.traverse(e=>e.renderOrder = 90)
  67517. viewer.scene.scene.add(this.sceneMeshGroup);
  67518. this.sceneMeshGroup.visible = false;
  67519. this.poleStart.visible = false;
  67520. this.poleEnd.visible = false;
  67521. //-------------map---------------------
  67522. /* this.mapMarkStart = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  67523. transparent:true, depthTest:false,
  67524. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_start_route.png' )
  67525. }))
  67526. this.mapMarkEnd = new THREE.Mesh( planeGeo, new THREE.MeshBasicMaterial({
  67527. transparent:true, depthTest:false,
  67528. map: texLoader.load(Potree.resourcePath+'/textures/map_instruction_target_reached.png' )
  67529. }))
  67530. this.mapMarkStart.renderOrder = this.mapMarkEnd.renderOrder = 2//在箭头之上 */
  67531. var map2 = texLoader$b.load(Potree.resourcePath + '/textures/routePoint_map_fsna.png');
  67532. this.mapArrowMats = {
  67533. default: new MeshBasicMaterial({
  67534. transparent: true,
  67535. depthTest: false,
  67536. map: map2
  67537. }),
  67538. fade: new MeshBasicMaterial({
  67539. transparent: true,
  67540. depthTest: false,
  67541. map: map2,
  67542. opacity: 0.4
  67543. })
  67544. };
  67545. this.mapArrow = new Mesh(planeGeo$3, this.mapArrowMats.default);
  67546. this.mapArrow.scale.set(arrowSize, arrowSize, arrowSize);
  67547. this.mapArrows = new Object3D();
  67548. this.mapArrows.name = 'mapArrows';
  67549. this.mapMeshGroup.add(this.mapArrows);
  67550. this.mapMeshGroup.name = 'mapRouteLayer';
  67551. this.mapMeshGroup.visible = false;
  67552. viewer.mapViewer.dispatchEvent({
  67553. type: 'add',
  67554. object: this.mapMeshGroup,
  67555. name: 'route'
  67556. });
  67557. this.mapArrow.layers.mask = this.mapArrows.layers.mask; // 修改成和map中的layer一样的
  67558. viewer.modules.SiteModel.bus.addEventListener('FloorChange', () => {
  67559. if (this.routeStart && this.routeEnd) {
  67560. this.updateOpacityAtMap();
  67561. }
  67562. });
  67563. this.inited = true;
  67564. }
  67565. updateOpacityAtMap() {
  67566. //只有当前楼层的透明度为1
  67567. var currentFloor = viewer.modules.SiteModel.currentFloor;
  67568. //console.log('updateOpacityAtMap', currentFloor && currentFloor.name)
  67569. var lift = 0.3; // 因为发送请求时用的是floorPosition的高度,而它可能会到画好的floor之下,所以有误差
  67570. this.mapArrows.children.forEach((arrow, index) => {
  67571. var pos = this.mapPoints[index].clone();
  67572. pos.z += lift;
  67573. var inSide = currentFloor && currentFloor.ifContainsPoint(pos);
  67574. arrow.material = inSide ? this.mapArrowMats.default : this.mapArrowMats.fade;
  67575. //console.log('arrow',index, arrow.material.opacity)
  67576. });
  67577. viewer.mapViewer.dispatchEvent('content_changed');
  67578. } //但是如果楼层刚好只框柱相机位置而没框住地面位置就不好了……
  67579. createPole(polesMats, name) {
  67580. var height = 1.5,
  67581. sphereCount = 6,
  67582. shadowSize = 0.5 /* sphereSizeInfo.scale */,
  67583. sphereSize = 0.05;
  67584. var group = new Object3D();
  67585. group.name = 'pole_' + name;
  67586. var shadow = new Mesh(planeGeo$3, polesMats.shadowMat);
  67587. shadow.scale.set(shadowSize, shadowSize, shadowSize);
  67588. var sliceDis = height / (sphereCount + 1);
  67589. group.add(shadow);
  67590. for (var i = 0; i < sphereCount; i++) {
  67591. var sphere = new Sprite$2({
  67592. mat: polesMats.sphereMat,
  67593. renderOrder: 3
  67594. });
  67595. sphere.position.set(0, 0, sliceDis * (i + 1));
  67596. sphere.scale.set(sphereSize, sphereSize, sphereSize);
  67597. //sphere.visible = false
  67598. group.add(sphere);
  67599. }
  67600. var hatSphere = new Sprite$2({
  67601. mat: polesMats.hatMats[name],
  67602. sizeInfo: sphereSizeInfo,
  67603. renderOrder: 4
  67604. });
  67605. //sphere.visible = false
  67606. hatSphere.position.set(0, 0, height);
  67607. hatSphere.scale.copy(shadow.scale);
  67608. group.add(hatSphere);
  67609. group.hatSphere = hatSphere;
  67610. return group;
  67611. }
  67612. addTestArrow() {}
  67613. addArrow(position) {
  67614. var arrow = this.arrow.clone();
  67615. arrow.position.copy(position);
  67616. this.arrows.add(arrow);
  67617. }
  67618. addMapArrow(position) {
  67619. var mapArrow = this.mapArrow.clone();
  67620. mapArrow.position.copy(position).setZ(0);
  67621. this.mapArrows.add(mapArrow);
  67622. }
  67623. setArrowDir(arrows, index) {
  67624. var arrow = arrows[index];
  67625. var nextOne = arrows[index + 1];
  67626. var nextPos = nextOne ? nextOne.position : this.endPolePos; //routeEnd
  67627. var direction = new Vector3().subVectors(arrow.position, nextPos).setZ(0);
  67628. //direction.normalize();
  67629. //console.log(direction.toArray())
  67630. var angle = Math.atan2(direction.y, direction.x) + Math.PI / 2; //Math.PI/2是因为贴图本身箭头方向不朝x
  67631. arrow.rotation.z = angle;
  67632. //console.log(angle)
  67633. }
  67634. setRouteStart(pos, dealZ, datasetId) {
  67635. if (this.routeStart && pos && this.routeStart.equals(pos)) return; //可能重复设置
  67636. this.routeStart = pos && new Vector3().copy(pos);
  67637. if (dealZ && this.routeStart) {
  67638. this.routeStart.setZ(this.getZAtMap());
  67639. this.bus && this.bus.emit('reposStartMarker', this.routeStart);
  67640. }
  67641. console.log('setRouteStart', this.routeStart && this.routeStart.toArray());
  67642. this.datasetIds[0] = datasetId;
  67643. //this.setStartPole(pos)
  67644. this.poleStart.visible = !!pos;
  67645. pos && this.poleStart.position.copy(this.routeStart);
  67646. pos && this.poleStart.hatSphere.waitUpdate();
  67647. this.generateRoute();
  67648. viewer.dispatchEvent('content_changed');
  67649. }
  67650. setStartPole(pos) {
  67651. this.startPolePos = pos;
  67652. this.bus && this.bus.emit('reposStartMarker', pos);
  67653. }
  67654. setRouteEnd(pos, dealZ, datasetId) {
  67655. if (this.routeEnd && pos && this.routeEnd.equals(pos)) return;
  67656. this.routeEnd = pos && new Vector3().copy(pos);
  67657. if (dealZ && this.routeEnd) {
  67658. this.routeEnd.setZ(this.getZAtMap());
  67659. this.bus && this.bus.emit('reposEndMarker', this.routeEnd);
  67660. }
  67661. console.log('setRouteEnd', this.routeEnd && this.routeEnd.toArray());
  67662. this.datasetIds[1] = datasetId;
  67663. //this.setEndPole(pos)
  67664. this.poleEnd.visible = !!pos;
  67665. pos && this.poleEnd.position.copy(this.routeEnd);
  67666. pos && this.poleEnd.hatSphere.waitUpdate();
  67667. this.generateRoute();
  67668. viewer.dispatchEvent('content_changed');
  67669. }
  67670. getZAtMap() {
  67671. //找到position.z与当前高度最接近的漫游点
  67672. var result = Common.sortByScore(viewer.images360.panos, [], [e => -Math.abs(e.position.z - viewer.images360.position.z)]);
  67673. var pano = result && result[0] && result[0].item;
  67674. return pano ? pano.floorPosition.z : viewer.bound.boundingBox.min.z + 1;
  67675. //若在平面图上画实在得不到当前楼层的,大概率是楼层画得不好,那就只能去获取当前楼层的了
  67676. //navvis的高度取的是主视图所在楼层的中心高度(可能再高些)
  67677. }
  67678. setEndPole(pos) {
  67679. this.endPolePos = pos;
  67680. this.bus && this.bus.emit('reposEndMarker', pos);
  67681. }
  67682. getSourceProjectionIndex(route) {
  67683. //真正的起始
  67684. var e = route.findIndex(function (t) {
  67685. return t.instruction && t.instruction.type === 'source_projection_to_navgraph';
  67686. });
  67687. return e < 0 ? 0 : e;
  67688. }
  67689. getDestinationProjectionIndex(route) {
  67690. //真正的终点
  67691. var e = route.findIndex(function (t) {
  67692. return t.instruction && t.instruction.type === "destination_projection_to_navgraph";
  67693. });
  67694. return e < 0 ? route.length - 1 : e;
  67695. }
  67696. generateRoute() {
  67697. this.sceneMeshGroup.visible = true;
  67698. if (!this.routeStart || !this.routeEnd) {
  67699. return;
  67700. }
  67701. var initialPointcloud = viewer.scene.pointclouds.find(e => e.dataset_id == Potree.settings.originDatasetId);
  67702. //array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  67703. var create = () => {
  67704. this.routeLength = this.route.reduce((total, currentValue, currentIndex, arr) => {
  67705. if (currentIndex == 0) return 0;
  67706. return total + currentValue.distanceTo(arr[currentIndex - 1]);
  67707. }, 0);
  67708. var count = Math.max(2, Math.round(this.routeLength / arrowSpacing)); //点数
  67709. var curve = new CatmullRomCurve3(this.route);
  67710. curve.curveType = 'chordal'; //'centripetal' 'catmullrom'这个可能会超出路径外
  67711. this.curve = curve;
  67712. var scenePoints = curve.getSpacedPoints(count); //更平均
  67713. //const scenePoints = curve.getPoints( count );
  67714. scenePoints.splice(0, 1); //去掉首尾
  67715. scenePoints.pop();
  67716. this.scenePoints = scenePoints;
  67717. this.updateMapArrows();
  67718. this.displayRoute();
  67719. {
  67720. //map focus on this area
  67721. var minBound = new Vector2(1, 1); //针对垂直线,在地图上只有一个点
  67722. var bound = new Box2();
  67723. this.route.forEach(e => {
  67724. bound.expandByPoint(e);
  67725. });
  67726. var size = bound.getSize(new Vector2());
  67727. var markerSize = new Vector2(115, 40); //起始和终点的标识呈长方形
  67728. var areaSize = viewer.mapViewer.viewports[0].resolution2;
  67729. var areaArea = areaSize.x * areaSize.y;
  67730. if (areaArea > 800 * 400) {
  67731. //是放大的
  67732. markerSize.multiplyScalar(areaArea / (800 * 400) /* / (size.x * size.y) */);
  67733. }
  67734. var margin = size.clone().divide(viewer.mapViewer.viewports[0].resolution2).multiply(markerSize); ///边距 重点是起始和终点的标识占据较大
  67735. size.add(margin);
  67736. var center = bound.getCenter(new Vector2());
  67737. size.x = Math.max(size.x, minBound.x);
  67738. size.y = Math.max(size.y, minBound.y);
  67739. var duration = 1000;
  67740. viewer.mapViewer.moveTo(center, size, duration);
  67741. }
  67742. this.bus.emit('gotResult', {
  67743. dis: this.routeLength
  67744. });
  67745. /* this.generateDeferred && this.generateDeferred.resolve({dis:this.routeLength})
  67746. this.generateDeferred = null */
  67747. };
  67748. if (Potree.fileServer) {
  67749. var dealData = data => {
  67750. if (!data.data) {
  67751. console.log('没有数据');
  67752. var result;
  67753. if (data && data.code == 4002) {
  67754. result = data; //正被修改数据集
  67755. } else if (this.routeStart.distanceTo(this.routeEnd) < 1) {
  67756. result = {
  67757. code: 500,
  67758. msg: '距离太短,无法规划路线'
  67759. };
  67760. } else {
  67761. result = {
  67762. code: 500,
  67763. msg: '超出数据集范围,无法规划路线'
  67764. };
  67765. }
  67766. this.clearRoute();
  67767. this.setStartPole(this.routeStart);
  67768. this.setEndPole(this.routeEnd);
  67769. this.displayRoute(); //还是要显示一下起始
  67770. this.bus && this.bus.emit('gotResult', result);
  67771. return; //this.generateDeferred && this.generateDeferred.resolve()
  67772. }
  67773. data = data.data;
  67774. this.clearRoute();
  67775. var length = data.length;
  67776. if (length < 2) {
  67777. //可能距离太短
  67778. console.log('路径点数为' + length + ',直接取起点和终点连线');
  67779. this.route = [this.routeStart, this.routeEnd];
  67780. } else {
  67781. var startIndex = this.getSourceProjectionIndex(data);
  67782. var endIndex = this.getDestinationProjectionIndex(data);
  67783. var effectiveItems = data.slice(startIndex, endIndex + 1); //只要点云范围内的点
  67784. effectiveItems.forEach((item, i) => {
  67785. //let pos = viewer.transform.lonlatToLocal.forward(item.location.slice(0)/* ,true */)
  67786. var pos = item.location.slice(0);
  67787. pos = new Vector3().fromArray(pos); //.setZ(item.z)
  67788. pos.z -= initialPointcloud.datasetData.location[2];
  67789. this.route.push(pos);
  67790. });
  67791. //console.log('route', this.route)
  67792. }
  67793. this.setStartPole(this.route[0]);
  67794. this.setEndPole(this.route[this.route.length - 1]);
  67795. create();
  67796. /*
  67797. distance: 0.17581000000000116
  67798. distance_to_previous: 0.17581000000000116
  67799. id: 567
  67800. instruction: {type: 'source_projection_to_navgraph'}
  67801. latitude: 22.366605927999238
  67802. location: (3) [113.5957510575092, 22.366605927999238, -1.12419]
  67803. longitude: 113.5957510575092
  67804. z: -1.12419
  67805. */
  67806. };
  67807. if (this.lastResult && (this.lastResult.data || this.lastResult.data.code != 4002)) {
  67808. //正被修改数据集的话要重新计算
  67809. var data = Common.CloneObject(this.lastResult.data),
  67810. use; //直接用上次的结果
  67811. if (this.lastResult.routeStart.equals(this.routeStart) && this.lastResult.routeEnd.equals(this.routeEnd)) {
  67812. //和上次请求相同
  67813. use = true;
  67814. } else if (this.lastResult.routeStart.equals(this.routeEnd) && this.lastResult.routeEnd.equals(this.routeStart)) {
  67815. //..反向
  67816. use = true;
  67817. if (data.data) {
  67818. data.data = this.lastResult.data.data.slice(0).reverse();
  67819. }
  67820. }
  67821. if (use) {
  67822. console.log('直接用上次的结果');
  67823. return setTimeout(() => {
  67824. dealData(data);
  67825. }, 1); //延迟是为了等待获得 RouteGuider.generateDeferred
  67826. }
  67827. }
  67828. var start = this.routeStart.clone();
  67829. var end = this.routeEnd.clone();
  67830. //let startLonlat = viewer.transform.lonlatToLocal.inverse(start/* , true */)
  67831. //let endLonlat = viewer.transform.lonlatToLocal.inverse(end/* , true */)
  67832. /* var query = {
  67833. source_longitude: start.x,
  67834. source_latitude: start.y,
  67835. source_z: start.z,
  67836. destination_longitude: end.x,
  67837. destination_latitude: end.y,
  67838. destination_z: end.z
  67839. }; */
  67840. var query = {
  67841. source_longitude: start.x,
  67842. source_latitude: start.y,
  67843. source_z: start.z + initialPointcloud.datasetData.location[2],
  67844. destination_longitude: end.x,
  67845. destination_latitude: end.y,
  67846. destination_z: end.z + initialPointcloud.datasetData.location[2]
  67847. };
  67848. /* var query = {
  67849. source_longitude: startLonlat.x,
  67850. source_latitude: startLonlat.y,
  67851. source_z: start.z,
  67852. destination_longitude: endLonlat.x,
  67853. destination_latitude: endLonlat.y,
  67854. destination_z: end.z
  67855. }; */
  67856. //let url = `/laser/route/${Potree.settings.number}/getRoute/${this.datasetIds[0]}/${this.datasetIds[1]}?`
  67857. var url = "/laser/route/".concat(Potree.settings.number, "/getRoute/").concat(Potree.settings.originDatasetId, "?");
  67858. for (var i in query) {
  67859. url += i + '=' + query[i] + '&';
  67860. }
  67861. Potree.fileServer.get(url).then(data => {
  67862. //console.log('data', data.data)
  67863. if (!this.routeStart || !this.routeEnd) return;
  67864. this.lastResult = {
  67865. //保存数据
  67866. routeStart: this.routeStart.clone(),
  67867. routeEnd: this.routeEnd.clone(),
  67868. data
  67869. };
  67870. dealData(data);
  67871. });
  67872. } else {
  67873. //创个直线
  67874. /* const sliceDis = 1
  67875. let dis = this.routeStart.distanceTo(this.routeEnd);
  67876. let count = Math.max(2,Math.round(dis / sliceDis))//点数
  67877. let realSlideDis = dis / (count-1);
  67878. let dir = new THREE.Vector3().subVectors(this.routeEnd, this.routeStart).normalize().multiplyScalar(realSlideDis);
  67879. this.route = [this.routeStart];
  67880. for(let i=0;i<count-1;i++){
  67881. let lastOne = this.route[i];
  67882. this.route.push(new THREE.Vector3().addVectors(lastOne,dir))
  67883. }
  67884. this.route.splice(0,1) //route不用包含收尾 */
  67885. this.clearRoute();
  67886. this.route = [this.routeStart, this.routeEnd];
  67887. create();
  67888. }
  67889. }
  67890. updateMapArrows(ifReset) {
  67891. if (this.route.length == 0) return;
  67892. var zoom = viewer.mapViewer.camera.zoom;
  67893. var isBig = viewer.mapViewer.viewports[0].resolution.y > 300;
  67894. var count = Math.max(2, Math.round(this.routeLength * zoom / arrowSpacing / (isBig ? 35 : 30))); //点数
  67895. if (count == this.mapPoints.length + 1) return; //没变
  67896. var mapPoints = this.curve.getSpacedPoints(count);
  67897. mapPoints.splice(0, 1); //去掉首尾
  67898. mapPoints.pop();
  67899. this.mapPoints = mapPoints;
  67900. var scale = (isBig ? 26 : 22) / zoom;
  67901. this.mapArrow.scale.set(scale, scale, scale);
  67902. /* this.mapMarkStart.scale.set(scale,scale,scale)
  67903. this.mapMarkEnd.scale.set(scale,scale,scale) */
  67904. if (ifReset) {
  67905. //因为缩放而重新排布箭头
  67906. this.clearRoute({
  67907. resetMap: true
  67908. });
  67909. this.displayRoute({
  67910. resetMap: true
  67911. });
  67912. }
  67913. this.updateOpacityAtMap();
  67914. }
  67915. updateArrowDisplay() {
  67916. //根据当前位置更新显示一定范围内的箭头
  67917. if (this.scenePoints.length == 0) return;
  67918. /* var a = Common.sortByScore(this.scenePoints , null, [(point)=>{ //是否还要再requires里限制最远距离?
  67919. var playerPos = viewer.scene.getActiveCamera().position.clone().setZ(0)
  67920. var pos = point.clone().setZ(0)
  67921. return -pos.distanceTo(playerPos);
  67922. }]);
  67923. //获得展示的起始点
  67924. let start = a[0].item
  67925. let startIndex = this.scenePoints.indexOf(start)
  67926. this.arrows.children.forEach((e,i)=>{
  67927. if(i<startIndex || i>startIndex+arrowsShowingCount)e.visible = false
  67928. else e.visible = true
  67929. }) */
  67930. var cameraPos = viewer.scene.getActiveCamera().position;
  67931. this.arrows.children.forEach((e, i) => {
  67932. if (e.position.distanceTo(cameraPos) < arrowShowMinDis) e.visible = true;else e.visible = false;
  67933. });
  67934. viewer.dispatchEvent('content_changed');
  67935. }
  67936. displayRoute() {
  67937. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  67938. if (!o.resetMap) {
  67939. this.poleStart.position.copy(this.startPolePos || this.routeStart);
  67940. this.poleEnd.position.copy(this.endPolePos || this.routeEnd);
  67941. /* this.mapMarkStart.position.copy(this.routeStart).setZ(0)
  67942. this.mapMarkEnd.position.copy(this.routeEnd).setZ(0) */
  67943. this.scenePoints.forEach(e => this.addArrow(e));
  67944. this.arrows.children.forEach((e, i) => this.setArrowDir(this.arrows.children, i));
  67945. }
  67946. this.sceneMeshGroup.visible = true; //.traverse(e=>e.visible = true)
  67947. this.mapMeshGroup.visible = true;
  67948. this.mapPoints.forEach(e => this.addMapArrow(e));
  67949. this.mapArrows.children.forEach((e, i) => this.setArrowDir(this.mapArrows.children, i));
  67950. viewer.mapViewer.dispatchEvent({
  67951. 'type': 'content_changed'
  67952. });
  67953. this.updateArrowDisplay();
  67954. }
  67955. clearRoute() {
  67956. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  67957. if (!o.resetMap) {
  67958. this.routeLength = 0;
  67959. this.route = [];
  67960. this.scenePoints = [];
  67961. this.mapPoints = [];
  67962. var arrows = this.arrows.children.slice(0);
  67963. arrows.forEach(e => {
  67964. this.arrows.remove(e);
  67965. });
  67966. }
  67967. var mapArrows = this.mapArrows.children.slice(0);
  67968. mapArrows.forEach(e => {
  67969. this.mapArrows.remove(e);
  67970. });
  67971. this.sceneMeshGroup.visible = false;
  67972. //this.sceneMeshGroup.traverse(e=>e.visible = false) //包括sprite也要设置,防止update
  67973. this.mapMeshGroup.visible = false;
  67974. viewer.mapViewer.dispatchEvent({
  67975. 'type': 'content_changed'
  67976. });
  67977. viewer.dispatchEvent('content_changed');
  67978. }
  67979. clear() {
  67980. //退出
  67981. console.log('导航clear');
  67982. this.routeStart = null;
  67983. this.routeEnd = null;
  67984. this.clearRoute();
  67985. }
  67986. }
  67987. //大概每十米要花一秒
  67988. /*
  67989. 存在的问题:
  67990. 路径不准确。起始点和终点偏移。
  67991. https://uat-laser.4dkankan.com/routeDebug/ 可查整个map的通路点位图
  67992. */
  67993. //import History from "../../utils/History.js"
  67994. var cameraProps$1 = [{
  67995. name: 'top',
  67996. axis: ["x", "y"],
  67997. direction: new Vector3(0, 0, -1),
  67998. //镜头朝向
  67999. openCount: 0
  68000. }];
  68001. class Clipping extends EventDispatcher {
  68002. //实时剪裁
  68003. constructor() {
  68004. super();
  68005. this.views = {};
  68006. this.cameras = {};
  68007. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  68008. this.orthoCamera.up.set(0, 0, 1);
  68009. }
  68010. init() {
  68011. if (this.inited) return;
  68012. this.initViews();
  68013. this.inited = true;
  68014. this.prepareRecord = true;
  68015. this.activeViewName = 'mainView';
  68016. this.events = {
  68017. transfromCallback: e => {
  68018. //拖拽变化时
  68019. this.adjustCamHeight();
  68020. //检测漫游点、回退等
  68021. /* if(this.prepareRecord){
  68022. let box = viewer.transformationTool.selection[0]
  68023. this.history.writeIn({box, matrix:box.matrix.clone()})
  68024. this.prepareRecord = false
  68025. } */
  68026. },
  68027. /* onTransfromEnd:(e)=>{//拖拽结束、松开
  68028. this.prepareRecord = true
  68029. }, */
  68030. selectCallback: e => {
  68031. this.adjustCamHeight();
  68032. var unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0;
  68033. if (Potree.settings.unableNavigate && !unableNavigate) {
  68034. setTimeout(() => {
  68035. Potree.settings.unableNavigate = this.activeViewName != 'mainView' || e.selection.length > 0;
  68036. }, 300); //延迟是因为点击时取消选择后可能立即就会触发flyToPano。 而且有的人喜欢点两下
  68037. } else Potree.settings.unableNavigate = unableNavigate;
  68038. },
  68039. onkeydown: e => {
  68040. if (e.keyCode == 8 || e.keyCode == 46) {
  68041. // Backspace or Delete
  68042. viewer.inputHandler.selection[0] && viewer.scene.removeVolume(viewer.inputHandler.selection[0]);
  68043. }
  68044. }
  68045. };
  68046. /* this.history = new History({ //也可以写到全局,但需要加个判断物品是否存在的函数
  68047. applyData: (data)=>{
  68048. if(viewer.scene.volumes.includes(data.box)){
  68049. data.matrix.decompose( data.box.position, data.box.quaternion, data.box.scale );
  68050. }else{
  68051. this.history.undo()//找不到就回退下一个。(直接写这?)
  68052. }
  68053. }
  68054. }) */
  68055. }
  68056. initViews() {
  68057. this.splitScreenTool = new SplitScreen();
  68058. for (var i = 0; i < 1; i++) {
  68059. var prop = cameraProps$1[i];
  68060. var view = new ExtendView();
  68061. this.views[prop.name] = view;
  68062. this.cameras[prop.name] = this.orthoCamera;
  68063. view.direction = prop.direction;
  68064. }
  68065. this.views.mainView = viewer.mainViewport.view;
  68066. this.cameras.mainView = viewer.mainViewport.camera;
  68067. }
  68068. switchView(name) {
  68069. //替换view和camera到mainViewport
  68070. if (this.activeViewName == name) return;
  68071. var view = this.views[name];
  68072. var camera = this.cameras[name];
  68073. var prop = cameraProps$1.find(e => e.name == name);
  68074. var {
  68075. boundSize,
  68076. center,
  68077. boundingBox
  68078. } = viewer.bound;
  68079. this.lastViewName = this.activeViewName;
  68080. this.activeViewName = name;
  68081. var lastView = this.views[this.lastViewName];
  68082. var lastCamera = this.cameras[this.lastViewName];
  68083. viewer.mainViewport.view = view;
  68084. viewer.mainViewport.camera = camera;
  68085. if (lastCamera) lastView.zoom = lastCamera.zoom;
  68086. /* if(lastView){//2d->3d
  68087. view.copy(lastView)
  68088. } */
  68089. if (name == 'mainView') {
  68090. Potree.settings.unableNavigate = false;
  68091. /* viewer.transformationTool.handles['scale.z+'].node.visible = true
  68092. viewer.transformationTool.handles['scale.z-'].node.visible = true */
  68093. } else {
  68094. Potree.settings.unableNavigate = true;
  68095. /* viewer.transformationTool.handles['scale.z+'].node.visible = false
  68096. viewer.transformationTool.handles['scale.z-'].node.visible = false */
  68097. if (prop.openCount == 0) {
  68098. //至多执行一次
  68099. //this.viewportFitBound(name, boundSize, center)
  68100. this.orthoMoveFit(center, {
  68101. bound: boundingBox
  68102. }, 0);
  68103. this.camHeightOutOfModel = view.position.z; //记录下此刻相机高度。
  68104. }
  68105. prop.openCount++;
  68106. this.adjustCamHeight();
  68107. /* this.targetPlane.setFromNormalAndCoplanarPoint( view.direction.clone(), center )
  68108. this.targetPlane.projectPoint(view.position, this.shiftTarget ) //target转换到过模型中心的平面,以保证镜头一定在模型外
  68109. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport)) */
  68110. if (view.zoom) camera.zoom = view.zoom; //恢复上次的zoom
  68111. }
  68112. viewer.updateScreenSize({
  68113. forceUpdateSize: true
  68114. }); //更新camera aspect left等
  68115. if (viewer.inputHandler.selection.length) {
  68116. this.focusOnObject(viewer.inputHandler.selection[0]);
  68117. }
  68118. }
  68119. focusOnObject(box) {
  68120. var duration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  68121. if (this.activeViewName == 'mainView') {
  68122. viewer.focusOnObject({
  68123. boundingBox: box.boundingBox.clone().applyMatrix4(box.matrixWorld)
  68124. }, 'boundingBox', duration);
  68125. } else {
  68126. this.orthoMoveFit(box.position, {
  68127. bound: box.boundingBox.clone().applyMatrix4(box.matrixWorld)
  68128. }, duration);
  68129. }
  68130. this.adjustCamHeight();
  68131. }
  68132. orthoMoveFit(pos, info, duration) {
  68133. var margin = {
  68134. x: viewer.mainViewport.resolution.x * 0.4,
  68135. y: viewer.mainViewport.resolution.y * 0.4
  68136. };
  68137. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin);
  68138. }
  68139. adjustCamHeight() {
  68140. if (this.activeViewName != 'top') return;
  68141. var view = this.views.top;
  68142. var height;
  68143. if (viewer.inputHandler.selection.length) {
  68144. //相机高度位于选中的box的顶部
  68145. var box = viewer.inputHandler.selection[0];
  68146. height = box.boundingBox.clone().applyMatrix4(box.matrixWorld).max.z;
  68147. } else {
  68148. height = this.camHeightOutOfModel; //显示全部点云
  68149. }
  68150. view.position.z = height;
  68151. //console.log('adjustCamHeight',height)
  68152. //缺点:1 会导致缩放很小的时候,transformationTool的轴因放大到了相机背面。(只有scale轴做了处理)
  68153. //2 无法直接切换 看不到的box,但可以先取消选择
  68154. //3 但是俯视图中无法切换到被上层盖住的box(不过把俯视图作为辅助,只针对单个box调动的话,问题不大)
  68155. }
  68156. enter() {
  68157. this.init();
  68158. viewer.transformationTool.setModeEnable(['translation']);
  68159. //viewer.transformationTool.handles['rotation.x'].node.visible = false
  68160. viewer.transformationTool.frame.material.visible = false; //不盖住boxVolume的frame
  68161. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  68162. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置
  68163. this.getAllBoxes().forEach(box => {
  68164. Potree.Utils.updateVisible(box, 'hidden', true); //显现
  68165. });
  68166. viewer.transformationTool.history.clear();
  68167. viewer.transformationTool.addEventListener('transformed', this.events.transfromCallback);
  68168. //viewer.transformationTool.addEventListener('stopDrag', this.events.onTransfromEnd)
  68169. viewer.inputHandler.addEventListener('selection_changed', this.events.selectCallback);
  68170. viewer.inputHandler.addEventListener('keydown', this.events.onkeydown);
  68171. this.setPointLevelAuto();
  68172. var initialPointcloud = viewer.scene.pointclouds.find(p => p.dataset_id == Potree.settings.originDatasetId);
  68173. //隐藏 初始数据集以外的数据集
  68174. viewer.scene.pointclouds.forEach(e => {
  68175. if (e.dataset_id != Potree.settings.originDatasetId) {
  68176. Potree.Utils.updateVisible(e, 'enterClipping', false);
  68177. //Potree.settings.floorplanEnables[e.dataset_id] = false
  68178. e.panos.forEach(pano => pano.setEnable(false)); //禁止漫游
  68179. } else {
  68180. Potree.Utils.updateVisible(e, 'enterClipping', true, 1, 'add');
  68181. //Potree.settings.floorplanEnables[e.dataset_id] = true
  68182. }
  68183. });
  68184. viewer.flyToDataset({
  68185. pointcloud: initialPointcloud,
  68186. duration: 0
  68187. });
  68188. }
  68189. enter2() {
  68190. //在土方量界面的
  68191. viewer.transformationTool.setModeEnable(['translation']);
  68192. viewer.transformationTool.frame.material.visible = false; //不盖住boxVolume的frame
  68193. viewer.transformationTool.history.clear();
  68194. //viewer.inputHandler.addEventListener('keydown', this.events.onkeydown)
  68195. }
  68196. leave() {
  68197. viewer.transformationTool.setModeEnable(['scale', 'translation', 'rotation']);
  68198. viewer.transformationTool.frame.material.visible = true; //恢复
  68199. this.switchView('mainView');
  68200. this.getAllBoxes().forEach(box => {
  68201. Potree.Utils.updateVisible(box, 'hidden', false); //隐身
  68202. });
  68203. viewer.transformationTool.removeEventListener('transformed', this.events.transfromCallback);
  68204. //viewer.transformationTool.removeEventListener('stopDrag', this.events.onTransfromEnd)
  68205. viewer.inputHandler.removeEventListener('selection_changed', this.events.selectCallback);
  68206. //viewer.inputHandler.removeEventListener('keydown', this.events.onkeydown)
  68207. viewer.transformObject(null);
  68208. viewer.transformationTool.history.clear();
  68209. //恢复 初始数据集以外的数据集
  68210. viewer.scene.pointclouds.forEach(e => {
  68211. if (e.dataset_id != Potree.settings.originDatasetId) {
  68212. Potree.Utils.updateVisible(e, 'enterClipping', true);
  68213. e.panos.forEach(pano => pano.setEnable(true));
  68214. } else {
  68215. Potree.Utils.updateVisible(e, 'enterClipping', false, 0, 'cancel');
  68216. }
  68217. });
  68218. }
  68219. setTranMode(mode) {
  68220. //rotate or translate
  68221. this.tranMode = mode;
  68222. viewer.transformationTool.setModeEnable([mode]);
  68223. viewer.dispatchEvent('content_changed');
  68224. }
  68225. //问:是否要显示其他数据集
  68226. setPointLevelAuto() {
  68227. /*
  68228. let visiCount = viewer.images360.panos.length
  68229. let maxCount = 200, minCount = 20, minPer = 0.7, maxPer = 1
  68230. let percent = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount - minCount) / (maxCount - minCount),0,1)
  68231. Potree.settings.UserDensityPercent = percent ---还是不限制了,尤其是平面图希望更细致点,毕竟剪裁主要要看清剪裁的部位。
  68232. */
  68233. viewer.setPointBudget(5 * 1000 * 1000); //给个中等到高等之间的质量
  68234. Potree.settings.sizeFitToLevel = true;
  68235. viewer.setPointLevels();
  68236. }
  68237. getAllBoxes() {
  68238. return viewer.scene.volumes.filter(v => v.clip && v instanceof Potree.BoxVolume);
  68239. }
  68240. getCalcData() {
  68241. //给后台矩阵数据,以裁剪点云。
  68242. var Clip = viewer.modules.Clip; //裁剪下载模块
  68243. var data = {
  68244. transformation_matrix: viewer.scene.pointclouds.filter(p => p.dataset_id == Potree.settings.originDatasetId).map(cloud => {
  68245. var data = {
  68246. id: cloud.dataset_id,
  68247. matrix: new Matrix4().elements,
  68248. //参照downloadNoCrop,给默认值,表示没有最外层裁剪
  68249. visiMatrixes: cloud.material.clipBoxes_in.filter(e => !e.box.isNew).map(e => Clip.getTransformationMatrix(cloud, e.inverse).elements),
  68250. unVisiMatrixes: cloud.material.clipBoxes_out.filter(e => !e.box.isNew).map(e => Clip.getTransformationMatrix(cloud, e.inverse).elements),
  68251. modelMatrix: new Matrix4().elements //(new THREE.Matrix4).copy(cloud.transformMatrix).transpose().elements //需要保证没有位移,否则剪裁后的模型位置会变化
  68252. };
  68253. return data;
  68254. }),
  68255. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //剪裁空间
  68256. };
  68257. return data;
  68258. }
  68259. saveClipData(boxes) {
  68260. //输出所有的clip volumeBox
  68261. var oldState = !viewer.clipUnabled;
  68262. //viewer.setClipState(true)
  68263. var data = (boxes || this.getAllBoxes()).filter(e => !e.isNew).map(volume => {
  68264. return {
  68265. clipTask: volume.clipTask,
  68266. position: Potree.Utils.datasetPosTransform({
  68267. position: volume.position,
  68268. toDataset: true,
  68269. datasetId: Potree.settings.originDatasetId
  68270. }).toArray(),
  68271. rotation: Potree.Utils.datasetRotTransform({
  68272. rotation: volume.rotation,
  68273. toDataset: true,
  68274. datasetId: Potree.settings.originDatasetId,
  68275. getRotation: true
  68276. }).toArray().slice(0, 3),
  68277. scale: volume.scale.toArray()
  68278. };
  68279. });
  68280. //console.log(data)
  68281. //console.log(JSON.stringify(data))
  68282. //viewer.setClipState(oldState)
  68283. return data;
  68284. }
  68285. loadFromData() {
  68286. var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  68287. data.forEach(v => {
  68288. var volume = new Potree.BoxVolume({
  68289. clip: true,
  68290. clipTask: v.clipTask
  68291. });
  68292. volume.scale.fromArray(v.scale);
  68293. volume.position.fromArray(v.position);
  68294. volume.rotation.fromArray(v.rotation);
  68295. volume.position.copy(Potree.Utils.datasetPosTransform({
  68296. position: volume.position,
  68297. fromDataset: true,
  68298. datasetId: Potree.settings.originDatasetId
  68299. }));
  68300. volume.rotation.copy(Potree.Utils.datasetRotTransform({
  68301. rotation: volume.rotation,
  68302. fromDataset: true,
  68303. datasetId: Potree.settings.originDatasetId,
  68304. getRotation: true
  68305. }));
  68306. viewer.scene.addVolume(volume);
  68307. viewer.volumeTool.scene.add(volume);
  68308. });
  68309. }
  68310. }
  68311. //注意:实时裁剪只对初始数据集有效,其他数据集已经隐藏
  68312. /*
  68313. 备注:
  68314. 2023
  68315. 发送给后台数据样例:
  68316. {"transformation_matrix":[{"id":"1626189981883699200","matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],"visiMatrixes":[],"unVisiMatrixes":[[0.18610746638254325,-0.0005022517888587003,0,-0.01638495865566026,0.0002721420073982042,0.10084117292688818,0,0.25897037181878035,0,0,0.17066427841288187,-0.1913158687770112,0,0,0,1]],"modelMatrix":[0.999996358477288,-0.0026987093514294095,0,3.275872500136923e-8,0.0026987093514294095,0.999996358477288,0,-4.2486927309681385e-9,0,0,1,0,0,0,0,1]}],"aabb":"b-12742000 -12742000 -12742000 12742000 12742000 12742000"}
  68317. 发送给算法部的数据样例:
  68318. {
  68319. "model": [
  68320. {
  68321. "cut_transformation": "1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0",
  68322. "file": "/mnt/data/pvt000004/1079784714115481600/pvt000004_202302271512444930_laserData/laserData/laser.las",
  68323. "visiMatrixes": [[..],[..]],
  68324. "dataSetId": "1630105213031026688",
  68325. "sceneCode": "SS-t-MVQ1Jb80oMG",
  68326. "modelMatrix": "-0.9338946595415051 -0.35754826930060274 0.0 -3.483651134875185E-8 0.35754826930060274 -0.9338946595415051 0.0 5.664923641290965E-9 0.0 0.0 0.9999999999999999 0.0 0.0 0.0 0.0 1.0",
  68327. "unVisiMatrixes": [[..],[..]]
  68328. }
  68329. ],
  68330. "aabb": "b-12742000 -12742000 -12742000 12742000 12742000 12742000"
  68331. }
  68332. */
  68333. var vertexShader = "\n attribute float randam;\n attribute float sprite;\n attribute float centerHeight; //add\n \n //uniform float fireHeight; //add \n uniform float time;\n uniform float size;\n uniform float heightOfNearPlane;\n \n \n \n \n //varying float heightRatio;\n varying float vSprite;\n varying float vOpacity; \n float PI = 3.14;\n\n float quadraticIn( float t ) \n { \n float tt = t * t;\n return tt * tt; \n //\u53D8\u5316\u66F2\u7EBF \u8D8A\u6765\u8D8A\u5FEB\n } \n \n void main() {\n float progress = fract( time + ( 2.0 * randam - 1.0 ) );\n float progressNeg = 1.0 - progress;\n float ease = quadraticIn( progress );\n float influence = sin( PI * ease );\n //vec3 newPosition = position * vec3( 1.0, 1.0 , ease);\n vec3 newPosition = position;\n newPosition.z = (newPosition.z - centerHeight) * ease + centerHeight;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );\n gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;\n vOpacity = min( influence * 4.0, 1.0 ) * progressNeg;\n vSprite = sprite;\n \n //heightRatio = (newPosition.z - centerHeight) / fireHeight ;\n \n }\n";
  68334. var fragmentShader = "\n uniform vec3 color;\n uniform sampler2D u_sampler;\n\n varying float vSprite;\n varying float vOpacity;\n //varying float heightRatio;\n\n void main() \n {\n \n \n vec2 texCoord = vec2(gl_PointCoord.x * 0.25 + vSprite, gl_PointCoord.y);\n \n gl_FragColor = vec4( texture2D( u_sampler, texCoord ).xyz * color * vOpacity, 1.0 );\n \n \n }\n";
  68335. // import { vertexShader, fragmentShader } from './shaders'
  68336. var ONE_SPRITE_ROW_LENGTH = 0.25; //对应着色器的0.25
  68337. var texture;
  68338. var getTexture = () => {
  68339. if (!texture) {
  68340. texture = new TextureLoader().load(Potree.resourcePath + '/textures/fire.png');
  68341. }
  68342. return texture;
  68343. };
  68344. var boxGeo = new BoxBufferGeometry(1, 1, 1, 1);
  68345. var boxMat = new MeshBasicMaterial({
  68346. wireframe: true,
  68347. color: "#ffffff"
  68348. });
  68349. class FireParticle extends Points {
  68350. constructor(prop) {
  68351. super();
  68352. for (var key in prop) {
  68353. this[key] = prop[key];
  68354. }
  68355. this.strength = this.strength || 1;
  68356. this.radius = prop.radius || 1;
  68357. this.height = prop.height || 5;
  68358. this.computeParams();
  68359. this.geometry = this.createGeometry(this.radius, this.height, this.particleCount);
  68360. if (this.color == void 0) this.color = 0xff3200;
  68361. this.createMaterial(); //小蓝火:0x00338f
  68362. //---?:
  68363. this.velocity = new Vector3();
  68364. this.acceleration = new Vector3();
  68365. this.angle = 0;
  68366. this.angleVelocity = 0;
  68367. this.angleAcceleration = 0;
  68368. this.size = 16;
  68369. this.opacity = 1;
  68370. this.age = 0;
  68371. this.alive = 0;
  68372. this.sizeTween = null;
  68373. this.colorTween = null;
  68374. this.opacityTween = null;
  68375. this.setSize({
  68376. viewport: viewer.mainViewport
  68377. });
  68378. this.setFov(viewer.fov);
  68379. var setSize = e => {
  68380. if (e.viewport.name != "MainView") return;
  68381. this.setSize(e);
  68382. };
  68383. var setFov = e => {
  68384. this.setFov(e.fov);
  68385. };
  68386. viewer.addEventListener('resize', setSize);
  68387. viewer.addEventListener('fov_changed', setFov);
  68388. this.addEventListener('dispose', () => {
  68389. viewer.removeEventListener('resize', setSize);
  68390. viewer.removeEventListener('fov_changed', setFov);
  68391. });
  68392. }
  68393. computeParams() {
  68394. var length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  68395. var minSize = 0.3,
  68396. maxSize = 3,
  68397. minRadiusBound = 0.3,
  68398. maxRadiusBound = 10;
  68399. this.size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius, minRadiusBound, maxRadiusBound);
  68400. //console.log('fire material particle size:', size )
  68401. this.particleCount = Math.ceil(length * Math.sqrt(this.strength * this.height) * this.radius / (this.size * this.size) * 25);
  68402. //console.log('fire particleCount',this.particleCount)
  68403. }
  68404. getPointsForBound() {
  68405. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  68406. }
  68407. getBound(points) {
  68408. // points为生成点(圆心)
  68409. this.boundPoints = [];
  68410. var boundingBox = new Box3();
  68411. var margin = this.size * 0.13 + 0.3;
  68412. points.forEach(bottom => {
  68413. var top = bottom.clone();
  68414. top.z += this.height;
  68415. boundingBox.expandByPoint(bottom);
  68416. boundingBox.expandByPoint(top);
  68417. this.boundPoints.push(bottom, top);
  68418. });
  68419. var xyExpand = this.radius + margin;
  68420. boundingBox.expandByVector(new Vector3(xyExpand, xyExpand, margin));
  68421. this.boundingBox = boundingBox;
  68422. /* if(!this.debugBox){
  68423. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  68424. this.add(this.debugBox)
  68425. }
  68426. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  68427. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  68428. }
  68429. createGeometry(radius, height, particleCount) {
  68430. var geometry = new BufferGeometry();
  68431. var count, points;
  68432. if (this.positions.length > 1) {
  68433. var spaceDis = 0.2; //间隔距离
  68434. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  68435. //console.log('count', count)
  68436. points = this.curve.getSpacedPoints(count); //得到的数量会比count多一个
  68437. count = points.length;
  68438. //得到的点不太均匀,两端容易点少。
  68439. this.getBound(points);
  68440. } else {
  68441. this.getBound(this.positions);
  68442. }
  68443. var position = new Float32Array(particleCount * 3);
  68444. var randam = new Float32Array(particleCount);
  68445. var sprite = new Float32Array(particleCount);
  68446. var centerHeight = new Float32Array(particleCount);
  68447. for (var i = 0; i < particleCount; i++) {
  68448. var center = new Vector3().copy(this.positions.length > 1 ? points[Math.floor(i / particleCount * count)] : this.positions[0]);
  68449. centerHeight[i] = center.z;
  68450. if (i === 0) {
  68451. // to avoid going out of Frustum
  68452. position[i * 3 + 0] = center.x;
  68453. position[i * 3 + 1] = center.y;
  68454. position[i * 3 + 2] = center.z;
  68455. } else {
  68456. var r = Math.sqrt(Math.random()) * radius;
  68457. var angle = Math.random() * 2 * Math.PI;
  68458. position[i * 3 + 0] = center.x + Math.cos(angle) * r;
  68459. position[i * 3 + 1] = center.y + Math.sin(angle) * r;
  68460. position[i * 3 + 2] = center.z + (radius - r) / radius * height / 2 + height / 2; //不太明白这句为什么能达到height高度
  68461. sprite[i] = 0.25 * (Math.random() * 4 | 0);
  68462. randam[i] = Math.random();
  68463. //center在底部
  68464. }
  68465. }
  68466. geometry.setAttribute('centerHeight', new BufferAttribute(centerHeight, 1));
  68467. geometry.setAttribute('position', new BufferAttribute(position, 3));
  68468. geometry.setAttribute('randam', new BufferAttribute(randam, 1));
  68469. geometry.setAttribute('sprite', new BufferAttribute(sprite, 1));
  68470. return geometry;
  68471. }
  68472. updateGeometry() {
  68473. this.computeParams();
  68474. this.geometry.dispose();
  68475. this.geometry = this.createGeometry(this.radius, this.height, this.particleCount);
  68476. this.material.uniforms.size.value = this.size;
  68477. }
  68478. createMaterial() {
  68479. var material = new ShaderMaterial({
  68480. uniforms: {
  68481. color: {
  68482. type: "c",
  68483. value: new Color(this.color)
  68484. },
  68485. size: {
  68486. type: "f",
  68487. value: this.size
  68488. },
  68489. u_sampler: {
  68490. type: "t",
  68491. value: getTexture()
  68492. },
  68493. time: {
  68494. type: "f",
  68495. value: 0.0
  68496. },
  68497. heightOfNearPlane: {
  68498. type: "f",
  68499. value: 0
  68500. },
  68501. //相对far ,以确保画面缩放时点的大小也会缩放
  68502. height: {
  68503. type: "f",
  68504. value: this.height
  68505. }
  68506. },
  68507. vertexShader,
  68508. fragmentShader,
  68509. blending: AdditiveBlending,
  68510. //加法融合模式 glBlendFunc(GL_ONE, GL_ONE)
  68511. depthTest: true,
  68512. depthWrite: false,
  68513. transparent: true
  68514. });
  68515. this.material = material;
  68516. this.setPerspective(this.fov, this.screenHeight);
  68517. }
  68518. setSize(e) {
  68519. var viewport = e.viewport;
  68520. this.screenHeight = viewport.resolution.y;
  68521. this.setPerspective(this.fov, this.screenHeight);
  68522. }
  68523. setFov(fov) {
  68524. this.fov = fov;
  68525. this.setPerspective(this.fov, this.screenHeight);
  68526. }
  68527. setPerspective(fov, height) {
  68528. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  68529. var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  68530. this.material.uniforms.heightOfNearPlane.value = far;
  68531. }
  68532. update(delta) {
  68533. if (!Potree.Utils.getObjVisiByReason(this, 'force')) {
  68534. //被手动隐藏了
  68535. return;
  68536. }
  68537. if (!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())) {
  68538. Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围
  68539. //console.log('unvi')
  68540. return;
  68541. } else {
  68542. Potree.Utils.updateVisible(this, 'isInsideFrustum', true);
  68543. }
  68544. delta *= 1; //更改速度
  68545. this.material.uniforms.time.value = (this.material.uniforms.time.value + delta) % 1;
  68546. viewer.dispatchEvent('content_changed');
  68547. }
  68548. dispose() {
  68549. this.geometry.dispose();
  68550. this.material.dispose();
  68551. this.dispatchEvent('dispose');
  68552. }
  68553. }
  68554. class Tween {
  68555. constructor(times, values) {
  68556. this.times = times || [];
  68557. this.values = values || [];
  68558. }
  68559. lerp(t) {
  68560. if (this.times.length == 0) return;
  68561. var i = 0,
  68562. n = this.times.length;
  68563. while (i < n && t > this.times[i]) i++;
  68564. if (i == 0) return this.values[0];
  68565. if (i == n) return this.values[n - 1];
  68566. var ratio = (t - this.times[i - 1]) / (this.times[i] - this.times[i - 1]);
  68567. if (this.values[0] instanceof Vector3) {
  68568. return this.values[i - 1].clone().lerp(this.values[i], ratio);
  68569. } else {
  68570. return this.values[i - 1] + ratio * (this.values[i] - this.values[i - 1]);
  68571. }
  68572. }
  68573. clone() {
  68574. return Common.CloneClassObject(this);
  68575. }
  68576. }
  68577. class Particle$1 {
  68578. constructor() {
  68579. var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  68580. this.position = new Vector3();
  68581. this.velocity = new Vector3(); // units per second
  68582. this.angle = 0;
  68583. this.angleVelocity = 0; // degrees per second
  68584. this.angleAcceleration = 0; // degrees per second, per second
  68585. this.size = 16.0;
  68586. this.color = new Color();
  68587. this.opacity = 1.0;
  68588. this.age = 0;
  68589. this.alive = 0; // use float instead of boolean for shader purposes
  68590. this.lastChangeVage = 0; //add
  68591. this.sizeTween = prop.sizeTween || new Tween([0, 1], [32, 128]);
  68592. this.opacityTween = prop.opacityTween || new Tween([0.8, 2], [0.5, 0]);
  68593. this.colorTween = prop.colorTween || new Tween([0.4, 1], [new Vector3(0, 0, 0.2), new Vector3(0, 0, 0.5)]);
  68594. }
  68595. update(dt) {
  68596. this.position.add(this.velocity.clone().multiplyScalar(dt));
  68597. this.velocity.multiplyScalar(1 + this.acceleration * dt);
  68598. // convert from degrees to radians: 0.01745329251 = Math.PI/180
  68599. this.angle += this.angleVelocity * 0.01745329251 * dt;
  68600. this.angleVelocity += this.angleAcceleration * 0.01745329251 * dt;
  68601. this.age += dt;
  68602. // if the tween for a given attribute is nonempty,
  68603. // then use it to update the attribute's value
  68604. if (this.sizeTween.times.length > 0) this.size = this.sizeTween.lerp(this.age / this.deathAge);
  68605. if (this.colorTween.times.length > 0) {
  68606. var colorHSL = this.colorTween.lerp(this.age / this.deathAge);
  68607. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  68608. }
  68609. if (this.opacityTween.times.length > 0) {
  68610. this.opacity = this.opacityTween.lerp(this.age / this.deathAge);
  68611. }
  68612. viewer.dispatchEvent('content_changed');
  68613. }
  68614. }
  68615. var vertexShader$1 = "\n attribute vec3 customColor;\n attribute float customOpacity;\n attribute float customSize;\n attribute float customAngle;\n attribute float customVisible; \n uniform float heightOfNearPlane;\n \n \n varying vec4 vColor;\n varying float vAngle;\n void main()\n {\n if ( customVisible > 0.5 ) \t\t\t\t\n vColor = vec4( customColor, customOpacity ); \n else\t\t\t\t\t\t\t\n vColor = vec4(0.0, 0.0, 0.0, 0.0);\t\t\n \n vAngle = customAngle;\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n //gl_PointSize = customSize * ( 300.0 / length( mvPosition.xyz ) ); \n gl_Position = projectionMatrix * mvPosition;\n gl_PointSize = ( heightOfNearPlane * customSize ) / gl_Position.w;\n \n \n }\n";
  68616. var fragmentShader$1 = "\n uniform sampler2D u_sampler;\n varying vec4 vColor;\t\n varying float vAngle; \n void main()\n {\n gl_FragColor = vColor;\n \n float c = cos(vAngle);\n float s = sin(vAngle);\n vec2 rotatedUV = vec2(c * (gl_PointCoord.x - 0.5) + s * (gl_PointCoord.y - 0.5) + 0.5, c * (gl_PointCoord.y - 0.5) - s * (gl_PointCoord.x - 0.5) + 0.5); \n vec4 rotatedTexture = texture2D( u_sampler, rotatedUV );\n gl_FragColor = gl_FragColor * rotatedTexture; \n }\n";
  68617. var Type = Object.freeze({
  68618. "CUBE": 1,
  68619. "SPHERE": 2
  68620. });
  68621. var particleTexture;
  68622. var getTexture$1 = () => {
  68623. if (!particleTexture) {
  68624. particleTexture = new TextureLoader().load(Potree.resourcePath + '/textures/smokeparticle.png');
  68625. }
  68626. return particleTexture;
  68627. };
  68628. var boxGeo$1 = new BoxBufferGeometry(1, 1, 1, 1);
  68629. var boxMat$1 = new MeshBasicMaterial({
  68630. wireframe: true,
  68631. color: "#ffffff"
  68632. });
  68633. var defaults = {
  68634. positions: [],
  68635. positionStyle: "sphere",
  68636. positionBase: new Vector3(0, 0, 0),
  68637. positionSpread: new Vector3(1, 1, 0),
  68638. //cube
  68639. radius: 1,
  68640. // sphere
  68641. velocityStyle: 'cube',
  68642. velocityBase: new Vector3(0, 0, 0.5),
  68643. // cube 基础速度
  68644. velocitySpread: new Vector3(1, 1, 0.3),
  68645. accelerationBase: 0.3,
  68646. //基础加速度
  68647. accelerationSpread: 0.6,
  68648. //没使用
  68649. speedBase: 0.1,
  68650. //sphere
  68651. speedSpread: 0.5,
  68652. angleBase: 0,
  68653. angleSpread: 360,
  68654. angleVelocityBase: 1,
  68655. angleVelocitySpread: 30,
  68656. angleAccelerationBase: 1,
  68657. angleAccelerationSpread: 5,
  68658. sizeBase: 0,
  68659. sizeSpread: 0,
  68660. sizeTween: [[0, 0.3, 1], [0.3, 1.4, 6]],
  68661. colorBase: new Vector3(0.0, 1.0, 0.5),
  68662. colorSpread: new Vector3(0.0, 0.0, 0.0),
  68663. colorTween: new Tween([0.2, 1], [new Vector3(0, 0, 0.4), new Vector3(0, 0, 0.1)]),
  68664. opacityBase: 0.1,
  68665. //1.0,
  68666. opacitySpread: 0.2,
  68667. opacityTween: [[0, 0.1, 0.9, 1], [0.1, 0.4, 0.03, 0]],
  68668. //particlesPerSecond : 20,
  68669. strength: 1,
  68670. particleDeathAge: 3,
  68671. //从底下升起后能持续的时间
  68672. //emitterDeathAge : 60 // time (seconds) at which to stop creating particles.
  68673. height: 3
  68674. };
  68675. var debugSphere = new Mesh(new SphereBufferGeometry(0.03, 5, 5), new MeshBasicMaterial({
  68676. color: 'white',
  68677. depthTest: false
  68678. }));
  68679. class SmokeParticle extends Points {
  68680. constructor() {
  68681. var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  68682. super();
  68683. this.blendStyle = NormalBlending; // false;
  68684. this.emitterAge = 0.0;
  68685. //this.emitterAlive = true;
  68686. prop = $.extend({}, defaults, prop);
  68687. for (var key in prop) {
  68688. var value = prop[key];
  68689. if (value instanceof Array && value[0] instanceof Array) this[key] = new Tween(...value);else if (value instanceof Vector3 || value instanceof Color) {
  68690. this[key] = value.clone();
  68691. } else {
  68692. this[key] = value;
  68693. }
  68694. }
  68695. this.defaultSizeTween = this.sizeTween.clone();
  68696. this.defaultOpacityTween = this.opacityTween.clone();
  68697. this.geometry = new BufferGeometry();
  68698. this.computeParams();
  68699. this.createMaterial();
  68700. this.createGeometry();
  68701. this.dynamic = true;
  68702. this.sortParticles = true;
  68703. this.frustumCulled = false; //似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  68704. prop.position && this.position.copy(prop.position);
  68705. //---------------------------------------
  68706. this.setSize({
  68707. viewport: viewer.mainViewport
  68708. });
  68709. this.setFov(viewer.fov);
  68710. var setSize = e => {
  68711. if (e.viewport.name != "MainView") return;
  68712. this.setSize(e);
  68713. };
  68714. var setFov = e => {
  68715. this.setFov(e.fov);
  68716. };
  68717. /* let reStart = (e)=>{
  68718. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  68719. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  68720. //console.log('归零')
  68721. //this.reStart()
  68722. },1)
  68723. }
  68724. } */
  68725. viewer.addEventListener('resize', setSize);
  68726. viewer.addEventListener('fov_changed', setFov);
  68727. //viewer.addEventListener('pageVisible', reStart)
  68728. this.addEventListener('dispose', () => {
  68729. viewer.removeEventListener('resize', setSize);
  68730. viewer.removeEventListener('fov_changed', setFov);
  68731. //viewer.removeEventListener('pageVisible', reStart)
  68732. });
  68733. }
  68734. computeParams() {
  68735. var length = (this.curve ? this.curve.wholeLength : 0) + this.radius * 2; //加上首尾的半径
  68736. //注意:烟最低高度一米, 0<strength<1
  68737. if (this.positionStyle == 'cube') {
  68738. this.positionSpread.set(this.radius, this.radius, 0);
  68739. }
  68740. this.velocityBase.set(0, 0, (this.height - 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge) / this.particleDeathAge);
  68741. //let height = this.velocityBase.z * this.particleDeathAge + 0.5 * this.accelerationBase * this.particleDeathAge * this.particleDeathAge;//s = V0 * t + 0.5 * a * t*t ;
  68742. this.velocityBase.z = Math.max(0, this.velocityBase.z);
  68743. this.particleCount = Math.ceil(length * Math.sqrt(this.strength * this.height * this.radius));
  68744. this.particleCount = Math.max(5, this.particleCount);
  68745. {
  68746. var minSize = 1,
  68747. maxSize = 2,
  68748. minBound = 0.01,
  68749. maxBound = 1;
  68750. var size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.strength, minBound, maxBound);
  68751. this.sizeTween.values = this.defaultSizeTween.values.map(e => e * size);
  68752. }
  68753. {
  68754. var _minSize = 1,
  68755. _maxSize = 1.5,
  68756. _minBound = 0.01,
  68757. _maxBound = 1;
  68758. var opac = _minSize + (_maxSize - _minSize) * MathUtils.smoothstep(this.strength, _minBound, _maxBound);
  68759. this.opacityTween.values = this.defaultOpacityTween.values.map(e => e * opac);
  68760. }
  68761. //console.log('smoke particleCount',this.particleCount)
  68762. }
  68763. reStart() {
  68764. this.emitterAge = 0;
  68765. this.createGeometry();
  68766. }
  68767. updateGeometry() {
  68768. this.computeParams();
  68769. this.reStart();
  68770. }
  68771. createParticle(center) {
  68772. var particle = new Particle$1({
  68773. sizeTween: this.sizeTween,
  68774. opacityTween: this.opacityTween,
  68775. colorTween: this.colorTween
  68776. });
  68777. particle.deathAge = this.particleDeathAge;
  68778. particle.center = center;
  68779. if (this.positionStyle == 'cube') particle.position = this.randomVector3(this.positionBase, this.positionSpread);
  68780. if (this.positionStyle == 'sphere') {
  68781. /* var z = 2 * Math.random() - 1
  68782. var t = Math.PI * 2 * Math.random();
  68783. var r = Math.sqrt( 1 - z*z ) ;
  68784. var vec3 = new THREE.Vector3( r * Math.cos(t), r * Math.sin(t), z );
  68785. particle.position = new THREE.Vector3().addVectors( this.positionBase, vec3.multiplyScalar( this.radius ) );
  68786. */
  68787. //怎么改半径
  68788. var y = 2 * Math.random() - 1;
  68789. var t = Math.PI * 2 * Math.random();
  68790. var r = Math.sqrt(1 - y * y); //因为 r*r = 1-y*y = x*x + z*z = r*r(cos^2 + sin^2 );
  68791. var lowDownRatio = 0.2; //压低近平面
  68792. var vec3 = new Vector3(r * Math.cos(t), y, Math.abs(r * Math.sin(t)) * lowDownRatio);
  68793. particle.position = new Vector3().addVectors(this.positionBase, vec3.multiplyScalar(this.radius));
  68794. }
  68795. particle.position.add(center); //add
  68796. if (this.velocityStyle == 'cube') {
  68797. particle.velocity = this.randomVector3(this.velocityBase, this.velocitySpread);
  68798. }
  68799. if (this.velocityStyle == 'sphere') {
  68800. //var direction = particle.position.clone()
  68801. var direction = new Vector3(0, 0, 1); //烟应该都是向上的
  68802. var speed = this.randomValue(this.speedBase, this.speedSpread);
  68803. particle.velocity = direction.normalize().multiplyScalar(speed);
  68804. }
  68805. particle.acceleration = this.randomValue(this.accelerationBase, this.accelerationSpread);
  68806. particle.angle = this.randomValue(this.angleBase, this.angleSpread);
  68807. particle.angleVelocity = this.randomValue(this.angleVelocityBase, this.angleVelocitySpread);
  68808. particle.angleAcceleration = this.randomValue(this.angleAccelerationBase, this.angleAccelerationSpread);
  68809. particle.size = this.randomValue(this.sizeBase, this.sizeSpread);
  68810. var color = this.randomVector3(this.colorBase, this.colorSpread);
  68811. particle.color = new Color().setHSL(color.x, color.y, color.z);
  68812. particle.opacity = this.randomValue(this.opacityBase, this.opacitySpread);
  68813. particle.age = 0;
  68814. particle.alive = 0; // particles initialize as inactive
  68815. return particle;
  68816. }
  68817. getPointsForBound() {
  68818. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  68819. }
  68820. getBound(points) {
  68821. // points为生成点(圆心)
  68822. this.boundPoints = [];
  68823. var boundingBox = new Box3();
  68824. var maxSize = this.sizeTween.values.slice().sort((a, b) => b - a)[0];
  68825. var margin0 = maxSize * 0.11;
  68826. var margin1 = margin0 + 0.5; //保守估计还会飘出这么多距离吧: size + 飘动
  68827. points.forEach(bottom => {
  68828. var top = bottom.clone();
  68829. top.z += this.height;
  68830. boundingBox.expandByPoint(bottom);
  68831. boundingBox.expandByPoint(top);
  68832. this.boundPoints.push(bottom, top);
  68833. });
  68834. var xyExpand = this.radius + margin1;
  68835. boundingBox.expandByVector(new Vector3(xyExpand, xyExpand, 0));
  68836. boundingBox.min.z -= margin0;
  68837. boundingBox.max.z += margin1;
  68838. this.boundingBox = boundingBox;
  68839. /* if(!this.debugBox){
  68840. this.debugBox = new THREE.Mesh(boxGeo, boxMat)
  68841. this.add(this.debugBox)
  68842. }
  68843. this.debugBox.scale.copy(boundingBox.getSize(new THREE.Vector3))
  68844. this.debugBox.position.copy(boundingBox.getCenter(new THREE.Vector3)) */
  68845. }
  68846. createGeometry() {
  68847. this.particleArray = [];
  68848. var positions = [];
  68849. var colors = [];
  68850. var alives = [];
  68851. var opacitys = [];
  68852. var sizes = [];
  68853. var angles = [];
  68854. var count, points;
  68855. if (this.positions.length > 1) {
  68856. var spaceDis = 0.6; //间隔距离
  68857. count = Math.ceil(this.curve.wholeLength / spaceDis) + 1;
  68858. points = this.curve.getSpacedPoints(count);
  68859. count = points.length;
  68860. /* points.forEach(e=> {
  68861. var sphere = debugSphere.clone();
  68862. sphere.position.copy(e)
  68863. viewer.scene.scene.add(sphere)
  68864. }) */
  68865. var haventGetPoints = points.slice();
  68866. var getRanPoints = function getRanPoints(i) {
  68867. var a = Math.random();
  68868. var choseIndex = Math.floor(haventGetPoints.length * a);
  68869. var point = haventGetPoints[choseIndex];
  68870. if (haventGetPoints.length == 1) {
  68871. haventGetPoints = points.slice();
  68872. } else {
  68873. haventGetPoints.splice(choseIndex, 1);
  68874. }
  68875. return point;
  68876. };
  68877. this.getBound(points);
  68878. } else {
  68879. this.getBound(this.positions);
  68880. }
  68881. for (var i = 0; i < this.particleCount; i++) {
  68882. var center = new Vector3().copy(this.positions.length > 1 ? getRanPoints(i) : this.positions[0]);
  68883. //var center = new THREE.Vector3().copy(this.positions.length>1 ? points[Math.floor(i/this.particleCount * count)] : this.positions[0])
  68884. // remove duplicate code somehow, here and in update function below.
  68885. this.particleArray[i] = this.createParticle(center);
  68886. positions[3 * i] = this.particleArray[i].position.x;
  68887. positions[3 * i + 1] = this.particleArray[i].position.y;
  68888. positions[3 * i + 2] = this.particleArray[i].position.z;
  68889. colors[3 * i] = this.particleArray[i].color.r;
  68890. colors[3 * i + 1] = this.particleArray[i].color.g;
  68891. colors[3 * i + 2] = this.particleArray[i].color.b;
  68892. alives[i] = this.particleArray[i].alive;
  68893. opacitys[i] = this.particleArray[i].opacity;
  68894. sizes[i] = this.particleArray[i].size;
  68895. angles[i] = this.particleArray[i].angle;
  68896. }
  68897. this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
  68898. this.geometry.setAttribute('customColor', new BufferAttribute(new Float32Array(colors), 3));
  68899. this.geometry.setAttribute('customVisible', new BufferAttribute(new Float32Array(alives), 1));
  68900. this.geometry.setAttribute('customOpacity', new BufferAttribute(new Float32Array(opacitys), 1));
  68901. this.geometry.setAttribute('customSize', new BufferAttribute(new Float32Array(sizes), 1));
  68902. this.geometry.setAttribute('customAngle', new BufferAttribute(new Float32Array(angles), 1));
  68903. }
  68904. createMaterial() {
  68905. this.material = new ShaderMaterial({
  68906. uniforms: {
  68907. u_sampler: {
  68908. type: "t",
  68909. value: getTexture$1()
  68910. },
  68911. heightOfNearPlane: {
  68912. type: "f",
  68913. value: 0
  68914. } //相对far ,以确保画面缩放时点的大小也会缩放
  68915. },
  68916. vertexShader: vertexShader$1,
  68917. vertexShader: vertexShader$1,
  68918. fragmentShader: fragmentShader$1,
  68919. transparent: true,
  68920. alphaTest: 0.5,
  68921. // if having transparency issues, try including: alphaTest: 0.5,
  68922. blending: this.blendStyle,
  68923. depthTest: this.blendStyle != NormalBlending
  68924. });
  68925. this.setPerspective(this.fov, this.screenHeight);
  68926. }
  68927. update(dt) {
  68928. if (!Potree.Utils.getObjVisiByReason(this, 'force')) {
  68929. //被手动隐藏了
  68930. return;
  68931. }
  68932. if (!Potree.Utils.isInsideFrustum(this.boundingBox, viewer.scene.getActiveCamera())) {
  68933. Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围
  68934. //console.log('unvi')
  68935. return;
  68936. } else {
  68937. Potree.Utils.updateVisible(this, 'isInsideFrustum', true);
  68938. }
  68939. if (dt > 1) {
  68940. console.log('update dt>1', dt);
  68941. }
  68942. //dt *= 0.5;
  68943. var recycleIndices = [];
  68944. var recycleAges = [];
  68945. var positions = [];
  68946. var colors = [];
  68947. var alives = [];
  68948. var opacitys = [];
  68949. var sizes = [];
  68950. var angles = [];
  68951. for (var i = 0; i < this.particleCount; i++) {
  68952. if (this.particleArray[i].alive) {
  68953. if (this.velocityStyle == 'cube') {
  68954. //一定几率改变下方向
  68955. var ratio = Math.random();
  68956. if (this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge * ratio) {
  68957. this.particleArray[i].velocity = this.randomVector3(this.velocityBase, this.velocitySpread);
  68958. this.particleArray[i].lastChangeVage = this.particleArray[i].age;
  68959. }
  68960. } else {
  68961. /* if(this.particleArray[i].age - this.particleArray[i].lastChangeVage > this.particleDeathAge*0.3 ){
  68962. if( Math.random()>0.1){//一定几率改变下方向
  68963. var speed = this.randomValue( this.speedBase, this.speedSpread );
  68964. this.particleArray[i].velocity = this.randomVector3( new THREE.Vector3, new THREE.Vector3(1,1,1) );
  68965. this.particleArray[i].velocity.normalize().multiplyScalar( speed );
  68966. }
  68967. this.particleArray[i].lastChangeVage = this.particleArray[i].age
  68968. } */
  68969. }
  68970. this.particleArray[i].update(dt);
  68971. // check if particle should expire
  68972. // could also use: death by size<0 or alpha<0.
  68973. if (this.particleArray[i].age > this.particleDeathAge) {
  68974. this.particleArray[i].alive = 0.0;
  68975. recycleIndices.push(i);
  68976. recycleAges.push((this.particleArray[i].age - this.particleDeathAge) % this.particleDeathAge);
  68977. }
  68978. // update particle properties in shader
  68979. positions[3 * i] = this.particleArray[i].position.x;
  68980. positions[3 * i + 1] = this.particleArray[i].position.y;
  68981. positions[3 * i + 2] = this.particleArray[i].position.z;
  68982. colors[3 * i] = this.particleArray[i].color.r;
  68983. colors[3 * i + 1] = this.particleArray[i].color.g;
  68984. colors[3 * i + 2] = this.particleArray[i].color.b;
  68985. alives[i] = this.particleArray[i].alive;
  68986. opacitys[i] = this.particleArray[i].opacity;
  68987. sizes[i] = this.particleArray[i].size;
  68988. angles[i] = this.particleArray[i].angle;
  68989. }
  68990. }
  68991. // check if particle emitter is still running
  68992. //if ( !this.emitterAlive ) return;
  68993. this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
  68994. this.geometry.setAttribute('customColor', new BufferAttribute(new Float32Array(colors), 3));
  68995. this.geometry.setAttribute('customVisible', new BufferAttribute(new Float32Array(alives), 1));
  68996. this.geometry.setAttribute('customOpacity', new BufferAttribute(new Float32Array(opacitys), 1));
  68997. this.geometry.setAttribute('customSize', new BufferAttribute(new Float32Array(sizes), 1));
  68998. this.geometry.setAttribute('customAngle', new BufferAttribute(new Float32Array(angles), 1));
  68999. this.geometry.attributes.customColor.needsUpdate = true;
  69000. this.geometry.attributes.customVisible.needsUpdate = true;
  69001. this.geometry.attributes.customOpacity.needsUpdate = true;
  69002. this.geometry.attributes.customSize.needsUpdate = true;
  69003. this.geometry.attributes.customAngle.needsUpdate = true;
  69004. // if no particles have died yet, then there are still particles to activate
  69005. if (this.emitterAge < this.particleDeathAge)
  69006. //开始时一个个放出来
  69007. {
  69008. var particlesPerSecond = this.particleCount / this.particleDeathAge;
  69009. // determine indices of particles to activate
  69010. var startIndex = Math.round(particlesPerSecond * (this.emitterAge + 0));
  69011. var endIndex = Math.round(particlesPerSecond * (this.emitterAge + dt));
  69012. if (endIndex > this.particleCount) endIndex = this.particleCount;
  69013. for (var i = startIndex; i < endIndex; i++) this.particleArray[i].alive = 1.0;
  69014. }
  69015. // if any particles have died while the emitter is still running, we imediately recycle them
  69016. for (var j = 0; j < recycleIndices.length; j++) {
  69017. var i = recycleIndices[j];
  69018. this.particleArray[i] = this.createParticle(this.particleArray[i].center);
  69019. this.particleArray[i].alive = 1.0; // activate right away
  69020. this.particleArray[i].age = recycleAges[j];
  69021. positions[3 * i] = this.particleArray[i].position.x;
  69022. positions[3 * i + 1] = this.particleArray[i].position.y;
  69023. positions[3 * i + 2] = this.particleArray[i].position.z;
  69024. }
  69025. this.geometry.setAttribute('position', new BufferAttribute(new Float32Array(positions), 3));
  69026. this.geometry.attributes.position.needsUpdate = true;
  69027. // stop emitter?
  69028. this.emitterAge += dt;
  69029. //if ( this.emitterAge > this.emitterDeathAge ) this.emitterAlive = false;
  69030. }
  69031. randomValue(base, spread) {
  69032. //return base + spread * (Math.random() - 0.5);
  69033. var p = Math.random();
  69034. return base * p + spread * (1 - p);
  69035. }
  69036. randomVector3(base, spread) {
  69037. var rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  69038. return new Vector3().addVectors(base, new Vector3().multiplyVectors(spread, rand3));
  69039. }
  69040. setSize(e) {
  69041. var viewport = e.viewport;
  69042. this.screenHeight = viewport.resolution.y;
  69043. this.setPerspective(this.fov, this.screenHeight);
  69044. }
  69045. setFov(fov) {
  69046. this.fov = fov;
  69047. this.setPerspective(this.fov, this.screenHeight);
  69048. }
  69049. setPerspective(fov, height) {
  69050. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  69051. var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  69052. this.material.uniforms.heightOfNearPlane.value = far;
  69053. }
  69054. dispose() {
  69055. this.geometry.dispose();
  69056. this.material.dispose();
  69057. this.dispatchEvent('dispose');
  69058. }
  69059. }
  69060. /*
  69061. 改进:如果有必要
  69062. 根据curve中分成的点,分成多个簇,每个簇掌管该部分的可见性和particle的数量。
  69063. 在camera_changed时根据远近修改每个簇的particle的数量,当然不会大于初始创建的个数。多出的随机隐藏。
  69064. */
  69065. var vertexShader$2 = "\n attribute vec3 color;\n attribute float size;\n attribute float angle;\n attribute float opacity;\n attribute float visible;\n varying vec4 vColor;\n varying float vAngle;\n uniform float heightOfNearPlane;\n \n void main() {\n if(visible > 0.5) {\n vColor = vec4(color, opacity);\n } else {\n vColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n vAngle = angle;\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n gl_Position = projectionMatrix * mvPosition;\n \n gl_PointSize = ( heightOfNearPlane * size ) / gl_Position.w;\n }\n";
  69066. var fragmentShader$2 = "\n uniform sampler2D u_sampler;\n varying vec4 vColor;\n varying float vAngle;\n void main() {\n gl_FragColor = vColor;\n float u = cos(vAngle);\n float v = sin(vAngle);\n vec2 uv = vec2(\n u * (gl_PointCoord.x - 0.5) + v * (gl_PointCoord.y - 0.5) + 0.5, \n u * (gl_PointCoord.y - 0.5) - v * (gl_PointCoord.x - 0.5) + 0.5\n );\n vec4 texture = texture2D(u_sampler, uv);\n gl_FragColor = gl_FragColor * texture;\n }\n";
  69067. // import { vertexShader, fragmentShader } from './shader'
  69068. var DEG2RAD = Math.PI / 180;
  69069. class Particle$2 {
  69070. constructor() {
  69071. this.position = new Vector3();
  69072. this.velocity = new Vector3();
  69073. this.angle = 0;
  69074. this.angleVelocity = 0;
  69075. this.angleAcceleration = 0;
  69076. this.size = 16;
  69077. this.color = new Color();
  69078. this.opacity = 1;
  69079. this.rebornCount = 0; //重生次数
  69080. this.age = 0;
  69081. this.alive = 0; //注意,一开始时是未出生的
  69082. this.deadAge = 0; //已死亡时间
  69083. this.sizeTween = null;
  69084. this.colorTween = null;
  69085. this.opacityTween = null;
  69086. }
  69087. update(dt) {
  69088. //s = s0 + (v0 + at) * t 或 lastS + delta(vt)
  69089. this.position.add(this.velocity.clone().multiplyScalar(dt));
  69090. this.velocity.multiplyScalar(1 + this.acceleration * dt);
  69091. this.angle += this.angleVelocity * DEG2RAD * dt;
  69092. this.angleVelocity += this.angleAcceleration * DEG2RAD * dt;
  69093. this.age += dt;
  69094. if (this.sizeTween.times.length > 0) {
  69095. this.size = this.sizeTween.lerp(this.age / this.deathAge);
  69096. }
  69097. if (this.colorTween.times.length > 0) {
  69098. var colorHSL = this.colorTween.lerp(this.age / this.deathAge);
  69099. this.color = new Color().setHSL(colorHSL.x, colorHSL.y, colorHSL.z);
  69100. }
  69101. if (this.opacityTween.times.length > 0) {
  69102. this.opacity = this.opacityTween.lerp(this.age / this.deathAge);
  69103. }
  69104. viewer.dispatchEvent('content_changed');
  69105. }
  69106. }
  69107. class Util {
  69108. constructor() {}
  69109. randomValue(min, max) {
  69110. //return min + max * (Math.random() - 0.5)
  69111. var p = Math.random();
  69112. return min * p + max * (1 - p);
  69113. }
  69114. randomVector3(min, max) {
  69115. var rand3 = new Vector3(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5);
  69116. return new Vector3().addVectors(min, new Vector3().multiplyVectors(max, rand3));
  69117. }
  69118. }
  69119. var util$1 = new Util();
  69120. var Shape$1 = {
  69121. CUBE: 1,
  69122. SPHERE: 2
  69123. };
  69124. var particleTexture$1;
  69125. var getTexture$2 = () => {
  69126. if (!particleTexture$1) {
  69127. particleTexture$1 = new TextureLoader().load(Potree.resourcePath + '/textures/explode.png');
  69128. }
  69129. return particleTexture$1;
  69130. };
  69131. var sphereGeo = new SphereBufferGeometry(1, 10, 4);
  69132. var sphereMat = new MeshBasicMaterial({
  69133. wireframe: true,
  69134. color: "#ffffff"
  69135. });
  69136. var defaults$1 = {
  69137. position: new Vector3(0, 0, 1),
  69138. positionShape: Shape$1.SPHERE,
  69139. positionRange: new Vector3(1, 1, 1),
  69140. //cube
  69141. radius: 1.3,
  69142. //sphere
  69143. velocityShape: Shape$1.SPHERE,
  69144. velocity: new Vector3(0, 0, 2),
  69145. //cube
  69146. velocityRange: new Vector3(0, 0, 3),
  69147. //sphere
  69148. speed: 0.4,
  69149. speedRange: 1,
  69150. size: 0.4,
  69151. sizeRange: 2,
  69152. //sizeTween: new Tween( [0, 0.05, 0.3, 0.45], [0, 1, 3, 0.1] ),
  69153. sizeTween: [[0, 0.04, 0.2, 1], [0.1, 1, 6, 8]],
  69154. color: new Vector3(1.0, 1.0, 1.0),
  69155. colorRange: new Vector3(0, 0, 0),
  69156. colorTween: new Tween(),
  69157. opacity: 1.0,
  69158. opacityRange: 0.0,
  69159. opacityTween: new Tween([0, 0.06, 0.3, 0.8, 1], [0, 1, 0.3, 0.05, 0]),
  69160. blendMode: AdditiveBlending,
  69161. acceleration: 0.5,
  69162. accelerationRange: 0,
  69163. angle: 0,
  69164. angleRange: 0,
  69165. angleVelocity: 0,
  69166. angleVelocityRange: 0,
  69167. angleAcceleration: 0,
  69168. angleAccelerationRange: 0,
  69169. strength: 1,
  69170. //particlesPerSecond: 8,
  69171. particleDeathAge: 0.7,
  69172. recycleTimes: 3,
  69173. //每个粒子在一次爆炸后循环次数,循环完毕进入particleSpaceTime,等待下一次爆炸.
  69174. //爆炸时长: particleDeathAge * (recycleTimes+1)
  69175. particleSpaceTime: 3 //间隔
  69176. };
  69177. class ExplodeParticle extends Points {
  69178. constructor(params) {
  69179. super();
  69180. this.age = 0;
  69181. this.alive = true;
  69182. //this.deathAge = 60
  69183. this.loop = true;
  69184. this.blendMode = NormalBlending;
  69185. this.setParameters(params);
  69186. this.createParticles();
  69187. this.frustumCulled = false; //似乎是禁止相机裁剪,否则会在某些角度消失。但是会不会更耗性能呢?
  69188. //------------------------------------
  69189. this.setSize({
  69190. viewport: viewer.mainViewport
  69191. });
  69192. this.setFov(viewer.fov);
  69193. var setSize = e => {
  69194. if (e.viewport.name != "MainView") return;
  69195. this.setSize(e);
  69196. };
  69197. var setFov = e => {
  69198. this.setFov(e.fov);
  69199. };
  69200. /* let reStart = (e)=>{
  69201. if(e.v){//重新一个个放出粒子,否则会一股脑儿全部出来,因为同时大于粒子周期了一起重新生成出现。
  69202. setTimeout(()=>{//会先update一次delta为pageUnvisile的时间才触发
  69203. //console.log('归零')
  69204. //this.reStart()
  69205. },1)
  69206. }
  69207. } */
  69208. viewer.addEventListener('resize', setSize);
  69209. viewer.addEventListener('fov_changed', setFov);
  69210. //viewer.addEventListener('pageVisible', reStart)
  69211. this.addEventListener('dispose', () => {
  69212. viewer.removeEventListener('resize', setSize);
  69213. viewer.removeEventListener('fov_changed', setFov);
  69214. //viewer.removeEventListener('pageVisible', reStart)
  69215. });
  69216. }
  69217. computeParams() {
  69218. if (this.curve) {
  69219. this.position.copy(this.curve.points[0]);
  69220. }
  69221. var minSize = 0.8,
  69222. maxSize = 10,
  69223. minRadiusBound = 0.2,
  69224. maxRadiusBound = 20;
  69225. var size = minSize + (maxSize - minSize) * MathUtils.smoothstep(this.radius * this.strength, minRadiusBound, maxRadiusBound);
  69226. this.sizeTween.values = this.defaultSizeTween.values.map(e => e * size);
  69227. this.particleCount = Math.ceil(this.strength * this.radius * 5 /* * this.radius * this.radius */);
  69228. this.speed = defaults$1.speed * this.radius;
  69229. this.speedRange = defaults$1.speedRange * this.radius;
  69230. console.log(this.particleCount);
  69231. {
  69232. this.boundPoints = [];
  69233. this.boundPoints.push(this.position.clone());
  69234. var _maxSize = this.sizeTween.values.slice().sort((a, b) => b - a)[0];
  69235. var margin = _maxSize * 0.35 + 0.5;
  69236. var scale = this.radius + margin;
  69237. var sphere = new Sphere(this.position, scale); //加上防止剪裁
  69238. this.boundingSphere = sphere; //虽然还是会有一些后续移动的会超出
  69239. this.boundingBox = new Box3().setFromCenterAndSize(this.position, new Vector3(scale * 2, scale * 2, scale * 2));
  69240. /* if(!this.debugSphere){
  69241. this.debugSphere = new THREE.Mesh(sphereGeo, sphereMat)
  69242. this.add(this.debugSphere)
  69243. }
  69244. this.debugSphere.scale.set(scale,scale,scale) */
  69245. }
  69246. }
  69247. getPointsForBound() {
  69248. return this.boundPoints; //可以用于expand实时bound的点, 不含particle的size等边距
  69249. }
  69250. reStart() {
  69251. this.age = 0;
  69252. this.createParticles();
  69253. }
  69254. setParameters(params) {
  69255. params = $.extend({}, defaults$1, params);
  69256. for (var key in params) {
  69257. var value = params[key];
  69258. if (key == 'position') this.position.copy(value);else if (value instanceof Array && value[0] instanceof Array) {
  69259. this[key] = new Tween(...value);
  69260. } else if (value instanceof Vector3 || value instanceof Color) {
  69261. this[key] = value.clone();
  69262. } else {
  69263. this[key] = value;
  69264. }
  69265. }
  69266. this.defaultSizeTween = this.sizeTween.clone();
  69267. //Object.assign(this, params)
  69268. this.particles = [];
  69269. this.age = 0.0;
  69270. this.alive = true;
  69271. this.geometry = new BufferGeometry();
  69272. this.computeParams();
  69273. this.material = new ShaderMaterial({
  69274. uniforms: {
  69275. u_sampler: {
  69276. value: this.texture || getTexture$2()
  69277. },
  69278. heightOfNearPlane: {
  69279. type: "f",
  69280. value: 0
  69281. } //相对far ,以确保画面缩放时点的大小也会缩放
  69282. },
  69283. vertexShader: vertexShader$2,
  69284. fragmentShader: fragmentShader$2,
  69285. transparent: true,
  69286. alphaTest: 0.5,
  69287. depthTest: this.blendMode == NormalBlending,
  69288. blending: this.blendMode
  69289. });
  69290. }
  69291. createParticles() {
  69292. this.particles = [];
  69293. var count = this.particleCount;
  69294. var positionArray = new Float32Array(count * 3);
  69295. var colorArray = new Float32Array(count * 3);
  69296. var sizeArray = new Float32Array(count);
  69297. var angleArray = new Float32Array(count);
  69298. var opacityArray = new Float32Array(count);
  69299. var visibleArray = new Float32Array(count);
  69300. for (var i = 0; i < count; i++) {
  69301. var particle = this.createParticle();
  69302. /* positionArray[i * 3] = particle.position.x
  69303. positionArray[i * 3 + 1] = particle.position.y
  69304. positionArray[i * 3 + 2] = particle.position.z
  69305. colorArray[i * 3] = particle.color.r
  69306. colorArray[i * 3 + 1] = particle.color.g
  69307. colorArray[i * 3 + 2] = particle.color.b
  69308. sizeArray[i] = particle.size
  69309. angleArray[i] = particle.angel
  69310. opacityArray[i] = particle.opacity
  69311. visibleArray[i] = particle.alive */
  69312. this.particles[i] = particle;
  69313. }
  69314. this.geometry.setAttribute('position', new BufferAttribute(positionArray, 3));
  69315. this.geometry.setAttribute('color', new BufferAttribute(colorArray, 3));
  69316. this.geometry.setAttribute('angle', new BufferAttribute(angleArray, 1));
  69317. this.geometry.setAttribute('size', new BufferAttribute(sizeArray, 1));
  69318. this.geometry.setAttribute('visible', new BufferAttribute(visibleArray, 1));
  69319. this.geometry.setAttribute('opacity', new BufferAttribute(opacityArray, 1));
  69320. }
  69321. createParticle() {
  69322. var particle = new Particle$2();
  69323. particle.sizeTween = this.sizeTween;
  69324. particle.colorTween = this.colorTween;
  69325. particle.opacityTween = this.opacityTween;
  69326. particle.deathAge = this.particleDeathAge;
  69327. if (this.positionShape == Shape$1.CUBE) {
  69328. particle.position = util$1.randomVector3(new Vector3(), this.positionRange);
  69329. }
  69330. if (this.positionShape == Shape$1.SPHERE) {
  69331. /* const z = 2 * Math.random() - 1
  69332. const t = Math.PI * 2 * Math.random()
  69333. const r = Math.sqrt(1 - z*z)
  69334. const vec3 = new THREE.Vector3(r * Math.cos(t), r * Math.sin(t), z)
  69335. particle.position = vec3.multiplyScalar(this.radius) */
  69336. var y = 2 * Math.random() - 1;
  69337. var t = Math.PI * 2 * Math.random();
  69338. var r = Math.sqrt(1 - y * y);
  69339. var vec3 = new Vector3(r * Math.cos(t), y, r * Math.sin(t));
  69340. particle.position = vec3.multiplyScalar(this.radius);
  69341. }
  69342. if (this.velocityShape == Shape$1.CUBE) {
  69343. particle.velocity = util$1.randomVector3(this.velocity, this.velocityRange);
  69344. }
  69345. if (this.velocityShape == Shape$1.SPHERE) {
  69346. var direction = new Vector3().addVectors(particle.position, new Vector3(0, 0, this.radius * 2)); //向上升?
  69347. var speed = util$1.randomValue(this.speed, this.speedRange);
  69348. particle.velocity = direction.normalize().multiplyScalar(speed);
  69349. }
  69350. particle.acceleration = util$1.randomValue(this.acceleration, this.accelerationRange);
  69351. particle.angle = util$1.randomValue(this.angle, this.angleRange);
  69352. particle.angleVelocity = util$1.randomValue(this.angleVelocity, this.angleVelocityRange);
  69353. particle.angleAcceleration = util$1.randomValue(this.angleAcceleration, this.angleAccelerationRange);
  69354. particle.size = util$1.randomValue(this.size, this.sizeRange);
  69355. var color = util$1.randomVector3(this.color, this.colorRange);
  69356. particle.color = new Color().setHSL(color.x, color.y, color.z);
  69357. particle.opacity = util$1.randomValue(this.opacity, this.opacityRange);
  69358. return particle;
  69359. }
  69360. update(dt) {
  69361. if (!Potree.Utils.getObjVisiByReason(this, 'force')) {
  69362. //被手动隐藏了
  69363. return;
  69364. }
  69365. if (this.delayStartTime > 0) {
  69366. // 爆炸延迟
  69367. return this.delayStartTime -= dt;
  69368. }
  69369. if (!Potree.Utils.isInsideFrustum(this.boundingSphere, viewer.scene.getActiveCamera())) {
  69370. Potree.Utils.updateVisible(this, 'isInsideFrustum', false); //不在视野范围
  69371. return;
  69372. } else {
  69373. Potree.Utils.updateVisible(this, 'isInsideFrustum', true);
  69374. }
  69375. //const timeRatio = 0.5
  69376. if (dt > 1) {
  69377. console.log('update dt>1', dt);
  69378. }
  69379. //dt *= timeRatio
  69380. var particleDeathAge = this.particleDeathAge; /* * timeRatio */
  69381. var particleSpaceTime = this.particleSpaceTime; /* * timeRatio */
  69382. var recycleIndices = [];
  69383. var recycleAges = [];
  69384. var recycleRebornCount = [];
  69385. var positionArray = this.geometry.attributes.position.array;
  69386. var opacityArray = this.geometry.attributes.opacity.array;
  69387. var visibleArray = this.geometry.attributes.visible.array;
  69388. var colorArray = this.geometry.attributes.color.array;
  69389. var angleArray = this.geometry.attributes.angle.array;
  69390. var sizeArray = this.geometry.attributes.size.array;
  69391. for (var i = 0; i < this.particleCount; i++) {
  69392. var particle = this.particles[i];
  69393. if (particle.alive) {
  69394. particle.update(dt);
  69395. if (particle.age > particleDeathAge) {
  69396. particle.alive = 0.0;
  69397. if (particle.rebornCount >= this.recycleTimes) {
  69398. particle.deadAge = particle.age - particleDeathAge; //已死亡时间
  69399. } else {
  69400. //直接循环
  69401. recycleIndices.push(i);
  69402. recycleAges.push( /* ( */particle.age - particleDeathAge /* )%(this.particleDeathAge ) */);
  69403. recycleRebornCount.push(particle.rebornCount + 1);
  69404. }
  69405. }
  69406. positionArray[i * 3] = particle.position.x;
  69407. positionArray[i * 3 + 1] = particle.position.y;
  69408. positionArray[i * 3 + 2] = particle.position.z;
  69409. colorArray[i * 3] = particle.color.r;
  69410. colorArray[i * 3 + 1] = particle.color.g;
  69411. colorArray[i * 3 + 2] = particle.color.b;
  69412. visibleArray[i] = particle.alive;
  69413. opacityArray[i] = particle.opacity;
  69414. angleArray[i] = particle.angle;
  69415. sizeArray[i] = particle.size;
  69416. } else {
  69417. if (particle.rebornCount >= this.recycleTimes) {
  69418. if (particle.age > particleDeathAge) {
  69419. //其他已经死亡的粒子的时间继续增加
  69420. particle.deadAge += dt;
  69421. }
  69422. }
  69423. }
  69424. if (particle.rebornCount >= this.recycleTimes && particle.age > particleDeathAge) {
  69425. //已经死亡
  69426. if (particle.deadAge >= particleSpaceTime) {
  69427. //死亡时间超过设定的间隔时间后重启
  69428. recycleIndices.push(i);
  69429. var wholeTime = particleDeathAge * (this.recycleTimes + 1) + particleSpaceTime;
  69430. recycleAges.push((particle.deadAge - particleSpaceTime) % wholeTime); //剩余时间就是重生后的age
  69431. recycleRebornCount.push(0);
  69432. }
  69433. }
  69434. }
  69435. this.geometry.attributes.size.needsUpdate = true;
  69436. this.geometry.attributes.color.needsUpdate = true;
  69437. this.geometry.attributes.angle.needsUpdate = true;
  69438. this.geometry.attributes.visible.needsUpdate = true;
  69439. this.geometry.attributes.opacity.needsUpdate = true;
  69440. this.geometry.attributes.position.needsUpdate = true;
  69441. if (!this.alive) return;
  69442. if (this.age < particleDeathAge) {
  69443. var startIndex = Math.round(this.particleCount * (this.age + 0) / particleDeathAge);
  69444. var endIndex = Math.round(this.particleCount * (this.age + dt) / particleDeathAge);
  69445. if (endIndex > this.particleCount) {
  69446. endIndex = this.particleCount;
  69447. }
  69448. for (var _i = startIndex; _i < endIndex; _i++) {
  69449. this.particles[_i].alive = 1.0;
  69450. }
  69451. }
  69452. for (var j = 0; j < recycleIndices.length; j++) {
  69453. var _i2 = recycleIndices[j];
  69454. this.particles[_i2] = this.createParticle();
  69455. this.particles[_i2].alive = 1.0; //出生
  69456. this.particles[_i2].age = recycleAges[j];
  69457. this.particles[_i2].rebornCount = recycleRebornCount[j];
  69458. /* if(this.particles[i].age < particleDeathAge){
  69459. positionArray[i * 3] = this.particles[i].position.x
  69460. positionArray[i * 3 + 1] = this.particles[i].position.y
  69461. positionArray[i * 3 + 2] = this.particles[i].position.z
  69462. visibleArray[i] = particle.alive?
  69463. } */
  69464. }
  69465. this.geometry.attributes.position.needsUpdate = true;
  69466. this.age += dt;
  69467. if (this.age > this.deathAge && !this.loop) {
  69468. this.alive = false;
  69469. }
  69470. }
  69471. setSize(e) {
  69472. var viewport = e.viewport;
  69473. this.screenHeight = viewport.resolution.y;
  69474. this.setPerspective(this.fov, this.screenHeight);
  69475. }
  69476. setFov(fov) {
  69477. this.fov = fov;
  69478. this.setPerspective(this.fov, this.screenHeight);
  69479. }
  69480. setPerspective(fov, height) {
  69481. //this.uniforms.heightOfNearPlane.value = Math.abs(height / (2 * Math.tan(THREE.Math.degToRad(fov * 0.5))));
  69482. var far = Math.abs(height / (2 * Math.tan(MathUtils.degToRad(fov * 0.5))));
  69483. this.material.uniforms.heightOfNearPlane.value = far;
  69484. }
  69485. updateGeometry() {
  69486. this.computeParams();
  69487. this.reStart();
  69488. }
  69489. dispose() {
  69490. this.geometry.dispose();
  69491. this.material.dispose();
  69492. this.dispatchEvent('dispose');
  69493. }
  69494. }
  69495. var colors$2 = {
  69496. 'fire+smoke': 0xffffff,
  69497. 'smoke': 0xffffff,
  69498. 'explode': 0xffffff
  69499. };
  69500. var depthMatPrefix = {
  69501. clipDistance: 100,
  69502. occlusionDistance: 60,
  69503. /* 变为backColor距离 */
  69504. maxClipFactor: 0.5,
  69505. backColor: "#777",
  69506. useDepth: true,
  69507. transparent: !0
  69508. };
  69509. var lineMats$2;
  69510. var getLineMat$1 = function getLineMat(type) {
  69511. if (!lineMats$2) {
  69512. lineMats$2 = {
  69513. 'fire+smoke': LineDraw.createFatLineMat($.extend(depthMatPrefix, {
  69514. color: colors$2['fire+smoke'],
  69515. lineWidth: 2
  69516. })),
  69517. 'smoke': LineDraw.createFatLineMat($.extend(depthMatPrefix, {
  69518. color: colors$2['smoke'],
  69519. lineWidth: 2
  69520. })),
  69521. 'explode': LineDraw.createFatLineMat($.extend(depthMatPrefix, {
  69522. color: colors$2['explode'],
  69523. lineWidth: 2
  69524. }))
  69525. };
  69526. }
  69527. return lineMats$2[type];
  69528. };
  69529. var handleMats;
  69530. var getHandleMat = function getHandleMat(type) {
  69531. if (!handleMats) {
  69532. var texLoader = new TextureLoader();
  69533. handleMats = {
  69534. "fire+smoke": new DepthBasicMaterial($.extend(depthMatPrefix, {
  69535. map: texLoader.load(Potree.resourcePath + '/textures/icon-fire.png'),
  69536. color: colors$2['fire+smoke']
  69537. })),
  69538. "smoke": new DepthBasicMaterial($.extend(depthMatPrefix, {
  69539. map: texLoader.load(Potree.resourcePath + '/textures/icon-smoke.png'),
  69540. color: colors$2['smoke']
  69541. })),
  69542. "explode": new DepthBasicMaterial($.extend(depthMatPrefix, {
  69543. map: texLoader.load(Potree.resourcePath + '/textures/icon-explode.png'),
  69544. color: colors$2['explode']
  69545. }))
  69546. };
  69547. }
  69548. return handleMats[type];
  69549. };
  69550. var ParticleEditor = {
  69551. bus: new EventDispatcher(),
  69552. particleGroup: new Object3D(),
  69553. curveGroup: new Object3D(),
  69554. init: function init() {
  69555. this.particleGroup.name = 'particles';
  69556. viewer.scene.scene.add(this.particleGroup);
  69557. this.curveGroup.name = 'particles-curves';
  69558. viewer.scene.scene.add(this.curveGroup);
  69559. },
  69560. addParticle: function addParticle() {
  69561. var prop = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  69562. var particle;
  69563. if (prop.type == 'fire') {
  69564. particle = new FireParticle(prop);
  69565. } else if (prop.type == 'smoke') {
  69566. particle = new SmokeParticle(prop);
  69567. } else if (prop.type == 'explode') {
  69568. particle = new ExplodeParticle(prop);
  69569. }
  69570. this.particleGroup.add(particle);
  69571. return particle;
  69572. },
  69573. removeParticle(particle) {
  69574. //particle.dispatchEvent('delete')
  69575. particle.dispose();
  69576. this.particleGroup.remove(particle);
  69577. particle.curve.dispose();
  69578. },
  69579. update(delta) {
  69580. this.particleGroup.children.forEach(e => e.update(delta));
  69581. },
  69582. startInsertion() {
  69583. var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'fire';
  69584. var prop = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  69585. //viewer.modules.ParticleEditor.startInsertion()
  69586. var deferred = $.Deferred();
  69587. var particles = [];
  69588. var finish = ifDone => {
  69589. if (ifDone) {
  69590. deferred.resolve(particles);
  69591. }
  69592. viewer.dispatchEvent({
  69593. type: "CursorChange",
  69594. action: "remove",
  69595. name: "addSth"
  69596. });
  69597. viewer.removeEventListener('global_click', click);
  69598. this.bus.removeEventListener('cancel_insertions', cancel);
  69599. };
  69600. var curve = new CurveCtrl([], getLineMat$1(type), colors$2[type], type + '_curve', {
  69601. handleMat: getHandleMat(type)
  69602. });
  69603. this.curveGroup.add(curve);
  69604. prop.curve = curve;
  69605. prop.type = type;
  69606. //console.log('创建curve',type,curve.uuid)
  69607. var cancel = () => {
  69608. console.log('cancel_insertions', curve.uuid);
  69609. curve.dispose();
  69610. finish(false);
  69611. };
  69612. this.bus.dispatchEvent('cancel_insertions'); //删除旧的
  69613. this.bus.addEventListener('cancel_insertions', cancel);
  69614. var click = e => {
  69615. if (e.button === MOUSE.RIGHT) {
  69616. if (curve.points.length >= 1) {
  69617. //if(type.includes('fire') || type.includes('smoke') ){
  69618. particles = this.createFromData(prop);
  69619. finish(true);
  69620. }
  69621. return;
  69622. }
  69623. var I = e.intersect && (e.intersect.orthoIntersect || e.intersect.location);
  69624. if (!I) return;
  69625. curve.addPoint(I, null, true);
  69626. if (type == 'explode') {
  69627. particles = this.createFromData(prop);
  69628. finish(true);
  69629. }
  69630. return {
  69631. stopContinue: true
  69632. }; //防止继续执行别的侦听,如flytopano
  69633. };
  69634. viewer.addEventListener('global_click', click, {
  69635. importance: 10
  69636. }); //add importance
  69637. viewer.dispatchEvent({
  69638. type: "CursorChange",
  69639. action: "add",
  69640. name: "addSth"
  69641. });
  69642. return deferred.promise();
  69643. },
  69644. createFromData(prop) {
  69645. var type = prop.type;
  69646. var particles = [];
  69647. var curve = prop.curve;
  69648. if (!curve) {
  69649. curve = new CurveCtrl(prop.points, getLineMat$1(type), colors$2[type], type + '_curve', {
  69650. handleMat: getHandleMat(type)
  69651. });
  69652. this.curveGroup.add(curve);
  69653. }
  69654. if (type.includes('fire') || type.includes('smoke')) {
  69655. if (type.includes('fire')) {
  69656. var fire = this.addParticle({
  69657. type: 'fire',
  69658. positions: curve.points,
  69659. curve,
  69660. radius: prop.radius,
  69661. height: prop.height,
  69662. strength: prop.strength
  69663. });
  69664. particles.push(fire);
  69665. }
  69666. if (type.includes('smoke')) {
  69667. var smoke = this.addParticle({
  69668. type: 'smoke',
  69669. positions: curve.points,
  69670. curve,
  69671. positionStyle: 'sphere',
  69672. strength: prop.smokeStrength,
  69673. radius: prop.smokeRadius,
  69674. height: prop.smokeHeight
  69675. });
  69676. particles.push(smoke);
  69677. }
  69678. } else if (type == 'explode') {
  69679. var explode = this.addParticle({
  69680. type: 'explode',
  69681. position: curve.points[0],
  69682. strength: prop.strength,
  69683. radius: prop.radius,
  69684. particleSpaceTime: prop.particleSpaceTime,
  69685. curve,
  69686. delayStartTime: prop.delayStartTime
  69687. });
  69688. particles.push(explode);
  69689. }
  69690. curve.addEventListener('dragCurvePoint', () => {
  69691. Common.intervalTool.isWaiting('particlePointChange', () => {
  69692. //延时update,防止卡顿
  69693. particles.forEach(e => e.updateGeometry());
  69694. //geoNeedsUpdate = false
  69695. curve.dispatchEvent('sendUpdatePoints');
  69696. }, 400);
  69697. });
  69698. return particles;
  69699. }
  69700. };
  69701. var CamAniEditor = {
  69702. createAnimation(data) {
  69703. var animation = new CameraAnimation$1(viewer);
  69704. if (data) {
  69705. animation.name = data.name;
  69706. animation.duration = data.duration;
  69707. animation.useDurSlice = data.useDurSlice;
  69708. for (var cpdata of data.points) {
  69709. /* const position = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.position, datasetId: Potree.settings.originDatasetId })
  69710. const target = Potree.Utils.datasetPosTransform({ fromDataset: true, position: cpdata.target, datasetId: Potree.settings.originDatasetId })
  69711. */
  69712. var position = new Vector3().copy(cpdata.position);
  69713. var target = new Vector3().copy(cpdata.target);
  69714. var duration = cpdata.time;
  69715. var cp = animation.createControlPoint(null, {
  69716. position,
  69717. target,
  69718. duration
  69719. });
  69720. }
  69721. }
  69722. animation.changeCallback();
  69723. viewer.scene.addCameraAnimation(animation);
  69724. return animation;
  69725. },
  69726. removeAnimation(animation) {
  69727. animation.dispatchEvent('dispose');
  69728. viewer.scene.removeCameraAnimation(animation);
  69729. }
  69730. };
  69731. var clickPanoToDisLink = false; //是否在编辑漫游点连接时,通过点击漫游点能断开连接
  69732. var images360, Alignment$1, SiteModel$1, suggestCircleMat;
  69733. var texLoader$c = new TextureLoader();
  69734. texLoader$c.crossOrigin = "anonymous";
  69735. var rotQua = new Quaternion().setFromAxisAngle(new Vector3(0, 0, 1), Math.PI);
  69736. var lineMats$3 = {};
  69737. var circleMats = {};
  69738. var renderOrders$1 = {
  69739. circleSelected: 3,
  69740. circle: 2,
  69741. line: 1
  69742. };
  69743. var pointColor = {
  69744. /* selected:"#c80",
  69745. default:'#1ac' */
  69746. selected: "#c60",
  69747. default: '#17c'
  69748. };
  69749. var opacitys = {
  69750. //点云透明度
  69751. 'topView': {
  69752. default: 0.4,
  69753. selected: 0.6
  69754. },
  69755. 'sideView': {
  69756. //侧面重叠概率高
  69757. default: 0.2,
  69758. selected: 0.5
  69759. }
  69760. }; //调这么低是因为有的重叠边缘太亮了
  69761. var cameraProps$2 = [{
  69762. name: 'top',
  69763. axis: ["x", "y"],
  69764. direction: new Vector3(0, 0, -1),
  69765. //镜头朝向
  69766. openCount: 0
  69767. }, {
  69768. name: 'right',
  69769. axis: ["y", "z"],
  69770. direction: new Vector3(1, 0, 0),
  69771. openCount: 0
  69772. }, {
  69773. name: 'mainView',
  69774. openCount: 0
  69775. }];
  69776. class PanoEditor extends EventDispatcher {
  69777. constructor() {
  69778. super();
  69779. this.panoGroup = [],
  69780. //分组
  69781. this.viewports = {}, this.panoLink = {}, this.panoMeshs = new Object3D(), this.lineMeshes = new Object3D();
  69782. this.views = {};
  69783. this.cameras = {};
  69784. this.orthoCamera = new OrthographicCamera(-100, 100, 100, 100, 0.01, 10000);
  69785. this.orthoCamera.up.set(0, 0, 1);
  69786. this.selectedPano;
  69787. this.selectedGroup;
  69788. this.operation;
  69789. this.visiblePanos = [];
  69790. this.suggestLines = [];
  69791. }
  69792. init() {
  69793. {
  69794. //init lineMats
  69795. lineMats$3.default = LineDraw.createFatLineMat({
  69796. color: '#eeeeee',
  69797. lineWidth: 2,
  69798. depthTest: false
  69799. });
  69800. lineMats$3.hovered = LineDraw.createFatLineMat({
  69801. color: '#00c8af',
  69802. lineWidth: 2,
  69803. depthTest: false
  69804. });
  69805. lineMats$3.selected = LineDraw.createFatLineMat({
  69806. color: '#00c8af',
  69807. lineWidth: 3,
  69808. depthTest: false
  69809. });
  69810. lineMats$3.suggestLink = LineDraw.createFatLineMat({
  69811. color: '#ff2222',
  69812. lineWidth: 4,
  69813. dashed: true,
  69814. depthTest: false
  69815. });
  69816. }
  69817. suggestCircleMat = new MeshBasicMaterial({
  69818. map: texLoader$c.load(Potree.resourcePath + '/textures/whiteCircle.png'),
  69819. color: '#ff2222',
  69820. transparent: true,
  69821. depthTest: false,
  69822. depthWrite: false
  69823. });
  69824. this.initViews();
  69825. /* {
  69826. this.box = new BoxVolume({
  69827. clip:true
  69828. })
  69829. this.box.clipTask = ClipTask['SHOW_INSIDE_Big' ]
  69830. this.box.name = "panoEditClipBox";
  69831. } */
  69832. viewer.addEventListener('allLoaded', () => {
  69833. images360 = viewer.images360;
  69834. Alignment$1 = viewer.modules.Alignment;
  69835. SiteModel$1 = viewer.modules.SiteModel;
  69836. this.panoMeshs.name = 'panoMeshs';
  69837. viewer.scene.scene.add(this.panoMeshs);
  69838. this.lineMeshes.name = 'lineMeshes';
  69839. viewer.scene.scene.add(this.lineMeshes);
  69840. Potree.settings.ifShowMarker = false;
  69841. {
  69842. this.transformControls = new TransformControls(viewer.mainViewport.camera, viewer.renderArea, {
  69843. dontHideWhenFaceCamera: true,
  69844. rotFullCircle: true
  69845. });
  69846. this.transformControls.setSize(1.5);
  69847. viewer.scene.scene.add(this.transformControls);
  69848. this.transformControls._gizmo.hideAxis = {
  69849. /* translate:['x','y'], */rotate: ['x', 'y', 'e']
  69850. };
  69851. this.transformControls.setRotateMethod(2);
  69852. this.fakeMarkerForTran = new Mesh(new BoxBufferGeometry(0.3, 0.3, 0.3), new MeshBasicMaterial({
  69853. color: "#FFFFFF",
  69854. opacity: 0.4,
  69855. transparent: true,
  69856. visible: false
  69857. })); //一个看不见的mesh,只是为了让transformControls移动点云
  69858. viewer.scene.scene.add(this.fakeMarkerForTran);
  69859. var afterMoveCircle = type => {
  69860. if (type == 'position') {
  69861. var moveVec = new Vector3().subVectors(this.fakeMarkerForTran.position, this.fakeMarkerForTran.oldState.position);
  69862. this.selectedClouds.forEach(cloud => Alignment$1.translate(cloud, moveVec));
  69863. } else {
  69864. var center = this.selectedPano.position;
  69865. var forward = new Vector3(0, 1, 0);
  69866. var vec1 = forward.clone().applyQuaternion(this.fakeMarkerForTran.oldState.quaternion);
  69867. var vec2 = forward.clone().applyQuaternion(this.fakeMarkerForTran.quaternion);
  69868. var diffAngle = math.getAngle(vec1, vec2, 'z');
  69869. this.selectedClouds.forEach(cloud => {
  69870. Alignment$1.rotateAround(center, cloud, null, diffAngle);
  69871. });
  69872. }
  69873. this.fakeMarkerForTran.oldState = {
  69874. position: this.fakeMarkerForTran.position.clone(),
  69875. quaternion: this.fakeMarkerForTran.quaternion.clone()
  69876. };
  69877. Alignment$1.history.beforeChange(this.selectedClouds);
  69878. };
  69879. this.fakeMarkerForTran.addEventListener('position_changed', afterMoveCircle.bind(this, 'position'));
  69880. this.fakeMarkerForTran.addEventListener("rotation_changed", afterMoveCircle.bind(this, 'rotation'));
  69881. this.transformControls.addEventListener('mouseUp', () => {
  69882. Alignment$1.history.afterChange(this.selectedClouds);
  69883. });
  69884. Alignment$1.history.addEventListener('undo', () => {
  69885. this.updateTranCtl();
  69886. });
  69887. }
  69888. this.initPanoLink();
  69889. this.addPanoMesh();
  69890. viewer.scene.pointclouds.forEach(e => {
  69891. e.material.color = pointColor.default;
  69892. });
  69893. viewer.setEDLEnabled(true); //为了降一倍的绘制. 同时用描边增强立体感,弥补点云稀疏
  69894. viewer.setEDLRadius(3);
  69895. viewer.setEDLStrength(0.02);
  69896. this.switchView('top');
  69897. {
  69898. //默认选择一个楼层
  69899. var panoVisiReady, siteModelReady;
  69900. var floorInit = () => {
  69901. if (!panoVisiReady || !siteModelReady) return;
  69902. setTimeout(() => {
  69903. if (this.currentFloor == 'all') {
  69904. //还未选择楼层的话
  69905. var floor = SiteModel$1.entities.find(e => e.buildType == 'floor' && e.panos.length); //选择有漫游点的一层
  69906. if (!floor) {
  69907. floor = 'all'; //SiteModel.entities.find(e=>e.buildType == 'floor')
  69908. console.log('没有一层有漫游点?!');
  69909. }
  69910. console.log('initDataDone');
  69911. console.log('gotoFloor 1');
  69912. this.gotoFloor(floor);
  69913. }
  69914. }, 1); //2d那边用了nextTick ,so setTimeout here
  69915. };
  69916. SiteModel$1.bus.addEventListener('initDataDone', () => {
  69917. siteModelReady = true;
  69918. floorInit();
  69919. }, {
  69920. once: true
  69921. });
  69922. this.addEventListener('panoVisiReady', () => {
  69923. //2d初始化完成,才可以由3d修改pano显示 (因为在之前2d会给每个pano传来显示的消息,在这之前的修改都会别覆盖)
  69924. panoVisiReady = true;
  69925. floorInit();
  69926. }, {
  69927. once: true
  69928. });
  69929. }
  69930. Alignment$1.bus.addEventListener('switchHandle', this.updateCursor.bind(this));
  69931. viewer.addEventListener('global_click', e => {
  69932. if (e.button === MOUSE.RIGHT) {
  69933. //取消旋转和平移
  69934. //console.log('right click',e)
  69935. this.setLinkOperateState('addLink', false);
  69936. this.setLinkOperateState('removeLink', false);
  69937. } else if (this.clickToZoomInEnabled) {
  69938. if (this.activeViewName == 'mainView') {
  69939. viewer.controls.zoomToLocation(e.mouse);
  69940. } else {
  69941. this.zoomIn(e.intersect.orthoIntersect, e.pointer);
  69942. }
  69943. this.setZoomInState(false);
  69944. }
  69945. });
  69946. /* {//旋转时的辅助线--绕某个点旋转的版本
  69947. this.rotGuideLine = LineDraw.createLine([], {color:'#aaffee'})
  69948. this.rotGuideLine.visible = false
  69949. this.rotGuideLine.name = 'rotGuideLine'
  69950. this.rotGuideLine.renderOrder = renderOrders.line
  69951. viewer.scene.scene.add(this.rotGuideLine)
  69952. let startPoint
  69953. Alignment.bus.addEventListener('rotateStart', (e)=>{
  69954. startPoint = e.startPoint
  69955. })
  69956. Alignment.bus.addEventListener('rotate', (e)=>{
  69957. LineDraw.updateLine(this.rotGuideLine, [startPoint, e.endPoint] )
  69958. this.rotGuideLine.visible = true
  69959. })
  69960. viewer.fpControls.addEventListener("end",(e)=>{
  69961. startPoint = null
  69962. this.rotGuideLine.visible = false
  69963. })
  69964. } */
  69965. {
  69966. //连接时的辅助线
  69967. this.linkGuideLine = LineDraw.createLine([], {
  69968. color: '#ddd',
  69969. deshed: true,
  69970. dashSize: 0.1,
  69971. gapSize: 0.05,
  69972. depthTest: false
  69973. });
  69974. this.linkGuideLine.visible = false;
  69975. this.linkGuideLine.name = 'linkGuideLine';
  69976. viewer.scene.scene.add(this.linkGuideLine);
  69977. this.linkGuideLine.renderOrder = renderOrders$1.line;
  69978. var update = e => {
  69979. if (this.operation != 'addLink' || this.activeViewName != 'top' && this.activeViewName != 'mainView' || !this.selectedPano) {
  69980. return this.linkGuideLine.visible = false;
  69981. }
  69982. var endPos;
  69983. if (this.activeViewName == 'top') {
  69984. endPos = e.intersect.orthoIntersect.clone().setZ(this.selectedPano.position.z);
  69985. } else if (this.activeViewName == 'mainView') {
  69986. if (!e.intersect || !e.intersect.point) return;
  69987. endPos = e.intersect.point.position;
  69988. }
  69989. LineDraw.updateLine(this.linkGuideLine, [this.selectedPano.position, endPos]);
  69990. this.linkGuideLine.visible = true;
  69991. viewer.dispatchEvent('content_changed');
  69992. };
  69993. viewer.addEventListener('global_mousemove', e => {
  69994. update(e);
  69995. });
  69996. //this.addEventListener('updateLinkGuideLine', update)
  69997. }
  69998. /*
  69999. viewer.inputHandler.addEventListener('keydown', (e)=>{
  70000. if(e.event.key == "r" ){
  70001. this.setTranMode('rotate')
  70002. }else if(e.event.key == "t"){
  70003. this.setTranMode('translate')
  70004. }
  70005. }) */
  70006. /* {
  70007. viewer.addEventListener('camera_changed', (e)=>{
  70008. Common.intervalTool.isWaiting('updatePointLevels', ()=>{
  70009. this.updatePointLevels()
  70010. }, 1050)
  70011. })
  70012. setTimeout(()=>{
  70013. this.updatePointLevels()
  70014. }, viewer.scene.pointclouds.length*150) //等待差不多updat出了正确的visibleNode时
  70015. } */
  70016. this.panoReposCallback = () => {
  70017. viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动
  70018. };
  70019. });
  70020. }
  70021. setTranMode(mode) {
  70022. //rotate or translate
  70023. console.log('setTranMode', mode);
  70024. this.tranMode = mode;
  70025. if (this.activeViewName == 'mainView') {
  70026. mode && this.transformControls.setMode(mode);
  70027. this.updateTranCtl();
  70028. } else {
  70029. Alignment$1.switchHandle(mode);
  70030. }
  70031. this.updateIntersectEnable();
  70032. }
  70033. updateIntersectEnable() {
  70034. //侧面容易因intersect卡住, 如果非必要关闭intersect. 3d页面也会卡,但controls需要所以不能去掉
  70035. Potree.settings.intersectWhenHover = !!(this.activeViewName == 'mainView' || this.selectedPano && this.tranMode);
  70036. }
  70037. updateTranCtl() {
  70038. // 设置3D页面的transformControls相关
  70039. if (!this.tranMode || !this.selectedPano || this.activeViewName != 'mainView') {
  70040. return this.transformControls.detach();
  70041. } else if (this.checkIfAllLinked({
  70042. group: this.selectedGroup
  70043. })) {
  70044. this.dispatchEvent('needToDisConnect');
  70045. return this.transformControls.detach();
  70046. }
  70047. this.transformControls.attach(this.fakeMarkerForTran);
  70048. var {
  70049. position,
  70050. quaternion
  70051. } = this.getPanoPose(this.selectedPano);
  70052. this.fakeMarkerForTran.position.copy(position);
  70053. this.fakeMarkerForTran.quaternion.copy(quaternion);
  70054. this.fakeMarkerForTran.oldState = {
  70055. position: position.clone(),
  70056. quaternion: quaternion.clone()
  70057. };
  70058. }
  70059. //////////////////////////////////
  70060. initViews() {
  70061. this.splitScreenTool = new SplitScreen();
  70062. this.targetPlane = viewer.mainViewport.targetPlane = new Plane();
  70063. this.shiftTarget = viewer.mainViewport.shiftTarget = new Vector3(); //project在targetPlane上的位置
  70064. for (var i = 0; i < 2; i++) {
  70065. var prop = cameraProps$2[i];
  70066. var view = new ExtendView();
  70067. this.views[prop.name] = view;
  70068. this.cameras[prop.name] = this.orthoCamera;
  70069. view.name = prop.name;
  70070. view.direction = prop.direction;
  70071. }
  70072. this.views.mainView = viewer.mainViewport.view;
  70073. this.cameras.mainView = viewer.mainViewport.camera;
  70074. }
  70075. switchView(name) {
  70076. //替换view和camera到mainViewport
  70077. var view = this.views[name];
  70078. var camera = this.cameras[name];
  70079. var prop = cameraProps$2.find(e => e.name == name);
  70080. var {
  70081. boundSize,
  70082. center
  70083. } = viewer.bound;
  70084. this.lastViewName = this.activeViewName;
  70085. this.activeViewName = name;
  70086. var lastView = this.views[this.lastViewName];
  70087. var lastCamera = this.cameras[this.lastViewName];
  70088. viewer.mainViewport.view = view;
  70089. viewer.mainViewport.camera = camera;
  70090. if (lastCamera) lastView.zoom = lastCamera.zoom;
  70091. this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center);
  70092. this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外
  70093. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  70094. if (view.zoom) camera.zoom = view.zoom; //恢复上次的zoom
  70095. viewer.updateScreenSize({
  70096. forceUpdateSize: true
  70097. }); //更新camera aspect left等
  70098. this.updateCursor();
  70099. if (name == 'mainView') {
  70100. viewer.mainViewport.alignment = null;
  70101. var changeMat = () => {
  70102. viewer.scene.pointclouds.forEach(e => {
  70103. e.material.activeAttributeName = 'rgba';
  70104. e.material.useFilterByNormal = false;
  70105. e.changePointOpacity(1);
  70106. });
  70107. };
  70108. /* if(prop.openCount == 0){ //点数较多时,首次转到3D视角会卡顿,因为要切换材质。
  70109. let delay1 = THREE.Math.clamp(viewer.scene.pointclouds.length*0.5, 1, 200)
  70110. setTimeout(()=>{
  70111. this.activeViewName == 'mainView' && changeMat()
  70112. },delay1)
  70113. //console.log('switchview',delay1 )
  70114. }else{ */
  70115. changeMat();
  70116. //}
  70117. Potree.Utils.updateVisible(viewer.reticule, 'force', true);
  70118. if (lastView) {
  70119. //2d->3d
  70120. view.copy(lastView);
  70121. var direction = view.direction;
  70122. var panos = images360.panos.filter(e => e.circle.visible);
  70123. var nearestPano = Common.sortByScore(panos, [], [pano => {
  70124. var vec = new Vector3().subVectors(pano.position, view.position);
  70125. return -vec.dot(direction);
  70126. }], true);
  70127. //console.log('最近',nearestPano )
  70128. if (nearestPano && nearestPano[0]) {
  70129. //尽量不变画面范围,使pano点保持原位,转换到mainView
  70130. var halfHeight = lastCamera.top / lastCamera.zoom;
  70131. var dis = halfHeight / Math.tan(MathUtils.degToRad(camera.fov / 2));
  70132. view.position.add(direction.clone().multiplyScalar(-nearestPano[0].score - dis));
  70133. //console.log('getCloser', -nearestPano[0].score - dis)
  70134. this.lastDisToPano = dis; //记录一下
  70135. }
  70136. }
  70137. viewer.fpControls.lockKey = false;
  70138. } else {
  70139. if (this.lastViewName == 'mainView') {
  70140. //3d->2d
  70141. var _direction = lastView.direction;
  70142. var _panos = images360.panos.filter(e => e.circle.visible);
  70143. //尽量靠近画布中心,且距离相机较近
  70144. var _nearestPano = Common.sortByScore(_panos, [], [pano => {
  70145. var vec = new Vector3().subVectors(pano.position, lastView.position);
  70146. var dis = vec.dot(_direction);
  70147. return dis < 0 ? dis * 10 : -dis;
  70148. }, pano => {
  70149. var vec = new Vector3().subVectors(pano.position, lastView.position);
  70150. var angle = vec.angleTo(_direction);
  70151. return -angle * 70;
  70152. }], true);
  70153. //目前还存在的问题就是不知selectedPano和最近点的取舍
  70154. //console.log('panos',nearestPano )
  70155. if (_nearestPano && _nearestPano[0]) {
  70156. //console.log('nearestPano',nearestPano[0].item.id )
  70157. var pos1 = _nearestPano[0].item.position.clone();
  70158. var pos2 = pos1.clone();
  70159. var _dis = new Vector3().subVectors(_nearestPano[0].item.position, lastView.position).dot(_direction); //-nearestPano[0].score
  70160. //根据2d->3d的式子逆求zoom
  70161. var _halfHeight = Math.abs(_dis) * Math.tan(MathUtils.degToRad(lastCamera.fov / 2));
  70162. camera.zoom = camera.top / _halfHeight;
  70163. camera.updateProjectionMatrix();
  70164. if (name == 'right') {
  70165. //侧视图
  70166. view.direction = _direction.clone().setZ(0); //水平方向设定为3d的方向
  70167. this.targetPlane.setFromNormalAndCoplanarPoint(view.direction.clone(), center);
  70168. this.targetPlane.projectPoint(view.position, this.shiftTarget); //target转换到过模型中心的平面,以保证镜头一定在模型外
  70169. view.position.copy(this.splitScreenTool.getPosOutOfModel(viewer.mainViewport));
  70170. }
  70171. view.applyToCamera(camera); //update
  70172. pos1.project(lastCamera);
  70173. pos2.project(camera);
  70174. //目标是找到画面上最接近中心的一点(最好是漫游点,不然就是点云),让其在转换画面后在画面上的位置不变。万一找到的点不在屏幕中(比如当屏幕中没点云时),就默认让那个点移动到屏幕中央,也就是假设当前它pos1在屏幕中央位置。
  70175. //
  70176. if (pos1.z > 1) {
  70177. console.warn('选取的点在相机背后了!?');
  70178. }
  70179. //如果最近点超出屏幕范围 (-1,1), 最好将其拉到边缘,甚至居中 。这样屏幕上就不会没有漫游点了
  70180. var bound = 0.9;
  70181. pos1.x = MathUtils.clamp(pos1.x, -bound, bound);
  70182. pos1.y = MathUtils.clamp(pos1.y, -bound, bound);
  70183. var vecOnscreen = new Vector3().subVectors(pos1, pos2);
  70184. var moveVec = Potree.Utils.getOrthoCameraMoveVec(vecOnscreen, camera);
  70185. //console.log('pos1', pos1)
  70186. view.position.sub(moveVec);
  70187. }
  70188. } else {
  70189. if (prop.openCount == 0) {
  70190. //至多执行一次
  70191. this.viewportFitBound(name, boundSize, center);
  70192. }
  70193. }
  70194. viewer.scene.pointclouds.forEach(e => {
  70195. e.material.activeAttributeName = 'color';
  70196. e.material.useFilterByNormal = true;
  70197. var opaProp = name == 'top' ? opacitys.topView : opacitys.sideView;
  70198. if (this.selectedPano && this.selectedClouds.includes(e)) {
  70199. e.changePointOpacity(opaProp.selected, true);
  70200. e.material.color = pointColor.selected;
  70201. } else {
  70202. e.changePointOpacity(opaProp.default, true);
  70203. e.material.color = pointColor.default;
  70204. }
  70205. });
  70206. Potree.Utils.updateVisible(viewer.reticule, 'force', false);
  70207. if (name == 'top') viewer.mainViewport.alignment = {
  70208. rotate: true,
  70209. translate: true
  70210. };
  70211. if (name == 'right') {
  70212. viewer.mainViewport.alignment = {
  70213. translate: true,
  70214. rotateSide: true,
  70215. translateVec: new Vector3(0, 0, 1)
  70216. }; //只能上下移动
  70217. viewer.mainViewport.rotateSide = true;
  70218. } else {
  70219. viewer.mainViewport.rotateSide = false;
  70220. }
  70221. viewer.fpControls.lockKey = true;
  70222. }
  70223. this.updateTranCtl();
  70224. this.setTranMode(this.tranMode); // update
  70225. this.setZoomInState(false); //取消放大模式
  70226. //this.updatePointLevels()
  70227. this.updateIntersectEnable();
  70228. prop.openCount++;
  70229. }
  70230. viewportFitBound() {
  70231. //使一个viewport聚焦在某个范围
  70232. if (viewer.mainViewport.resolution.x == 0 || viewer.mainViewport.resolution.y == 0) {
  70233. return setTimeout(() => {
  70234. this.viewportFitBound();
  70235. }, 10);
  70236. }
  70237. this.gotoFloor(this.currentFloor, true, 0, null, true);
  70238. }
  70239. rotateSideCamera(angle) {
  70240. //侧视图绕模型中心水平旋转
  70241. this.splitScreenTool.rotateSideCamera(viewer.mainViewport, angle);
  70242. }
  70243. zoomIn(intersect, pointer) {
  70244. var camera = viewer.mainViewport.camera;
  70245. var endZoom = 200;
  70246. //this.orthoMoveFit(intersect, {endZoom:viewer.mainViewport.camera.zoom < aimZoom ? aimZoom : null} , 300)
  70247. var startZoom = camera.zoom;
  70248. if (startZoom >= endZoom) {
  70249. return;
  70250. }
  70251. viewer.mainViewport.view.zoomOrthoCamera(camera, endZoom, pointer, 300);
  70252. }
  70253. orthoMoveFit(pos, info, duration) {
  70254. var margin = {
  70255. x: 200,
  70256. y: 230
  70257. };
  70258. this.splitScreenTool.viewportFitBound(viewer.mainViewport, info.bound, pos, duration, margin);
  70259. }
  70260. setZoomInState(state, informinformBy2d) {
  70261. //是否点击后可放大
  70262. //if(state && this.activeViewName == 'mainView')return console.log('3D不可放大')
  70263. this.clickToZoomInEnabled = !!state;
  70264. if (state) {
  70265. viewer.dispatchEvent({
  70266. type: "CursorChange",
  70267. action: "add",
  70268. name: "zoomInCloud"
  70269. });
  70270. } else {
  70271. viewer.dispatchEvent({
  70272. type: "CursorChange",
  70273. action: "remove",
  70274. name: "zoomInCloud"
  70275. });
  70276. }
  70277. if (!state && !informinformBy2d) {
  70278. this.dispatchEvent({
  70279. type: 'operationCancel',
  70280. operation: 'zoomIn'
  70281. });
  70282. }
  70283. }
  70284. gotoFloor(floor, force) {
  70285. var duration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 600;
  70286. var informBy2d = arguments.length > 3 ? arguments[3] : undefined;
  70287. var fitBound = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true;
  70288. // 选择不同楼层, 切换点位显示。 'all'为全部显示
  70289. floor = floor || 'all';
  70290. if (this.currentFloor == floor && !force) return;
  70291. if (this.currentFloor != floor) {
  70292. //如果楼层没变,不修改可视
  70293. //let pointclouds = viewer.findPointcloudsAtFloor(floor)
  70294. var panos = floor == 'all' ? viewer.images360.panos : floor.panos;
  70295. viewer.images360.panos.forEach(pano => {
  70296. var v = panos.includes(pano);
  70297. this.switchPanoVisible(pano, v);
  70298. });
  70299. }
  70300. this.updateLinesVisible();
  70301. //切换楼层时清空选择状态
  70302. if (this.selectedPano && floor != 'all' && !floor.panos.includes(this.selectedPano)) {
  70303. this.selectedPano.circle.dispatchEvent('click');
  70304. }
  70305. if (this.selectedLine) {
  70306. this.selectedLine.dispatchEvent('click');
  70307. }
  70308. var bound, center;
  70309. if (floor == 'all') {
  70310. bound = viewer.images360.bound.bounding;
  70311. center = viewer.images360.bound.center;
  70312. } else {
  70313. bound = this.getPanosBound(floor);
  70314. center = bound.getCenter(new Vector3());
  70315. if (floor.panos.length == 0) console.log(floor.name, 'floor无漫游点');
  70316. }
  70317. if (this.activeViewName != 'mainView') {
  70318. fitBound && this.orthoMoveFit(center, {
  70319. bound
  70320. }, duration);
  70321. } else if (this.activeViewName == 'mainView') {
  70322. //if(floor != 'all'){ //切换一下位置,因为原处点云会消失
  70323. //viewer.scene.view.setView({position:center, duration })
  70324. viewer.focusOnObject({
  70325. boundingBox: bound
  70326. }, 'boundingBox');
  70327. //}
  70328. }
  70329. this.currentFloor = floor;
  70330. //if(!informBy2d){ //注释原因:2d居然不会自己变
  70331. this.dispatchEvent({
  70332. type: 'changeFloor',
  70333. floor
  70334. });
  70335. //}
  70336. }
  70337. getPanosBound(floor) {
  70338. if (!floor.panosBound) {
  70339. if (floor.panos.length == 0) {
  70340. floor.panosBound = viewer.images360.bound.bounding.clone();
  70341. } else {
  70342. var minSize = new Vector3(10, 10, 10);
  70343. var bound = math.getBoundByPoints(floor.panos.map(e => e.position), minSize);
  70344. floor.panosBound = bound.bounding;
  70345. }
  70346. }
  70347. return floor.panosBound;
  70348. }
  70349. switchPanoVisible(pano, v, informBy2d) {
  70350. //console.log(pano.id,v)
  70351. Potree.Utils.updateVisible(pano.circle, 'panoEditor', v);
  70352. Potree.Utils.updateVisible(pano, 'panoEditor', v);
  70353. Potree.Utils.updateVisible(pano.pointcloud, 'panoEditor', v);
  70354. if (v) {
  70355. this.visiblePanos.includes(pano) || this.visiblePanos.push(pano);
  70356. } else {
  70357. var index = this.visiblePanos.indexOf(pano);
  70358. index > -1 && this.visiblePanos.splice(index, 1);
  70359. }
  70360. if (informBy2d) {
  70361. this.dispatchEvent('panoVisiReady');
  70362. this.updateLinesVisible();
  70363. }
  70364. informBy2d || this.dispatchEvent({
  70365. type: "switchPanoVisible",
  70366. pano,
  70367. v
  70368. });
  70369. /* {
  70370. setTimeout(()=>{
  70371. Common.intervalTool.isWaiting('updatePointLevels2', ()=>{
  70372. this.updatePointLevels()
  70373. }, 50)
  70374. },1)//等update过visibleNodes
  70375. } */
  70376. }
  70377. updateLinesVisible() {
  70378. this.lineMeshes.children.forEach(line => {
  70379. var names = line.name.split('-');
  70380. var pano0 = images360.getPano(names[0]);
  70381. var pano1 = images360.getPano(names[1]);
  70382. line.visible = this.visiblePanos.includes(pano0) || this.visiblePanos.includes(pano1);
  70383. });
  70384. }
  70385. updateCursor() {
  70386. var cursor;
  70387. if (this.activeViewName == 'mainView' || !this.selectedPano) {
  70388. cursor = null;
  70389. } else {
  70390. cursor = Alignment$1.handleState;
  70391. }
  70392. if (cursor == 'rotate') {
  70393. viewer.dispatchEvent({
  70394. type: "CursorChange",
  70395. action: "add",
  70396. name: "rotatePointcloud"
  70397. });
  70398. viewer.dispatchEvent({
  70399. type: "CursorChange",
  70400. action: "remove",
  70401. name: "movePointcloud"
  70402. });
  70403. } else if (cursor == 'translate') {
  70404. viewer.dispatchEvent({
  70405. type: "CursorChange",
  70406. action: "add",
  70407. name: "movePointcloud"
  70408. });
  70409. viewer.dispatchEvent({
  70410. type: "CursorChange",
  70411. action: "remove",
  70412. name: "rotatePointcloud"
  70413. });
  70414. } else {
  70415. viewer.dispatchEvent({
  70416. type: "CursorChange",
  70417. action: "remove",
  70418. name: "movePointcloud"
  70419. });
  70420. viewer.dispatchEvent({
  70421. type: "CursorChange",
  70422. action: "remove",
  70423. name: "rotatePointcloud"
  70424. });
  70425. }
  70426. //this.cursorState = cursor
  70427. }
  70428. setLinkOperateState(name, state, informinformBy2d) {
  70429. if (state && name == this.operation || !state && name != this.operation) return;
  70430. var old = this.operation;
  70431. this.operation = state ? name : null;
  70432. if (this.operation == 'removeLink') {
  70433. if (this.selectedLine) {
  70434. this.selectedLine.dispatchEvent('click'); //删除
  70435. }
  70436. if (this.selectedPano && clickPanoToDisLink) {
  70437. this.selectedPano.circle.dispatchEvent('click'); //删除
  70438. }
  70439. }
  70440. if (this.operation != 'addLink') {
  70441. this.linkGuideLine.visible = false;
  70442. }
  70443. if (!state && !informinformBy2d) {
  70444. this.dispatchEvent({
  70445. type: "operationCancel",
  70446. operation: old
  70447. });
  70448. }
  70449. if (this.operation == 'addLink') {
  70450. viewer.dispatchEvent({
  70451. type: "CursorChange",
  70452. action: "add",
  70453. name: "connectPano"
  70454. });
  70455. } else {
  70456. viewer.dispatchEvent({
  70457. type: "CursorChange",
  70458. action: "remove",
  70459. name: "connectPano"
  70460. });
  70461. }
  70462. if (this.operation == 'removeLink') {
  70463. viewer.dispatchEvent({
  70464. type: "CursorChange",
  70465. action: "add",
  70466. name: "disconnectPano"
  70467. });
  70468. } else {
  70469. viewer.dispatchEvent({
  70470. type: "CursorChange",
  70471. action: "remove",
  70472. name: "disconnectPano"
  70473. });
  70474. }
  70475. viewer.dispatchEvent('content_changed');
  70476. }
  70477. /////////////////////////////////
  70478. initPanoLink() {
  70479. images360.panos.forEach(pano => {
  70480. this.panoLink[pano.id] = {};
  70481. this.panoGroup.push([pano]);
  70482. });
  70483. images360.panos.forEach(pano => {
  70484. pano.visibles.forEach(index => {
  70485. //visibles中存的是下标!
  70486. this.linkChange(pano, images360.getPano(index, 'index'), 'add');
  70487. });
  70488. });
  70489. //console.log('panoLink',this.panoLink)
  70490. }
  70491. linkChange(pano0, pano1, type) {
  70492. //修改link (type == 'remove'时,pano1可以为空)
  70493. var temp = [];
  70494. if (type == 'add') {
  70495. if (!pano1) return console.error('不支持add时pano1为空');
  70496. this.panoLink[pano0.id][pano1.id] = this.panoLink[pano0.id][pano1.id] || {};
  70497. this.panoLink[pano1.id][pano0.id] = this.panoLink[pano1.id][pano0.id] || {};
  70498. } else {
  70499. if (!pano1) {
  70500. for (var id in this.panoLink[pano0.id]) {
  70501. if (this.panoLink[pano0.id][id]) {
  70502. this.panoLink[id][pano0.id] = false;
  70503. temp.push(id);
  70504. }
  70505. }
  70506. this.panoLink[pano0.id] = {}; //全部断连
  70507. } else {
  70508. this.panoLink[pano0.id][pano1.id] = false;
  70509. this.panoLink[pano1.id][pano0.id] = false;
  70510. }
  70511. }
  70512. if (!pano1) {
  70513. //全部断连
  70514. temp.forEach(id => {
  70515. this.lineChange(pano0, images360.getPano(id), type);
  70516. });
  70517. } else {
  70518. this.lineChange(pano0, pano1, type);
  70519. }
  70520. this.groupChange(pano0, pano1, type);
  70521. //this.updateSelectGroup()
  70522. this.selectPano(this.selectedPano, false, true); //更新选中点云显示
  70523. }
  70524. lineChange(pano0, pano1, type) {
  70525. //修改line
  70526. if (type == 'add') {
  70527. if (this.panoLink[pano0.id][pano1.id].line) return;
  70528. var line = LineDraw.createFatLine([pano0.position, pano1.position], {
  70529. mat: lineMats$3.default
  70530. });
  70531. line.name = "".concat(pano0.id, "-").concat(pano1.id);
  70532. line.renderOrder = line.pickOrder = renderOrders$1.line;
  70533. this.lineMeshes.add(line);
  70534. this.panoLink[pano0.id][pano1.id].line = this.panoLink[pano1.id][pano0.id].line = line;
  70535. line.addEventListener('mouseover', () => {
  70536. if (this.clickToZoomInEnabled) return;
  70537. //if(this.activeViewName == 'mainView')return
  70538. if (this.selectedLine != line) line.material = lineMats$3.hovered;
  70539. viewer.dispatchEvent({
  70540. type: "CursorChange",
  70541. action: "add",
  70542. name: "hoverLine"
  70543. });
  70544. });
  70545. line.addEventListener('mouseleave', () => {
  70546. if (this.clickToZoomInEnabled) return;
  70547. //if(this.activeViewName == 'mainView')return
  70548. if (this.selectedLine != line) line.material = lineMats$3.default;
  70549. viewer.dispatchEvent({
  70550. type: "CursorChange",
  70551. action: "remove",
  70552. name: "hoverLine"
  70553. });
  70554. });
  70555. line.addEventListener('click', e => {
  70556. if (this.clickToZoomInEnabled) return;
  70557. //if(this.activeViewName == 'mainView')return
  70558. if (this.operation == 'removeLink') {
  70559. if (this.selectedLine == line) this.selectLine(null);
  70560. return this.linkChange(pano0, pano1, 'remove');
  70561. }
  70562. this.selectLine(line);
  70563. });
  70564. } else {
  70565. var _line = this.lineMeshes.children.find(e => e.name == "".concat(pano0.id, "-").concat(pano1.id) || e.name == "".concat(pano1.id, "-").concat(pano0.id));
  70566. if (_line) {
  70567. this.lineMeshes.remove(_line);
  70568. _line.geometry.dispose();
  70569. }
  70570. }
  70571. }
  70572. groupChange(pano0, pano1, type) {
  70573. //修改group (type == 'remove'时,pano1可以为空)
  70574. if (type == 'add') {
  70575. Common.pushToGroupAuto([pano0, pano1], this.panoGroup);
  70576. } else {
  70577. var atGroup = this.panoGroup.find(e => e.includes(pano0) && (e.includes(pano1) || !pano1)); //所在组
  70578. if (!atGroup) {
  70579. if (pano1) {
  70580. console.log('这两个pano原本就不在一个组', pano0.id, pano1.id);
  70581. } else {
  70582. console.log('pano0不在任何组', pano0);
  70583. }
  70584. return;
  70585. }
  70586. //断开连接时,因为组内没有其他成员的连接信息,所以需要清除整组,并将剩余的一个个重新连接
  70587. this.panoGroup.splice(this.panoGroup.indexOf(atGroup), 1); //删除
  70588. atGroup.forEach(pano => {
  70589. //然后再重新生成这两个和组的关系,各自分组
  70590. this.panoGroup.push([pano]);
  70591. for (var id in this.panoLink[pano.id]) {
  70592. if (this.panoLink[pano.id][id]) {
  70593. var pano_ = images360.getPano(id);
  70594. Common.pushToGroupAuto([pano, pano_], this.panoGroup);
  70595. }
  70596. }
  70597. });
  70598. }
  70599. }
  70600. selectLine(line) {
  70601. if (this.selectedLine == line) return;
  70602. if (this.selectedLine) {
  70603. this.selectedLine.material = lineMats$3.default;
  70604. }
  70605. if (line) {
  70606. line.material = lineMats$3.selected;
  70607. }
  70608. this.selectedLine = line;
  70609. }
  70610. addPanoMesh() {
  70611. var map = texLoader$c.load(Potree.resourcePath + '/textures/correct_n.png');
  70612. /* circleMats.default_normal = new THREE.MeshBasicMaterial({
  70613. map,
  70614. color: 0xffffff,
  70615. transparent: true,
  70616. depthTest: false,
  70617. depthWrite: false,
  70618. }) */
  70619. window.circleMats = circleMats;
  70620. circleMats.default_normal = new DepthBasicMaterial({
  70621. map,
  70622. color: 0xffffff,
  70623. transparent: true,
  70624. useDepth: true,
  70625. backColor: 0x33ffdd,
  70626. occlusionDistance: 10,
  70627. //变为backColor距离
  70628. clipDistance: 5,
  70629. //消失距离
  70630. maxClipFactor: 0.8,
  70631. maxOcclusionFactor: 0.8
  70632. });
  70633. circleMats.default_rtk_on = circleMats.default_normal.clone();
  70634. circleMats.default_rtk_on.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-y-n.png');
  70635. circleMats.default_rtk_off = circleMats.default_normal.clone();
  70636. circleMats.default_rtk_off.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-f-n.png');
  70637. circleMats.selected_normal = circleMats.default_normal.clone();
  70638. circleMats.selected_normal.map = texLoader$c.load(Potree.resourcePath + '/textures/correct_s.png');
  70639. circleMats.selected_normal.useDepth = false;
  70640. circleMats.selected_rtk_on = circleMats.selected_normal.clone();
  70641. circleMats.selected_rtk_on.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-y-s.png');
  70642. circleMats.selected_rtk_off = circleMats.selected_normal.clone();
  70643. circleMats.selected_rtk_off.map = texLoader$c.load(Potree.resourcePath + '/textures/rtk-f-s.png');
  70644. circleMats.hovered_normal = circleMats.default_normal.clone();
  70645. circleMats.hovered_normal.color.set(0x00ff00);
  70646. circleMats.hovered_normal.useDepth = false;
  70647. circleMats.hovered_rtk_on = circleMats.default_rtk_on.clone();
  70648. circleMats.hovered_rtk_on.color.set(0x00ff00);
  70649. circleMats.hovered_rtk_on.useDepth = false;
  70650. circleMats.hovered_rtk_off = circleMats.default_rtk_off.clone();
  70651. circleMats.hovered_rtk_off.color.set(0x00ff00);
  70652. circleMats.hovered_rtk_off.useDepth = false;
  70653. var setPos = circle => {
  70654. circle.position.copy(circle.pano.position);
  70655. for (var id in this.panoLink[circle.pano.id]) {
  70656. var linkInfo = this.panoLink[circle.pano.id][id];
  70657. if (linkInfo) {
  70658. LineDraw.updateLine(linkInfo.line, [circle.pano.position, images360.getPano(id).position]);
  70659. }
  70660. }
  70661. circle.waitUpdate(); //update sprite Matrix
  70662. };
  70663. images360.panos.forEach(pano => {
  70664. var circle = new Sprite$2({
  70665. mat: circleMats['default' + '_' + this.getPanoRtkState(pano)],
  70666. sizeInfo: {
  70667. minSize: 50,
  70668. maxSize: 120,
  70669. nearBound: 2,
  70670. farBound: 10
  70671. },
  70672. renderOrder: renderOrders$1.circle,
  70673. pickOrder: renderOrders$1.circle
  70674. });
  70675. circle.pickDontCheckDis = true;
  70676. circle.name = 'panoCircle';
  70677. circle.sid = pano.id;
  70678. circle.pano = pano;
  70679. pano.circle = circle;
  70680. this.panoMeshs.add(circle);
  70681. setPos(circle);
  70682. pano.addEventListener('rePos', setPos.bind(this, circle));
  70683. var drag = e => {
  70684. /* if(this.activeViewName == 'mainView' && this.tranMode == 'translate'){//如果3d页不禁止xy的话,这段打开
  70685. this.transformControls.dispatchEvent('dragging')//触发拖拽
  70686. return
  70687. } */
  70688. if (this.tranMode != 'translate' || this.activeViewName == 'mainView') return e.refuse();
  70689. this.selectPano(circle.pano); //为了方便拖拽点云,拖动circle就直接选中
  70690. viewer.inputHandler.drag.object = null; //取消拖拽状态,否则不触发点云拖动
  70691. };
  70692. circle.addEventListener('drag', drag);
  70693. circle.addEventListener('mouseover', () => {
  70694. this.hoverPano(pano, true);
  70695. });
  70696. circle.addEventListener('mouseleave', () => {
  70697. this.hoverPano(pano, false);
  70698. });
  70699. circle.addEventListener('click', () => {
  70700. //if(this.activeViewName == 'mainView')return
  70701. if (this.clickToZoomInEnabled) return;
  70702. if (clickPanoToDisLink && this.operation == 'removeLink') {
  70703. this.linkChange(pano, null, 'remove'); //删除所有连接
  70704. }
  70705. if (this.selectedPano == circle.pano) return this.selectPano(null);
  70706. if (this.operation == 'addLink' && this.selectedPano) {
  70707. this.linkChange(this.selectedPano, circle.pano, 'add');
  70708. //this.setLinkOperateState('addLink',false)
  70709. return;
  70710. }
  70711. //if(this.operation == 'removeLink' && this.selectedPano){ //和选择中心点冲突
  70712. // this.linkChange(this.selectedPano, circle.pano, 'remove')
  70713. // //this.setLinkOperateState('removeLink',false)
  70714. // return
  70715. // }
  70716. this.selectPano(circle.pano);
  70717. });
  70718. });
  70719. }
  70720. hoverPano(pano, state) {
  70721. if (this.clickToZoomInEnabled) return;
  70722. if (pano && state) {
  70723. //在hover一个pano之前,一定会先取消已经hover的pano, 最多存在一个hovered的pano
  70724. if (this.hoveredPano == pano) return;
  70725. if (this.hoveredPano) {
  70726. this.hoverPano(this.hoveredPano, false);
  70727. }
  70728. this.hoveredPano = pano;
  70729. pano.hovered = true;
  70730. if ( /* this.activeViewName == 'mainView' || */Alignment$1.handleState && this.selectedPano && this.selectedPano == pano) return;
  70731. if (this.operation != 'addLink' || !this.selectedPano || this.selectedPano == pano) {
  70732. // this.selectedPano == pano?
  70733. viewer.dispatchEvent({
  70734. type: "CursorChange",
  70735. action: "add",
  70736. name: "hoverPano"
  70737. });
  70738. }
  70739. if (this.selectedPano != pano) pano.circle.material = circleMats['hovered' + '_' + this.getPanoRtkState(pano)];
  70740. } else if (pano && !state) {
  70741. //unhover
  70742. if (this.hoveredPano != pano) return;
  70743. pano.hovered = false;
  70744. viewer.dispatchEvent({
  70745. type: "CursorChange",
  70746. action: "remove",
  70747. name: "hoverPano"
  70748. });
  70749. if (this.selectedPano != pano) pano.circle.material = circleMats['default' + '_' + this.getPanoRtkState(pano)];
  70750. this.hoveredPano = null;
  70751. } else {
  70752. //unhover any
  70753. if (this.hoveredPano) {
  70754. this.hoverPano(this.hoveredPano, false);
  70755. }
  70756. }
  70757. }
  70758. selectPano(pano, informinformBy2d, force) {
  70759. if (this.selectedPano == pano && !force) return;
  70760. var lastSeletedPano = this.selectedPano;
  70761. var opaProp = this.activeViewName == 'top' ? opacitys.topView : opacitys.sideView;
  70762. if (this.selectedPano) {
  70763. this.selectedPano.circle.material = circleMats['default' + '_' + this.getPanoRtkState(this.selectedPano)];
  70764. this.selectedPano.circle.renderOrder = renderOrders$1.circle;
  70765. this.selectedPano.removeEventListener('rePos', this.panoReposCallback);
  70766. if (this.activeViewName == 'mainView') {} else {
  70767. this.selectedClouds.forEach(e => {
  70768. e.changePointOpacity(opaProp.default, true);
  70769. e.material.color = pointColor.default;
  70770. });
  70771. }
  70772. }
  70773. this.selectedPano = pano || null;
  70774. this.updateSelectGroup();
  70775. if (pano) {
  70776. this.selectedPano.circle.material = circleMats['selected' + '_' + this.getPanoRtkState(this.selectedPano)];
  70777. this.selectedPano.circle.renderOrder = this.selectedPano.circle.pickOrder = renderOrders$1.circleSelected; //侧视图能显示在最前
  70778. viewer.controls.setTarget(this.selectedPano.position); //3d时绕其为中心转动
  70779. this.selectedPano.addEventListener('rePos', this.panoReposCallback);
  70780. if (this.activeViewName == 'mainView') {} else {
  70781. this.selectedClouds.forEach(e => {
  70782. e.changePointOpacity(opaProp.selected, true);
  70783. e.material.color = pointColor.selected;
  70784. });
  70785. }
  70786. if (this.currentFloor != 'all') {
  70787. //如果原本不是展示全部楼层的话,自动切换楼层
  70788. var atFloor = SiteModel$1.entities.find(e => e.buildType == 'floor' && e.panos.includes(pano));
  70789. if (!atFloor) {
  70790. atFloor = 'all';
  70791. } else {}
  70792. this.gotoFloor(atFloor, false, 600);
  70793. }
  70794. } else {
  70795. viewer.controls.setTarget(null);
  70796. }
  70797. this.updateCursor();
  70798. this.updateTranCtl();
  70799. if (informinformBy2d) {
  70800. if (this.selectedPano) {
  70801. if (this.activeViewName == 'mainView') {
  70802. //平移,focus选中的pano
  70803. var distance = this.lastDisToPano || 5;
  70804. if (lastSeletedPano) {
  70805. distance = viewer.mainViewport.camera.position.distanceTo(lastSeletedPano.position);
  70806. }
  70807. viewer.focusOnObject({
  70808. position: this.selectedPano.position
  70809. }, 'point', null, {
  70810. distance
  70811. });
  70812. } else {
  70813. this.orthoMoveFit(this.selectedPano.position, {}, 500);
  70814. }
  70815. }
  70816. } else {
  70817. this.dispatchEvent({
  70818. type: 'panoSelect',
  70819. pano
  70820. });
  70821. }
  70822. this.updateIntersectEnable();
  70823. viewer.dispatchEvent('content_changed');
  70824. }
  70825. /* updatePointLevels(){
  70826. if(this.pauseUpdateLevels)return
  70827. let maxBudget = Potree.config.pointDensity.panoEdit.pointBudget
  70828. let visiCount1 = viewer.scene.pointclouds.filter(e=>e.visible).length
  70829. let visiCount2 = viewer.scene.pointclouds.filter(e=>e.visibleNodes.length>0).length //屏幕范围内可见的个数
  70830. let maxCount = 200, minCount = 1, minPer = 0.45 , maxPer = 1
  70831. let percent1 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount1 - minCount) / (maxCount - minCount),0,1)
  70832. let percent2 = maxPer - ( maxPer - minPer) * THREE.Math.clamp((visiCount2 - minCount) / (maxCount - minCount),0,1)
  70833. let percent = percent1*percent2
  70834. if(this.activeViewName == 'mainView' ){
  70835. //假设每个pointcloud所带的点个数大致相同,那么当可见点云个数越多,所能展示的level越低,否则因总个数超过budget的话密度会参差不齐。
  70836. //pointcloud.changePointSize()
  70837. //console.log('updatePointLevels', percent, visiCount)
  70838. Potree.settings.UserDensityPercent = Math.sqrt(percent2)
  70839. viewer.setPointBudget(maxBudget * percent2)
  70840. }else{
  70841. Potree.settings.UserDensityPercent = 1
  70842. viewer.setPointBudget(maxBudget * percent)
  70843. }
  70844. viewer.setPointBudget(maxBudget * percent)
  70845. viewer.setPointLevels()
  70846. //侧面容易卡顿,但和显示的点数无关,似乎是因加载点云多而卡?为何正面不会
  70847. //console.warn('setPointBudget', Potree.pointBudget, visiCount1,visiCount2, Potree.settings.UserDensityPercent)
  70848. } */
  70849. getPanoRtkState(pano) {
  70850. return pano.panosData.has_rtk ? pano.rtkState ? 'rtk_on' : 'rtk_off' : 'normal';
  70851. }
  70852. setPanoRtkState(pano, state) {
  70853. pano.rtkState = state;
  70854. pano.circle.material = circleMats[(this.selectedPano == pano ? 'selected' : 'default') + '_' + this.getPanoRtkState(pano)];
  70855. }
  70856. updateSelectGroup() {
  70857. //更新选中的组
  70858. this.selectedGroup = this.panoGroup.find(e => e.includes(this.selectedPano));
  70859. if (this.selectedGroup) {
  70860. this.selectedGroup = [this.selectedPano, ...this.selectedGroup.filter(e => e != this.selectedPano)]; //将选中的放第一个,便于旋转时绕其旋转。
  70861. }
  70862. //this.selectedClouds = this.selectedPano ? (this.selectedGroup || [this.selectedPano]).map(e=>e.pointcloud) : []
  70863. this.selectedClouds = this.selectedPano ? this.selectedGroup.map(e => e.pointcloud) : [];
  70864. }
  70865. checkIfCanSave() {
  70866. //如果未全部相连,不能保存
  70867. for (var datasetId in Potree.settings.datasetsPanos) {
  70868. if (!this.checkIfAllLinked({
  70869. datasetId
  70870. })) {
  70871. console.log('没有全部连通,不能保存。其中一个:', datasetId);
  70872. return;
  70873. }
  70874. }
  70875. return true;
  70876. }
  70877. checkIfAllLinked(o) {
  70878. //某个(or组所在的)数据集是否全部连通
  70879. var datasetId, group;
  70880. if (o.group) {
  70881. group = o.group;
  70882. var pano = o.group[0];
  70883. if (!pano) return; //会有没有漫游点的点云来编辑吗
  70884. datasetId = pano.pointcloud.dataset_id;
  70885. } else if (o.datasetId) {
  70886. datasetId = o.datasetId;
  70887. group = this.panoGroup.find(panos => panos[0].pointcloud.dataset_id == datasetId);
  70888. if (!group) return; //要找的数据集的pano全部都孤立了
  70889. }
  70890. if (datasetId == void 0) return;
  70891. var panos = Potree.settings.datasetsPanos[datasetId].panos;
  70892. return panos.length == group.length;
  70893. }
  70894. getSuggestLinkPanos() {
  70895. var _this = this;
  70896. //给出建议连接的点
  70897. var panos = [];
  70898. var startTime = Date.now();
  70899. var _loop = function _loop(datasetId) {
  70900. if (!_this.checkIfAllLinked({
  70901. datasetId
  70902. })) {
  70903. var groups = _this.panoGroup.filter(panos => panos[0].pointcloud.dataset_id == datasetId);
  70904. groups = groups.sort((a, b) => {
  70905. return b.length - a.length;
  70906. }); //找出个数最多的一组来连接其他组
  70907. var mainGroup = groups[0].slice(),
  70908. subGroup;
  70909. for (var i = 1, len = groups.length; i < len; i++) {
  70910. subGroup = groups[i];
  70911. var minDis = {
  70912. dis: Infinity,
  70913. panos: []
  70914. };
  70915. for (var a = 0, len1 = mainGroup.length; a < len1; a++) {
  70916. for (var b = 0, len2 = subGroup.length; b < len2; b++) {
  70917. var dis = mainGroup[a].position.distanceToSquared(subGroup[b].position);
  70918. if (dis < minDis.dis) {
  70919. minDis.dis = dis;
  70920. minDis.panos = [mainGroup[a], subGroup[b]];
  70921. }
  70922. }
  70923. }
  70924. panos.push(minDis.panos);
  70925. //console.log('第i次',minDis)
  70926. mainGroup.push(...subGroup); //连接后,加入集合
  70927. }
  70928. }
  70929. };
  70930. for (var datasetId in Potree.settings.datasetsPanos) {
  70931. _loop(datasetId);
  70932. }
  70933. //console.log('cost', Date.now() - startTime)
  70934. return panos;
  70935. }
  70936. showSuggestLinkPanos() {
  70937. var groups = this.getSuggestLinkPanos();
  70938. var s = 0.7;
  70939. var createCircle = pano => {
  70940. var circle = new Mesh(pano.circle.geometry, suggestCircleMat);
  70941. circle.name = 'suggest-circle';
  70942. circle.scale.set(s, s, s);
  70943. circle.renderOrder = 100;
  70944. pano.circle.add(circle);
  70945. };
  70946. groups.forEach(panos => {
  70947. createCircle(panos[0]);
  70948. createCircle(panos[1]);
  70949. var line = LineDraw.createFatLine([panos[0].position, panos[1].position], {
  70950. mat: lineMats$3.suggestLink
  70951. });
  70952. this.suggestLines.push(line);
  70953. line.renderOrder = renderOrders$1.line;
  70954. viewer.scene.scene.add(line);
  70955. });
  70956. }
  70957. getPanoPose(pano) {
  70958. var pose = {
  70959. position: pano.position.clone(),
  70960. quaternion: new Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua)
  70961. };
  70962. return pose;
  70963. }
  70964. exportSavingData() {
  70965. //输出漫游点新的坐标和朝向、以及连接信息
  70966. var sweepLocations = {};
  70967. for (var datasetId in Potree.settings.datasetsPanos) {
  70968. var {
  70969. panos
  70970. } = Potree.settings.datasetsPanos[datasetId];
  70971. var data = panos.map(pano => {
  70972. var visibles = [];
  70973. for (var id in this.panoLink[pano.id]) {
  70974. if (this.panoLink[pano.id][id]) {
  70975. visibles.push(viewer.images360.getPano(id).index);
  70976. }
  70977. }
  70978. var {
  70979. position,
  70980. quaternion
  70981. } = this.getPanoPose(pano);
  70982. return Object.assign({}, pano.panosData, {
  70983. uuid: pano.uuid,
  70984. /* pose:{
  70985. translation: dealData(pano.position.clone() ),
  70986. rotation: dealData(new THREE.Quaternion().setFromRotationMatrix(pano.panoMatrix).premultiply(rotQua) ),
  70987. }, */
  70988. pose: {
  70989. translation: dealData(position),
  70990. rotation: dealData(quaternion)
  70991. },
  70992. visibles,
  70993. use_rtk: !!pano.rtkState
  70994. //subgroup: 0,group: 1, "id_view":..
  70995. });
  70996. });
  70997. sweepLocations[datasetId] = {
  70998. sweepLocations: data
  70999. };
  71000. }
  71001. /* this.lineMeshes.children.forEach(e=>{//从line中搜集连接信息,而不从linkInfo,这样visibles不会重复一次
  71002. let names = e.name.split('-') //是不是该转成数字
  71003. var pano0 = names[0]
  71004. var pano1 = names[1]
  71005. sweepLocations.find(s=>s.uuid == pano0).visibles.push(pano1)
  71006. }) */
  71007. function dealData(value) {
  71008. var v = math.toPrecision(value, 6);
  71009. if (v instanceof Quaternion) {
  71010. return {
  71011. x: v.x,
  71012. y: v.y,
  71013. z: v.z,
  71014. w: v.w
  71015. };
  71016. } else if (v instanceof Vector3) {
  71017. return {
  71018. x: v.x,
  71019. y: v.y,
  71020. z: v.z
  71021. };
  71022. }
  71023. }
  71024. //console.log(sweepLocations)
  71025. return sweepLocations;
  71026. }
  71027. }
  71028. /*
  71029. 不同数据集之间不能连线
  71030. 不同楼层可能也不能
  71031. 如果楼层在不同建筑物怎么办? 楼层切换按钮只能在一个建筑内切换。
  71032. 全部相连时不能移动和旋转
  71033. 如果未全部相连,不能保存
  71034. */
  71035. var PanoEditor$1 = new PanoEditor();
  71036. //import {Prism} from './Prism.js'
  71037. var maxWidth = 4096;
  71038. var surfaceThick = 0.1; //最大表面厚度
  71039. var pointDensity = 'screenshot';
  71040. var maxPointBudge = Potree.config.pointDensity[pointDensity].pointBudget;
  71041. var Shaders$1 = {
  71042. 'modelHeight.vs': " \n precision highp float;\n \n uniform vec2 boundZ;\n varying float heightPercent; \n \n\n float round(float number){\n return floor(number + 0.5);\n }\n \n \n \n \n \n void main() \n { \n vec3 worldPos = (modelMatrix * vec4(position, 1.0)).xyz; \n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); \n \n float zMin = boundZ.x, zMax = boundZ.y ;\n heightPercent = (worldPos.z - zMin) / (zMax - zMin); \n \n \n }\n \n \n ",
  71043. 'modelHeight.fs': "\n precision highp float;\n varying float heightPercent; \n \n \n \n \n vec3 percentToByte(float num){\n //\u8F93\u51FA\u662F0-1\uFF0C shader\u7CBE\u5EA6\u4E0D\u591F\uFF0C\u53EA\u591F\u5B583\u4E2A\u6570\uFF0C\u56E0\u7B2C\u56DB\u4F4D\u603B\u662F0\n float a = 1.0;\n float result[4];\n for(int i=0;i<3;i++){\n a = i == 2 ? a/255.0 : a / 256.0 ; \n //\u5206\u6210256\u4EFD\uFF0C\u5176\u4E2D255\u4EFD\u7ED9\u5F53\u524D\u4F4D\u7F6E\uFF0C\u6700\u540E\u4E00\u4EFD\u7ED9\u540E\u4E00\u4E2A\u4F4D\u7F6E\uFF0C\u800C\u5230\u4E86\u6700\u540E\u4E00\u4E2A\u4F4D\u7F6E\u65F6\u6CA1\u6709\u4E0B\u4E00\u4E2A\u4F4D\u7F6E\u4E86\u6240\u4EE5\u53EA\u5206\u6210255\u4EFD\n if(num > a){\n float c = num / a;\n float r = floor(c);\n r = min(255.0, r);\n result[i] = r;\n num -= r * a;\n }else{\n result[i] = 0.0;\n }\n } \n return vec3(result[0]/255.0, result[1]/255.0,result[2]/255.0); \n \n } \n \n \n void main() {\n \n gl_FragColor = vec4(percentToByte(heightPercent),1.0); \n \n \n }\n "
  71044. };
  71045. var horizonZ,
  71046. zMin,
  71047. zMax,
  71048. lowest,
  71049. highest,
  71050. wDelta,
  71051. sDelta,
  71052. deferred,
  71053. interrupt,
  71054. timestamp,
  71055. buffer1,
  71056. buffer2,
  71057. modelZs = [];
  71058. var testPoint$1 = false;
  71059. //const asyncTimeout = (delay) => new Promise(resolve => setTimeout(resolve, delay))
  71060. var delayForNotify = 5,
  71061. notifyInterval = 500;
  71062. var lastNotifyTime = Date.now();
  71063. var curPercent;
  71064. var notify = (areas, num, str) => {
  71065. //num: 0-1
  71066. return new Promise(resolve => {
  71067. if (!deferred) return resolve();
  71068. var now = Date.now();
  71069. if (now - lastNotifyTime < notifyInterval) {
  71070. return resolve();
  71071. }
  71072. lastNotifyTime = now;
  71073. if (num == void 0) {
  71074. num = curPercent;
  71075. } else {
  71076. var s = 0,
  71077. e = 1;
  71078. if (num instanceof Function) {
  71079. num = num();
  71080. }
  71081. areas.forEach(area => {
  71082. var s_ = e * area[0] + s * (1 - area[0]);
  71083. var e_ = e * area[1] + s * (1 - area[1]);
  71084. s = s_, e = e_;
  71085. });
  71086. var p = e * num + s * (1 - num);
  71087. str == 'loadpoints' && Potree.settings.isTest && console.log('notify pro', p, str);
  71088. deferred.notify(p);
  71089. curPercent = p;
  71090. if (isNaN(p)) {
  71091. console.log('nan');
  71092. }
  71093. }
  71094. setTimeout(resolve, delayForNotify);
  71095. });
  71096. };
  71097. class VolumeComputer extends EventDispatcher {
  71098. constructor() {
  71099. super();
  71100. this.camera = new OrthographicCamera(-100, 100, -100, 100, 0.01, 100);
  71101. this.camera.up.set(0, 0, 1);
  71102. Potree.Utils.setCameraLayers(this.camera, ['model']);
  71103. this.view = new ExtendView();
  71104. this.viewport = new Viewport(this.view, this.camera, {
  71105. left: 0,
  71106. bottom: 0,
  71107. width: 1,
  71108. height: 1
  71109. });
  71110. this.renderTarget = new WebGLRenderTarget(1, 1, {
  71111. minFilter: LinearFilter,
  71112. magFilter: NearestFilter,
  71113. format: RGBAFormat
  71114. });
  71115. this.renderTarget2 = new WebGLRenderTarget(1, 1, {
  71116. minFilter: LinearFilter,
  71117. magFilter: NearestFilter,
  71118. format: RGBAFormat
  71119. });
  71120. this.renderTarget2.texture.name = 'volumeCptModelTex';
  71121. this.material = new ExtendPointCloudMaterial();
  71122. this.material.activeAttributeName = testPoint$1 ? "rgba" : 'heightCpt'; // 'rgba' indices prismHeight
  71123. this.prisms = [];
  71124. this.modelMat = new ShaderMaterial({
  71125. uniforms: {
  71126. boundZ: {
  71127. type: "vec2",
  71128. value: new Vector2()
  71129. }
  71130. },
  71131. vertexShader: Shaders$1['modelHeight.vs'],
  71132. fragmentShader: Shaders$1['modelHeight.fs'],
  71133. depthWrite: true,
  71134. depthTest: true,
  71135. transparent: false,
  71136. side: DoubleSide
  71137. });
  71138. this.scene = new Scene();
  71139. }
  71140. init() {
  71141. viewer.scene.addEventListener('measurement_added', e => {
  71142. if (e.measurement.isPrism) this.add(e.measurement);
  71143. });
  71144. viewer.scene.addEventListener('measurement_removed', e => {
  71145. if (e.measurement.isPrism) this.remove(e.measurement);
  71146. });
  71147. var this_ = this;
  71148. this.events = {
  71149. transformCallback: () => {
  71150. if (!this_.currentPrism) return;
  71151. //Common.intervalTool.isWaiting('volCptTransformed', ()=>{ //延时update,防止卡顿
  71152. var object = viewer.transformationTool.selection[0];
  71153. if (object == this_.currentPrism.baseModel) {
  71154. this.updateModelBound({
  71155. modelChange: true
  71156. });
  71157. }
  71158. this_.currentPrism.dispatchEvent('needsCompute'); //模型变动或clipBox变动后要重算
  71159. //}, 1000)
  71160. }
  71161. };
  71162. }
  71163. enter() {
  71164. this.entered = true;
  71165. viewer.measuringTool.history.clear(); //避免撤销到测量线去
  71166. this.oldStates = {
  71167. rotAroundPoint: Potree.settings.rotAroundPoint
  71168. };
  71169. Potree.settings.rotAroundPoint = false;
  71170. //viewer.objs.traverse(e=>e.material && ( e.material = this.material))
  71171. viewer.transformationTool.addEventListener('stopDrag', this.events.transformCallback);
  71172. viewer.transformationTool.addEventListener('changeByHistory', this.events.transformCallback);
  71173. }
  71174. leave() {
  71175. this.entered = false;
  71176. Potree.settings.rotAroundPoint = this.oldStates.rotAroundPoint;
  71177. this.setCurrentPrism(null);
  71178. viewer.transformationTool.removeEventListener('stopDrag', this.events.transformCallback);
  71179. viewer.transformationTool.removeEventListener('changeByHistory', this.events.transformCallback);
  71180. }
  71181. add(prism) {
  71182. this.prisms.push(prism);
  71183. }
  71184. remove(prism) {
  71185. var i = this.prisms.indexOf(prism);
  71186. i > -1 && this.prisms.splice(i, 1);
  71187. }
  71188. cancel() {
  71189. if (this.computingObject) {
  71190. interrupt = true;
  71191. }
  71192. }
  71193. startCompute(model, dontCompute) {
  71194. //test
  71195. this.enter();
  71196. var deferred = $.Deferred();
  71197. deferred.done(e => {
  71198. console.log('done', e);
  71199. });
  71200. deferred.fail(e => {
  71201. console.log('?fail????', e);
  71202. });
  71203. /* deferred.progress((e)=>{
  71204. console.log('progress', e)
  71205. }) */
  71206. if (model) {
  71207. this.prisms[this.prisms.length - 1].setBaseModel(model);
  71208. this.setCurrentPrism(this.prisms[this.prisms.length - 1]);
  71209. dontCompute || this.compute(this.prisms[this.prisms.length - 1]);
  71210. } else {
  71211. this.compute(this.prisms[this.prisms.length - 1], deferred);
  71212. }
  71213. }
  71214. setCurrentPrism(prism) {
  71215. //当进入单个prism编辑后才会高亮点云
  71216. if (this.currentPrism) {
  71217. this.currentPrism.removeEventListeners('updated');
  71218. }
  71219. this.currentPrism = prism; //允许没有model
  71220. if (!prism || !prism.baseModel /* || !prism.baseModel.visible */) {
  71221. viewer.scene.pointclouds.forEach(e => {
  71222. this.updateMatForModel(e.material); //取消高亮
  71223. });
  71224. return;
  71225. }
  71226. prism.addEventListener('updated', () => {
  71227. if (this.currentPrism != prism) {
  71228. return console.log('currentPrism changed? 侦听没删除');
  71229. }
  71230. this.updateModelBound();
  71231. });
  71232. this.updateModelBound({
  71233. regetMap: true
  71234. });
  71235. }
  71236. setModelMat(model, type) {
  71237. if (type == 'recover') {
  71238. model.traverse(e => e.originMat_ && (e.material = e.originMat_));
  71239. } else {
  71240. model.traverse(e => e.material && e.material != this.modelMat && (e.originMat_ = e.material, e.material = this.modelMat));
  71241. }
  71242. }
  71243. updateModelBound() {
  71244. var {
  71245. modelChange,
  71246. regetMap
  71247. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  71248. //regetMap是在更换currentPrism必须重绘map,但不需要needUpdate
  71249. var prism = this.currentPrism;
  71250. var model = this.currentPrism.baseModel;
  71251. if (!model) return;
  71252. model.currentBound = model.boundingBox.clone().applyMatrix4(model.matrixWorld); //作用同prismBound
  71253. var oldBound = model.clipBound && model.clipBound.clone();
  71254. model.clipBound = model.currentBound.clone(); //高亮范围
  71255. model.clipBound.min.max(prism.prismBound.min); //xy为交集
  71256. model.clipBound.max.min(prism.prismBound.max);
  71257. model.clipBound.min.z = Math.min(model.currentBound.min.z, prism.prismBound.min.z); //z为并集,范围覆盖prism点、点云、model三者
  71258. model.clipBound.max.z = Math.max(model.currentBound.max.z, prism.prismBound.max.z);
  71259. this.modelMat.uniforms.boundZ.value.set(model.clipBound.min.z, model.clipBound.max.z);
  71260. var boundChanged = !oldBound || !oldBound.equals(model.clipBound);
  71261. var boundSize = this.currentPrism.baseModel.clipBound.getSize(new Vector3());
  71262. this.boundSizeZero = boundSize.x <= 0 || boundSize.y <= 0 || boundSize.z <= 0; //会造成renderTarget尺寸为0,背景变白,报错:Framebuffer is incomplete: Attachment has zero size 和 The texture is a non-power-of-two texture.
  71263. if ((modelChange || regetMap || boundChanged) && !this.boundSizeZero) {
  71264. this.setModelHeightMap(); //包含cad在俯视中的范围 + 高度信息
  71265. //this.setModelMat(model,this.boundSizeZero ? 'recover' : null)
  71266. }
  71267. viewer.scene.pointclouds.forEach(e => {
  71268. //暂时先只支持一个高亮区域
  71269. this.updateMatForModel(e.material, model);
  71270. });
  71271. //需要重新渲染modelHeightmap的情况:bound改变、模型变动、更换currentPrism后
  71272. //注意,即使上传几种都没发生,仅仅移动prism的marker也要重算,假设一个marker在model范围内,移动后bound可能不变但体积肯定变。
  71273. /* if(boundChanged){
  71274. if(prism.recoverNeedCptNextTime){
  71275. prism.needsCompute = 'byVolume' //初始化,有volume就不用重算
  71276. prism.recoverNeedCptNextTime = false
  71277. }else{
  71278. prism.dispatchEvent('needsCompute')
  71279. }
  71280. } */
  71281. }
  71282. updateMatForModel(material, model) {
  71283. var oldMap = material.uniforms.baseHeightAreaMap.value;
  71284. if (model) {
  71285. material.uniforms.baseHeightAreaMap.value = this.renderTarget2.texture; //model.baseHeightAreaMap ;
  71286. material.uniforms.baseHeightBoundZ.value.set(model.clipBound.min.z, model.clipBound.max.z);
  71287. material.uniforms.baseHeightBoundXY.value.set(model.clipBound.min.x, model.clipBound.max.x, model.clipBound.min.y, model.clipBound.max.y);
  71288. } else {
  71289. material.uniforms.baseHeightAreaMap.value = null;
  71290. }
  71291. if (oldMap != material.uniforms.baseHeightAreaMap.value) {
  71292. material.shaderNeedsUpdate = true;
  71293. }
  71294. }
  71295. setModelHeightMap() {
  71296. var oldTarget = viewer.renderer.getRenderTarget();
  71297. var oldParent = this.currentPrism.baseModel.parent;
  71298. var oldVisi = this.currentPrism.baseModel.visible;
  71299. var boundSize = this.currentPrism.baseModel.clipBound.getSize(new Vector3());
  71300. var boundCenter = this.currentPrism.baseModel.clipBound.getCenter(new Vector3());
  71301. var {
  71302. w,
  71303. h
  71304. } = this.getResByBound(boundSize, 'forModel');
  71305. if (w <= 0 || h <= 0) {
  71306. return console.error('w<=0 || h<=0!!!!!!!!!', w, h);
  71307. }
  71308. /* w = THREE.Math.floorPowerOfTwo( w );
  71309. h = THREE.Math.floorPowerOfTwo( h ); */ //for warning:The texture is a non-power-of-two texture
  71310. this.camera.far = boundSize.z + 10;
  71311. this.camera.right = w / 2;
  71312. this.camera.left = -this.camera.right;
  71313. this.camera.top = h / 2;
  71314. this.camera.bottom = -this.camera.top;
  71315. this.viewport.resolution.set(w, h);
  71316. this.renderTarget2.setSize(w, h);
  71317. viewer.renderer.setRenderTarget(this.renderTarget2);
  71318. console.log('setModelHeightMap');
  71319. //最高处朝下看
  71320. var endPosition = new Vector3();
  71321. endPosition.copy(boundCenter).setZ(this.currentPrism.baseModel.clipBound.max.z + this.camera.near + 0.1);
  71322. this.view.pitch = -Math.PI / 2;
  71323. this.view.moveOrthoCamera(this.viewport, {
  71324. boundSize,
  71325. endPosition
  71326. }, 0);
  71327. this.view.applyToCamera(this.camera);
  71328. this.scene.add(this.currentPrism.baseModel);
  71329. this.setModelMat(this.currentPrism.baseModel);
  71330. this.currentPrism.baseModel.visible = true;
  71331. var gl = viewer.renderer.getContext();
  71332. viewer.renderer.setClearColor(new Color('#000'), 0);
  71333. viewer.renderer.clear();
  71334. viewer.renderer.render(this.scene, this.camera);
  71335. this.setModelMat(this.currentPrism.baseModel, 'recover');
  71336. var pixelCount = this.renderTarget2.width * this.renderTarget2.height;
  71337. buffer2 = new Uint8Array(4 * pixelCount);
  71338. //因为需要渲染完立即readPixels才能获取到,所以只能这时候就read了
  71339. gl.readPixels(0, 0, this.renderTarget2.width, this.renderTarget2.height, gl.RGBA, gl.UNSIGNED_BYTE, buffer2); //这句花费最多时间 pc:2-4, 即使只有1*1像素
  71340. modelZs = []; //等待计算
  71341. if (window.needDownload) {
  71342. var dataUrl = Potree.Utils.renderTargetToDataUrl(this.renderTarget2, this.renderTarget2.width, this.renderTarget2.height, viewer.renderer);
  71343. Common.downloadFile(dataUrl, (name || 'screenshot') + '-' + Date.now() + '.png');
  71344. }
  71345. oldParent.add(this.currentPrism.baseModel);
  71346. this.currentPrism.baseModel.visible = oldVisi;
  71347. viewer.renderer.setRenderTarget(oldTarget);
  71348. this.renderTarget2.texture.needsRebuild = true; //renderTarget在resize后会触发dispose, 然后 _gl.deleteTexture( textureProperties.__webglTexture )所以需要重新建立 否则图片变黑
  71349. return this.renderTarget2.texture;
  71350. }
  71351. getResByBound(boundSize, type) {
  71352. //let pxPerMetric = math.linearClamp(Math.max(boundSize.x,boundSize.y), [4, 10, 20, 80, 500, 2000], [300, 200, 100, 30, 6, 3])
  71353. var pxPerMetric = math.linearClamp(Math.max(boundSize.x, boundSize.y), [10, 60, 100, 500, 2000], [150, 60, 40, 6, 3]);
  71354. var w = pxPerMetric * boundSize.x,
  71355. h = boundSize.y * pxPerMetric;
  71356. var cW = 1,
  71357. cH = 1; //横向纵向渲染次数 超过maxWidth时分批渲染
  71358. if (w > maxWidth || h > maxWidth) {
  71359. /* if(){//多数据集判断是否间隔过远,是的话返回
  71360. } */
  71361. if (type == 'forCompute') {
  71362. //计算可以分多次渲染
  71363. cW = Math.ceil(w / maxWidth), cH = Math.ceil(h / maxWidth);
  71364. w /= cW, h /= cH;
  71365. } else if (type == 'forModel') {
  71366. //但是model的贴图只能有一个
  71367. if (w > h) {
  71368. w = maxWidth, h = w * boundSize.y / boundSize.x;
  71369. } else {
  71370. h = maxWidth, w = h * boundSize.x / boundSize.y;
  71371. }
  71372. }
  71373. }
  71374. w = Math.round(w);
  71375. h = Math.round(h);
  71376. return {
  71377. w,
  71378. h,
  71379. pxPerMetric,
  71380. cW,
  71381. cH
  71382. };
  71383. }
  71384. //法1:只用一个顶部相机(当挖方遮挡填方时不准,但好算)
  71385. compute(prism, deferred_, getResolveResult) {
  71386. var _this = this;
  71387. return _asyncToGenerator(function* () {
  71388. if (!prism || prism.modelHaventLoad) {
  71389. console.log('prism有问题');
  71390. return deferred_.reject();
  71391. }
  71392. if (_this.computingObject) return console.log('正在计算,请稍等');
  71393. var oldCurPrism = _this.currentPrism;
  71394. if (prism != _this.currentPrism) {
  71395. //在列表外点击计算
  71396. _this.setCurrentPrism(prism);
  71397. }
  71398. var computeDone = (_ref, deferred) => {
  71399. var {
  71400. highest,
  71401. lowest,
  71402. Vupper,
  71403. Vlower
  71404. } = _ref;
  71405. prism && prism.setVolumeInfo({
  71406. highest,
  71407. lowest,
  71408. Vupper,
  71409. Vlower
  71410. });
  71411. if (oldCurPrism != prism) {
  71412. _this.setCurrentPrism(oldCurPrism);
  71413. }
  71414. deferred && deferred.resolve(getResolveResult && getResolveResult());
  71415. };
  71416. if (prism.baseModel && _this.boundSizeZero) {
  71417. //bound没有交集 或 prism的boundsize为0
  71418. return computeDone({
  71419. highest: 0,
  71420. lowest: 0,
  71421. Vupper: 0,
  71422. Vlower: 0
  71423. }, deferred_);
  71424. }
  71425. _this.computingObject = {
  71426. prism,
  71427. model: prism.baseModel
  71428. };
  71429. deferred = deferred_;
  71430. var computeFinish = (debugStr, makeit) => {
  71431. makeit || deferred.reject(interrupt ? '主动取消' : debugStr || '');
  71432. _this.computingObject = null;
  71433. deferred = null;
  71434. interrupt = false;
  71435. debugStr && console.log('computeFinish', debugStr);
  71436. Potree.settings.displayMode = statesBefore.mode;
  71437. Potree.settings.pointDensity = statesBefore.pointDensity;
  71438. viewer.renderer.setRenderTarget(null);
  71439. viewer.renderer.state.reset();
  71440. viewer.renderer.setScissorTest(false);
  71441. gl.disable(gl.SCISSOR_TEST);
  71442. viewer.screenshoting = false;
  71443. viewer.mainViewport.active = true;
  71444. viewer.mapViewer && (viewer.mapViewer.viewports[0].active = true);
  71445. viewer.magnifier.viewport.active = true;
  71446. viewer.pauseTestMaxLevel = false;
  71447. };
  71448. var pointcloud = viewer.scene.pointclouds[0];
  71449. var center = new Vector3();
  71450. var boundSize = new Vector3();
  71451. var bound;
  71452. var gl = viewer.renderer.getContext();
  71453. var statesBefore = {
  71454. mode: Potree.settings.displayMode,
  71455. pointDensity: Potree.settings.pointDensity
  71456. };
  71457. timestamp = Date.now();
  71458. if (!_this.computingObject.model) {
  71459. horizonZ = prism.horizonZ;
  71460. zMin = prism.zMin;
  71461. zMax = prism.zMax;
  71462. bound = new Box3();
  71463. for (var i = 0; i < prism.points.length; i++) {
  71464. bound.expandByPoint(prism.points[i]);
  71465. }
  71466. } else {
  71467. zMin = _this.computingObject.model.clipBound.min.z;
  71468. zMax = _this.computingObject.model.clipBound.max.z;
  71469. bound = _this.computingObject.model.clipBound;
  71470. //读取model的高度
  71471. for (var u = 0; u < _this.renderTarget2.width; u++) {
  71472. var col = [];
  71473. for (var v = 0; v < _this.renderTarget2.height; v++) {
  71474. var offset = u + v * _this.renderTarget2.width;
  71475. var rgb = buffer2.slice(4 * offset, 4 * offset + 3),
  71476. a = buffer2[4 * offset + 3];
  71477. if (a == 0) {
  71478. //无点
  71479. col.push(null);
  71480. } else {
  71481. var z = _this.convertColorToHeight(rgb, zMin, zMax);
  71482. col.push(z);
  71483. }
  71484. }
  71485. modelZs.push(col);
  71486. }
  71487. }
  71488. lowest = zMax, highest = zMin; //init. to store pixel lowest and highest
  71489. bound.getCenter(center);
  71490. bound.getSize(boundSize);
  71491. _this.boundSizeZero = boundSize.x <= 0 || boundSize.y <= 0 || boundSize.z <= 0; //prism的问题
  71492. if (_this.boundSizeZero) {
  71493. computeDone({
  71494. highest: 0,
  71495. lowest: 0,
  71496. Vupper: 0,
  71497. Vlower: 0
  71498. }, deferred);
  71499. return computeFinish('finish', true);
  71500. }
  71501. center.z = zMax + _this.camera.near + 0.1;
  71502. _this.camera.far = zMax - zMin + 10;
  71503. viewer.screenshoting = true;
  71504. viewer.pauseTestMaxLevel = true;
  71505. var {
  71506. w,
  71507. h,
  71508. pxPerMetric,
  71509. cW,
  71510. cH
  71511. } = _this.getResByBound(boundSize, 'forCompute');
  71512. _this.camera.right = w / 2;
  71513. _this.camera.left = -_this.camera.right;
  71514. _this.camera.top = h / 2;
  71515. _this.camera.bottom = -_this.camera.top;
  71516. _this.viewport.resolution.set(w, h);
  71517. _this.renderTarget.setSize(w, h);
  71518. wDelta = boundSize.x / (w * cW);
  71519. sDelta = Math.pow(wDelta, 2);
  71520. //准备
  71521. Potree.settings.displayMode = 'showPointCloud';
  71522. Potree.settings.pointDensity = 'screenshot';
  71523. viewer.mainViewport.active = false; //暂停渲染,否则影响这边点云的加载
  71524. viewer.mapViewer && (viewer.mapViewer.viewports[0].active = false);
  71525. viewer.magnifier.viewport.active = false; //防止页面变白(似乎mainViewport被clear)
  71526. {
  71527. //material
  71528. if (!_this.computingObject.model) {
  71529. //this.material.shape = Potree.PointShape.PARABOLOID;//加上之后depth出错,后排点云会挡前排,可pick时为什么不会?
  71530. _this.updateMatForModel(_this.material, null); //计算时的shader这两种类型只能选一个,要么prism要么model,只能渲染一块区域
  71531. //this.material.opacity = 1;
  71532. } else {
  71533. _this.updateMatForModel(_this.material, _this.computingObject.model);
  71534. //this.material.opacity = 0.9; //为了输出透明度,负数高度的alpha是0.5
  71535. }
  71536. var clipBoxes_out = prism.clipBoxes.map(box => {
  71537. return {
  71538. inverse: box.matrixWorld.clone().invert(),
  71539. box
  71540. };
  71541. });
  71542. _this.material.setClipBoxes(null, [], clipBoxes_out, [], [prism]);
  71543. _this.material.pointSizeType = 'FIXED'; //'ADAPTIVE' //node会自动根据的其level更改点大小 使用ADAPTIVE后会使baseModelMap整片是黑的,原因未知
  71544. _this.material.uniforms.minSize.value = 0.1;
  71545. _this.material.uniforms.orthoMaxSize.value = 5; //px
  71546. _this.material.classification = pointcloud.material.classification;
  71547. _this.material.recomputeClassification();
  71548. _this.material.shaderNeedsUpdate = true;
  71549. pointcloud.updateMaterial(_this.material, null, _this.camera, viewer.renderer, _this.viewport.resolution);
  71550. _this.material.size = 1; //this.getPointsize(pointcloud.maxLevel) //0.025 米 //视图缩小(截图面积变大)后点会自动缩小,但至少是1个像素大小
  71551. }
  71552. viewer.renderer.state.buffers.depth.setTest(_this.material.depthTest);
  71553. viewer.renderer.state.buffers.depth.setMask(_this.material.depthWrite);
  71554. viewer.renderer.state.setBlending(NoBlending); //只需要设置不透明即可(使alpha不混合,后方不会影响前方的alpha,否则输出的a通道将没法用)
  71555. var pixelCount = _this.renderTarget.width * _this.renderTarget.height;
  71556. buffer1 = new Uint8Array(4 * pixelCount);
  71557. viewer.renderer.setRenderTarget(_this.renderTarget);
  71558. var results = [];
  71559. var boundSize_ = boundSize.clone();
  71560. boundSize_.x /= cW, boundSize_.y /= cH;
  71561. //分批渲染:从左到右 从下到上
  71562. var _loop = function* _loop(_i) {
  71563. var _loop2 = function* _loop2(j) {
  71564. var infos = [];
  71565. var progressStart = (_i * cH + j) / (cW * cH),
  71566. progressEnd = (_i * cH + j + 1) / (cW * cH);
  71567. if (interrupt) {
  71568. return {
  71569. v: {
  71570. v: computeFinish('23')
  71571. }
  71572. };
  71573. }
  71574. Potree.settings.pointDensity = 'screenshot'; //恢复为nodeMaxLevel
  71575. //最高处朝下看,找挖方的顶部
  71576. _this.view.pitch = -Math.PI / 2;
  71577. var endPosition = new Vector3(center.x + (_i - cW / 2 + 0.5) * boundSize_.x, center.y + (j - cH / 2 + 0.5) * boundSize_.y, center.z);
  71578. _this.view.moveOrthoCamera(_this.viewport, {
  71579. boundSize: boundSize_,
  71580. endPosition
  71581. }, 0);
  71582. var endPercent = _this.computingObject.model ? 0.7 : 0.4;
  71583. yield _this.render({
  71584. i: _i,
  71585. j,
  71586. index: 1,
  71587. cW,
  71588. cH,
  71589. infos,
  71590. /* maxLevels, */notifyArea: [[progressStart, progressEnd], [0, endPercent]],
  71591. computeFinish
  71592. });
  71593. if (interrupt) {
  71594. return {
  71595. v: {
  71596. v: computeFinish('2123')
  71597. }
  71598. };
  71599. }
  71600. if (!_this.computingObject.model) {
  71601. //水平面朝下看,找填方
  71602. _this.view.position.z = horizonZ + _this.camera.near;
  71603. yield _this.render({
  71604. i: _i,
  71605. j,
  71606. index: 2,
  71607. cW,
  71608. cH,
  71609. infos,
  71610. /* maxLevels, */notifyArea: [[progressStart, progressEnd], [0.4, 0.7]],
  71611. computeFinish
  71612. });
  71613. }
  71614. //水平面朝上看,找挖方的底部
  71615. /* this.view.position.z = horizonZ + surfaceThick //排除地面(水平面)上的点
  71616. this.view.pitch = Math.PI / 2;
  71617. await this.render({reverseRow:true,name:'第3张-'+i+'-'+j, infos, buffer,maxLevels }) */ //---土堆上有草地有厚度,还是去掉吧
  71618. var result = {
  71619. index: {
  71620. i: _i,
  71621. j
  71622. },
  71623. allFills: [],
  71624. fillVupper: 0,
  71625. fillVlower: 0,
  71626. Vupper: 0,
  71627. Vlower: infos[1] ? infos[1].Vlower : infos[0].Vlower,
  71628. // >= infos[0].Vlower 因能找到被上方遮挡住的凹槽
  71629. allDiffHeights: [],
  71630. fillVupperCount: 0,
  71631. fillVlowerCount: 0,
  71632. infos
  71633. };
  71634. var waitFill = [];
  71635. waitFill.count = 0;
  71636. var isNeighbor = (a, b) => {
  71637. return Math.abs(a.u - b.u) <= 1 && Math.abs(a.v - b.v) <= 1;
  71638. };
  71639. var isBelongToGroup = (group, item) => {
  71640. if (item[0]) item = item[0];
  71641. var i = group.length;
  71642. while (--i >= 0) {
  71643. //从后往前
  71644. if (item.u - group[i].u > 1 && Math.abs(item.v - group[i].v) > 1) break; //距离超出,前面肯定不相邻了
  71645. if (isNeighbor(group[i], item)) {
  71646. return true;
  71647. }
  71648. }
  71649. };
  71650. //计算挖方(但是边缘附近垂直方向上很多点云,体积被削皮,最终得到的会比infos[0]少)
  71651. var getValue = (u, v) => {
  71652. //当到了左上边界是否需要向前几批的查找?
  71653. if (infos[0].allHeights[u] && infos[0].allHeights[u][v] != void 0) return infos[0].allHeights[u][v];
  71654. return result.allFills[u] && result.allFills[u][v];
  71655. };
  71656. var hasValue = (u, v) => {
  71657. //在边界内
  71658. return u >= 0 && u < infos[0].allHeights.length && v >= 0 && v < infos[0].allHeights[0].length;
  71659. };
  71660. var getFill = (u, v) => {
  71661. //使用周围的八个点的平均值补洞
  71662. var neighbours = [[-1, 0], [0, 1], [1, 0], [0, -1], [-1, -1], [1, -1], [-1, 1], [1, 1]]; //先左右右先上后下
  71663. var i = 0,
  71664. c = 0,
  71665. sum = 0;
  71666. while (c < 4 && i < 8) {
  71667. var x = neighbours[i][0] + u,
  71668. y = neighbours[i][1] + v;
  71669. if (hasValue(x, y)) {
  71670. var neigh = getValue(x, y);
  71671. if (neigh != void 0) {
  71672. c++;
  71673. sum += neigh;
  71674. } else if (i >= 3) {
  71675. //add 2024.5.27
  71676. if (c == 0) break; //节省时间,主要为了大片透明区域
  71677. }
  71678. }
  71679. i++;
  71680. }
  71681. if (c > 0) {
  71682. sum /= c;
  71683. result.allFills[u] || (result.allFills[u] = []);
  71684. result.allFills[u][v] = sum;
  71685. return sum;
  71686. }
  71687. };
  71688. var add = (v, fill, count) => {
  71689. if (v > 0) {
  71690. result.Vupper += v;
  71691. fill && (result.fillVupper += v, result.fillVupperCount += count);
  71692. } else {
  71693. //fill的话才会有
  71694. fill && (result.fillVlower -= v, result.fillVlowerCount += count);
  71695. }
  71696. };
  71697. var compute = /*#__PURE__*/function () {
  71698. var _ref2 = _asyncToGenerator(function* (u, v) {
  71699. var top = infos[0].allHeights[u][v];
  71700. //let btm = infos[2].allHeights[u][v]
  71701. var fill;
  71702. if (top == void 0) {
  71703. if (prism) {
  71704. var x = endPosition.x - boundSize_.x / 2 + wDelta * (u + 0.5);
  71705. var y = endPosition.y - boundSize_.y / 2 + wDelta * (v + 0.5);
  71706. if (!math.isPointInArea(prism.points, null, {
  71707. x,
  71708. y
  71709. })) {
  71710. return; //出界
  71711. }
  71712. } else {
  71713. if (_this.getModelZByRes(u, v, cW, cH, _i, j) == void 0) {
  71714. return; //出界
  71715. }
  71716. }
  71717. fill = true;
  71718. top = getFill(u, v);
  71719. if (top == void 0) {
  71720. //左侧边缘有缺口时会出现
  71721. if (waitFill.cancel || waitFill.count > 1000 && waitFill[waitFill.length - 1][waitFill[waitFill.length - 1].length - 1].u - waitFill[0][0].u > 4) {
  71722. //跨度超过4列
  71723. waitFill.cancel = true; //丢弃,不加入补洞, 降低耗时
  71724. } else {
  71725. Common.pushToGroupAuto([{
  71726. u,
  71727. v
  71728. }], waitFill, null, isBelongToGroup); //按邻近点分组
  71729. }
  71730. waitFill.count++; //当数量达到几万以上会在这个地方花很长时间,不过很少出现这种情况
  71731. return;
  71732. }
  71733. }
  71734. /* let diff = top-btm
  71735. let useDiff
  71736. if(btm != void 0 && diff > surfaceThick ){
  71737. useDiff = diff
  71738. result.allDiffHeights.push(useDiff)
  71739. }else{
  71740. useDiff = top //从顶部一直到水平
  71741. }*/
  71742. if (waitFill.length) {
  71743. //补 之前没有值的邻居重新获取
  71744. if (interrupt) {
  71745. return computeFinish('12312');
  71746. }
  71747. if (waitFill.cancel) {
  71748. //console.log('直接清空waitFill', waitFill.count, waitFill.map(list=>[list[0], list[list.length-1]]))
  71749. waitFill.count = 0;
  71750. waitFill.length = 0;
  71751. waitFill.cancel = false;
  71752. } else {
  71753. ///* //Potree.settings.isTest && */ waitFill.count>1000 && console.log('waitFill.count', waitFill.count, 'groupLen', waitFill.length, waitFill[0][0], waitFill[0][waitFill[0].length-1])
  71754. waitFill.slice().forEach(group => {
  71755. //每个组都看看是否跟它相邻
  71756. if (isBelongToGroup(group, {
  71757. u,
  71758. v
  71759. })) {
  71760. var index = waitFill.indexOf(group);
  71761. waitFill.splice(index, 1);
  71762. waitFill.count -= group.length;
  71763. group.forEach(e => {
  71764. result.allFills[e.u] || (result.allFills[e.u] = []);
  71765. result.allFills[e.u][e.v] = top; //该组全部都使用该体积
  71766. });
  71767. var sum = top * group.length;
  71768. add(sum, fill, group.length);
  71769. }
  71770. });
  71771. }
  71772. }
  71773. add(top, fill, 1);
  71774. });
  71775. return function compute(_x, _x2) {
  71776. return _ref2.apply(this, arguments);
  71777. };
  71778. }();
  71779. var lastNotifyTime = Date.now();
  71780. //从左到右,从下到上一列列扫描
  71781. var _loop3 = function* _loop3(_u) {
  71782. for (var _v2 = 0; _v2 < _this.renderTarget.height; _v2++) {
  71783. //数据是从图的下到上存储的
  71784. if (interrupt) {
  71785. return {
  71786. v: {
  71787. v: {
  71788. v: computeFinish('1121')
  71789. }
  71790. }
  71791. };
  71792. }
  71793. compute(_u, _v2);
  71794. }
  71795. yield notify([[progressStart, progressEnd], [0.7, 1]], () => {
  71796. return _u / _this.renderTarget.width;
  71797. }, 'compute');
  71798. },
  71799. _ret3;
  71800. for (var _u = 0; _u < _this.renderTarget.width; _u++) {
  71801. _ret3 = yield* _loop3(_u);
  71802. if (_ret3) return _ret3.v;
  71803. }
  71804. if (waitFill.length) {
  71805. console.log('waitFill怎么还有??', waitFill); //如果是模型的话是有剩的可能,当它的周围刚好是模型的hole时,就被断开在孤立的组里了,如"回"字型,中间的口是有model但无点云处,外面的口是无model处。
  71806. }
  71807. result.Vupper *= sDelta;
  71808. result.fillVlower *= sDelta;
  71809. result.fillVupper *= sDelta;
  71810. result.Vlower += result.fillVlower;
  71811. results.push(result);
  71812. deferred && deferred.notify(progressEnd);
  71813. },
  71814. _ret2;
  71815. for (var j = 0; j < cH; j++) {
  71816. _ret2 = yield* _loop2(j);
  71817. if (_ret2) return _ret2.v;
  71818. }
  71819. },
  71820. _ret;
  71821. for (var _i = 0; _i < cW; _i++) {
  71822. _ret = yield* _loop(_i);
  71823. if (_ret) return _ret.v;
  71824. }
  71825. var Vupper = 0,
  71826. Vlower = 0,
  71827. fillVlower = 0,
  71828. fillVupper = 0;
  71829. results.forEach(c => {
  71830. Vupper += c.Vupper;
  71831. Vlower += c.Vlower;
  71832. fillVlower += c.fillVlower;
  71833. fillVupper += c.fillVupper;
  71834. });
  71835. computeDone({
  71836. highest,
  71837. lowest,
  71838. Vupper,
  71839. Vlower
  71840. }, deferred);
  71841. computeFinish('finish', true);
  71842. console.log({
  71843. Vupper,
  71844. Vlower,
  71845. oldVupper: Vupper - fillVupper,
  71846. oldVlower: Vlower - fillVlower,
  71847. highest,
  71848. lowest,
  71849. horizonZ,
  71850. wDelta
  71851. }, results, _this.viewport.resolution, {
  71852. cW,
  71853. cH
  71854. }, 'cost:', Date.now() - timestamp, 'pxPerMetric', pxPerMetric, 'boundSize', boundSize); //firefox用时是chrome两倍,edge和chrome差不多
  71855. })();
  71856. }
  71857. getModelZByRes(u, v, cW, cH, wIndex, hIndex) {
  71858. //传入renderTarget2的像素index
  71859. //如果两个map的尺寸不同
  71860. var x = Math.round(wIndex / cW + u / this.renderTarget.width * this.renderTarget2.width);
  71861. var y = Math.round(hIndex / cH + v / this.renderTarget.height * this.renderTarget2.height);
  71862. var z0 = modelZs[x][y];
  71863. return z0;
  71864. //return modelZs[u][v]
  71865. }
  71866. render() {
  71867. var _arguments = arguments,
  71868. _this2 = this;
  71869. return _asyncToGenerator(function* () {
  71870. var {
  71871. i,
  71872. j,
  71873. index,
  71874. cW,
  71875. cH,
  71876. reverseRow,
  71877. infos,
  71878. /* maxLevels, */notifyArea,
  71879. computeFinish
  71880. } = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {};
  71881. _this2.view.applyToCamera(_this2.camera);
  71882. Potree.updatePointClouds(viewer.scene.pointclouds, _this2.camera, _this2.viewport.resolution);
  71883. var gl = viewer.renderer.getContext();
  71884. var screenshot = name => {
  71885. //if(window.testScreen){
  71886. var dataUrl = Potree.Utils.renderTargetToDataUrl(_this2.renderTarget, _this2.renderTarget.width, _this2.renderTarget.height, viewer.renderer);
  71887. Common.downloadFile(dataUrl, (name || 'screenshot') + '-' + timestamp + '.png'); //为什么图片上不是只有pickWindowSize区域有颜色??
  71888. //}
  71889. };
  71890. var name = i + '-' + j + '-第' + index + '张';
  71891. console.log('开始渲染', name);
  71892. var camera = _this2.camera;
  71893. var viewport = _this2.viewport;
  71894. return new Promise((resolve, reject) => {
  71895. var done = /*#__PURE__*/function () {
  71896. var _ref3 = _asyncToGenerator(function* () {
  71897. gl.clearColor(0, 0, 0, 0);
  71898. viewer.renderer.clear(true, true, true);
  71899. //viewer.pRenderer.renderOctree(pointcloud, nodes, this.camera, this.renderTarget ,{material:this.material});
  71900. viewer.pRenderer.render(viewer.scene.scenePointCloud, _this2.camera, _this2.renderTarget, {
  71901. material: _this2.material /* transparent:!this.computingObject.isPrism */
  71902. });
  71903. if (interrupt) {
  71904. return reject(), computeFinish('re 23');
  71905. }
  71906. Potree.settings.isTest && screenshot(name);
  71907. gl.readPixels(0, 0, _this2.renderTarget.width, _this2.renderTarget.height, gl.RGBA, gl.UNSIGNED_BYTE, buffer1); //这句花费最多时间 pc:2-4, 即使只有1*1像素
  71908. notifyArea.push([progressEnd1, 1]);
  71909. var Vupper = 0,
  71910. Vlower = 0;
  71911. var upperHeights = [],
  71912. lowerHeights = [],
  71913. allHeights = [];
  71914. var _loop4 = function* _loop4(u) {
  71915. var col = [];
  71916. for (var v = 0; v < _this2.renderTarget.height; v++) {
  71917. var _v = reverseRow ? _this2.renderTarget.height - v - 1 : v;
  71918. var offset = u + _v * _this2.renderTarget.width;
  71919. var rgb = buffer1.slice(4 * offset, 4 * offset + 3),
  71920. a = buffer1[4 * offset + 3];
  71921. if (a == 0 /* rgb[0] == 0 && rgb[1] == 0 && rgb[2] == 0 */) {
  71922. //无点
  71923. col.push(null);
  71924. } else {
  71925. var z = _this2.convertColorToHeight(rgb, zMin, zMax);
  71926. var h = void 0;
  71927. if (!_this2.computingObject.model) {
  71928. h = z - horizonZ;
  71929. } else {
  71930. //和baseModel标准面之间的高度差
  71931. /* if(a == 128){//负数
  71932. h = -h
  71933. } ///如果这个也要lowest 那需改shader ,shader不计算高度差
  71934. */
  71935. var z0 = _this2.getModelZByRes(u, v, cW, cH, i, j);
  71936. h = z - z0;
  71937. }
  71938. z < lowest && (lowest = z); //上表面最低点
  71939. z > highest && (highest = z); //上表面最高点
  71940. if (h > 0) {
  71941. Vupper += h;
  71942. upperHeights.push(h); //
  71943. } else {
  71944. Vlower += -h;
  71945. lowerHeights.push(h);
  71946. }
  71947. col.push(h);
  71948. }
  71949. if (interrupt) {
  71950. return {
  71951. v: (reject(), computeFinish('re 023'))
  71952. };
  71953. }
  71954. //notify(notifyArea, (u*this.renderTarget.height + v) /(this.renderTarget.width*this.renderTarget.height))
  71955. }
  71956. allHeights.push(col);
  71957. yield notify(notifyArea, () => {
  71958. return u / _this2.renderTarget.width;
  71959. }, 'readPixels get');
  71960. },
  71961. _ret4;
  71962. for (var u = 0; u < _this2.renderTarget.width; u++) {
  71963. _ret4 = yield* _loop4(u);
  71964. if (_ret4) return _ret4.v;
  71965. }
  71966. Vupper *= sDelta;
  71967. Vlower *= sDelta;
  71968. infos.push({
  71969. Vupper,
  71970. Vlower,
  71971. sDelta,
  71972. upperHeights,
  71973. lowerHeights,
  71974. allHeights
  71975. });
  71976. resolve();
  71977. });
  71978. return function done() {
  71979. return _ref3.apply(this, arguments);
  71980. };
  71981. }();
  71982. //let finish , maxTime = 1e6
  71983. var progressEnd1 = math.linearClamp(_this2.camera.zoom, [1, 1000], [0.8, 0.2]); //放得越大,实际加载的点云相对越少,费时越少
  71984. var notifyArea_ = [...notifyArea, [0, progressEnd1]];
  71985. if (Potree.pointsLoading) {
  71986. //如果有要加载的node
  71987. var curProgress = 0,
  71988. beginTime = Date.now(),
  71989. unloadBefore,
  71990. tryPreLoadTime = Math.round(math.linearClamp(buffer1.length / _this2.camera.zoom / _this2.camera.zoom, [50, 10000], [1000, 15000]));
  71991. //console.log('tryPreLoadTime',tryPreLoadTime)
  71992. var decreaseLevel = () => {
  71993. //降点云level
  71994. //暂时先都一起降1
  71995. var pointclouds = viewer.scene.pointclouds.filter(e => e.visibleNodes.length);
  71996. console.log('准备decreaseLevel, numVisiblePoints', Potree.numVisiblePoints, '最小numVisiblePoints占比', 1 / pointclouds.length);
  71997. pointclouds.forEach(e => {
  71998. var percent = e.numVisiblePoints / Potree.numVisiblePoints;
  71999. console.log('numVisiblePoints占总比', e.dataset_id, percent);
  72000. if (percent < 1 / pointclouds.length) return;
  72001. var old = e.maxLevel;
  72002. var levels = e.visibleNodes.map(e => e.getLevel());
  72003. var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  72004. e.maxLevel = actMaxLevel - 1;
  72005. console.warn(e.dataset_id, 'decreaseLevel,新maxLevel', actMaxLevel - 1, '原maxlevel', old);
  72006. //this.material.size = this.getPointsize(e.maxLevel)
  72007. //this.material.size *= 2
  72008. });
  72009. };
  72010. var finish = makeit => {
  72011. //viewer.removeEventListener('overPointBudget',decreaseLevel)
  72012. makeit && done();
  72013. viewer.removeEventListener('update', update);
  72014. viewer.removeEventListener('pointsLoaded', loaded);
  72015. };
  72016. var update = () => {
  72017. Potree.updatePointClouds(viewer.scene.pointclouds, camera, viewport.resolution);
  72018. /* if( Potree.numVisiblePoints > maxPointBudge * 0.9){
  72019. decreaseLevel()
  72020. */
  72021. notify(notifyArea_, () => {
  72022. /* console.log('unloadedGeometry',Potree.unloadedGeometry.length)
  72023. return curProgress */
  72024. /* curProgress = THREE.Math.clamp(Potree.numVisiblePoints/predictPointCount,curProgress,1) //如果decreaseLevel了点会减少,也不管它,就停住吧,反正很快就加载好了
  72025. return curProgress */
  72026. if (!unloadBefore && Date.now() - beginTime < tryPreLoadTime) {
  72027. curProgress = (Date.now() - beginTime) / tryPreLoadTime * 0.5;
  72028. } else {
  72029. if (!unloadBefore) {
  72030. unloadBefore = Potree.unloadedGeometry.length;
  72031. //console.log('unloadBefore', unloadBefore)
  72032. }
  72033. unloadBefore = Math.max(Potree.unloadedGeometry.length, unloadBefore); //unloadedGeometry 刚开始可能越涨越多 - - 所以进度条会卡住
  72034. var curProgress_ = 0.5 + 0.5 * (1 - Potree.unloadedGeometry.length / unloadBefore);
  72035. curProgress = Math.max(curProgress, curProgress_);
  72036. }
  72037. //console.log('curProgress ', curProgress, 'numVisiblePoints', Potree.numVisiblePoints, 'unloadedGeometry',Potree.unloadedGeometry.length)
  72038. return curProgress;
  72039. }, 'loadpoints');
  72040. interrupt && (finish(false), reject(), computeFinish('正在loadPoints,unloadedGeometry个数' + Potree.unloadedGeometry.length)); //曾经遇到遇到bug 不发送pointsLoaded 一直update 一直有3个unloadedGeometry加载不了。。 是否为每个加载的node加个计时?
  72041. };
  72042. viewer.addEventListener('update', update);
  72043. var loaded = () => {
  72044. //点云加载完时(不一定准确)
  72045. console.warn('加载完毕', ' numVisiblePoints', Potree.numVisiblePoints);
  72046. finish(true);
  72047. };
  72048. viewer.addEventListener('pointsLoaded', loaded);
  72049. /* let predictPointCount = Math.round(math.linearClamp(buffer.length, [1e5, maxWidth*maxWidth*4],[1e6, maxPointBudge ]))//最终要加载到的数目
  72050. */
  72051. /* let overTime = ()=>{
  72052. if(document.hidden){
  72053. return setTimeout(overTime, maxTime)
  72054. }
  72055. if(!finish)console.warn('超时, numVisiblePoints', Potree.numVisiblePoints)
  72056. dealDone()
  72057. }
  72058. setTimeout(overTime, maxTime) */
  72059. } else {
  72060. notify(notifyArea_, 1);
  72061. done();
  72062. }
  72063. });
  72064. })();
  72065. }
  72066. convertColorToHeight(color, zMin, zMax) {
  72067. var percent = 0;
  72068. var a = 1;
  72069. for (var i = 0; i < 3; i++) {
  72070. a = i == 2 ? a / 255 : a / 256;
  72071. percent += a * color[i];
  72072. }
  72073. var height = (zMax - zMin) * percent;
  72074. return height + zMin;
  72075. }
  72076. getPointsize(maxLevel) {
  72077. //尽量铺满 size单位是米,需要和点云缝隙同宽
  72078. return 0.01; /* adaptive:0.2 */
  72079. var s = /* this.material.spacing */100 / Math.pow(2, maxLevel - 1); //adaptive的话在shader中已经乘了spacing
  72080. console.log('getPointsize', s, 'maxLevel', maxLevel);
  72081. return s; //会不会直接返回1就好?
  72082. //不能太小。假如gl_pointsize计算结果是0.1,那么显示就是1px;当level将级后,放大2倍为0.2,也还是1px,看起来就稀疏了。所以要保证这个数在最大level时gl_pointsize计算结果差不多是1px.(虽然我会在渲染大尺寸面积时降画布尺寸,但不能保证刚刚好,且因点云个数不可控不会降尺寸太狠)
  72083. }
  72084. download(prisms) {
  72085. if (this.prisms.length == 0) {
  72086. return null;
  72087. }
  72088. var visiPointclouds = viewer.scene.pointclouds.filter(e => Potree.Utils.getObjVisiByReason(e, 'datasetSelection'));
  72089. visiPointclouds.sort((a, b) => {
  72090. return a.dataset_id - b.dataset_id;
  72091. }); //缓存需要固定排序好比较
  72092. var data = {
  72093. transformation_matrix: visiPointclouds.map(cloud => {
  72094. var data = {
  72095. id: cloud.dataset_id,
  72096. matrix: new Matrix4().elements,
  72097. //参照downloadNoCrop,给默认值,表示没有最外层裁剪
  72098. visiMatrixes: prisms.map(prism => {
  72099. return {
  72100. matrix: prism.getTransformationMatrix(cloud).elements,
  72101. //剪裁框
  72102. points: prism.points.map(p => {
  72103. return {
  72104. x: p.x,
  72105. y: p.y
  72106. };
  72107. })
  72108. };
  72109. }),
  72110. modelMatrix: new Matrix4().copy(cloud.transformMatrix).transpose().elements
  72111. };
  72112. return data;
  72113. }),
  72114. aabb: "b-12742000 -12742000 -12742000 12742000 12742000 12742000" //剪裁空间
  72115. };
  72116. return data;
  72117. }
  72118. //体积多边形棱柱,z需要变换到-0.5 ~ 0.5
  72119. }
  72120. /* VolumeComputer.prototype.setClipBoxes = function(){
  72121. let lastPrisms = []
  72122. return function(){
  72123. let prismPolygons = this.prisms.filter(e=>!e.isNew && e.visible)
  72124. let prismList = [], prismPoints = [], maxPointsCount
  72125. if(prismPolygons.length){
  72126. let pointsCount = prismPolygons.pointsCount = prismPolygons.reduce((w,c)=>{return w+c.points.length},0)
  72127. prismList = new Float32Array(9 * prismPolygons.length);
  72128. prismPoints = new Float32Array(2 * pointsCount);
  72129. prismPolygons.maxPointsCount = 0//单个prism最大点个数
  72130. if(!this.entered)this.enter()
  72131. let pointIndex = 0
  72132. for(let i=0;i<prismPolygons.length;i++ ){
  72133. let bound = prismPolygons[i].prismBound
  72134. let z = prismPolygons[i].horizonZ
  72135. //z = Potree.browser.urlHasValue('zmin',true) || zs[0]
  72136. prismList.set([bound.min.z, z, bound.max.z, bound.min.x, bound.max.x, bound.min.y, bound.max.y, prismPolygons[i].points.length ],9*i);
  72137. //prismList.push(new THREE.Matrix3().fromArray([bound.min.z, z, bound.max.z, bound.min.x, bound.max.x, bound.min.y, bound.max.y, prismPolygons[i].points.length,0 ]))
  72138. for(let j=0;j<prismPolygons[i].points.length;j++){
  72139. prismPoints.set([prismPolygons[i].points[j].x, prismPolygons[i].points[j].y] , 2*j+pointIndex);
  72140. //prismPoints.push( new THREE.Vector2().copy(prismPolygons[i].points[j]))
  72141. }
  72142. pointIndex += 2 * prismPolygons[i].points.length
  72143. prismPolygons.maxPointsCount = Math.max(prismPolygons.maxPointsCount, prismPolygons[i].points.length)
  72144. }
  72145. }
  72146. let doUpdate = ( lastPrisms.length != prismPolygons.length) || lastPrisms.maxPointsCount != prismPolygons.maxPointsCount
  72147. let materials = viewer.scene.pointclouds.map(e=>e.material).concat([this.material])
  72148. materials.forEach(e=>{
  72149. e.uniforms.prismList.value = prismList
  72150. e.uniforms.prismPoints.value = prismPoints
  72151. e.shaderNeedsUpdate = e.shaderNeedsUpdate || doUpdate
  72152. e.prisms = prismPolygons
  72153. })
  72154. //修改obj材质
  72155. this.material.defines.num_prism = this.material.prisms.length//土方量数
  72156. this.material.defines.prismPointCountSum = this.material.prisms.pointsCount //点总个数
  72157. this.material.defines.prism_maxPointsCount = this.material.prisms.maxPointsCount //单个prism最大点个数
  72158. if(doUpdate){
  72159. this.material.needsUpdate = true
  72160. viewer.dispatchEvent('content_changed')
  72161. }
  72162. lastPrisms = prismPolygons
  72163. }
  72164. }(); */
  72165. /*
  72166. 渲染像素pxPerMetric越高,边缘越细腻、准确; 点size越小,越不容易遮盖住下方点云,造成体积偏大。但会不会有底部点云透出来?
  72167. 该版本计算用到两张截图,第一张为整体的俯视图,包括挖方和填方;第二张仅包含填方。
  72168. 缺陷:在补洞时,只利用第一张图的结果,所以整体的挖方会偏多,填方偏少(因为在挖方填方同时存在时,没有分别补挖方和填方,而是放在一起,而上方可能遮盖下方的)
  72169. 尝试过第一张只绘制挖方部分,但是在遍历时就需要多遍历一次,测得的用时更多一些,结果却没变化
  72170. 也尝试过补洞时挖方填方分别补各自的,但这样要考虑更多的东西,用时多了两倍以上。(因为目前规定无论范围内实际有没有点云都补上,非挖即填;如果分开的话,填方边缘也都补上肯定是错的,无法找到挖和填的界限,无法分清是只有挖还是填还是两者均有。如果要探测周围点,耗时很多)
  72171. 如果数据集修改了,土方量需要手动重算。所以场景刷新后显示的体积有可能是错的。
  72172. 之前记的,太麻烦了,延期处理:
  72173. 1 一般情况:我需要记录每个土方量范围内存在的数据集的位置,如
  72174. {datasetId:"1745733728954093568", location:[113.59550104511611, 22.36677932324081, 0] ,orientation: 0.1}
  72175. 如果刷新后土方量范围内存在的数据集发生改变,将重算。
  72176. 数据集也可能显示或隐藏
  72177. 2 其他特殊情况,如裁剪,难以知道裁剪了哪块,所以只能全部重算
  72178. ------------------
  72179. baseModel 基于模型的挖方填方
  72180. 由于模型高度不一致,只能把相机放最高处朝下看,而无法像prism那样在horizonZ处再渲染一张,所以更加不能有多层点云干扰。
  72181. 如模型在一个房间屋顶上方,那么填方会得到两个高度,屋顶和地板的高度,地板是从屋顶的点云缝隙而得。
  72182. 如果模型放房间中间,并不能按理想的那样得到其上的挖方和其下的填方,因为相机朝下看时屋顶会遮住屋底,导致填方减少挖方增多。虽然能在bound底部朝上再拍一张,但若是有更复杂的情况依旧不能保证正确。
  72183. 故需要设置好zMin zMax
  72184. 如果模型有可能很大,但数据集不大,可以将bound只取交集
  72185. */
  72186. var texLoader$d = new TextureLoader();
  72187. var circleGeo = new CircleGeometry(1.45, 100);
  72188. var sphereGeo$1 = new SphereBufferGeometry(0.008, 8, 8);
  72189. var magDisMin = 1; //相机离目标位置的距离的分界线,当离得远时要缩小fov以使看到的视野固定(望远镜效果)
  72190. var magDisMax = 20;
  72191. /* const radius_ = 0.2; //当相机离目标位置的距离>magDistance_时,希望看到的视野的半径
  72192. const maxFov = THREE.Math.radToDeg(Math.atan(radius_ / magDisMin )) * 2//提前计算出当相机离目标位置的距离<magDisMin时的fov,均使用=magDisMin时的fov。只要保证该fov大于主相机的fov就会有放大效果
  72193. */
  72194. var w$1 = 230 / 1.43;
  72195. var maxPX = 1366 * 1024; //ipad pro. 大于这个分辨率的就直接用devicePixelRatio, 如macbook也是
  72196. var width2dPX = Math.round(window.devicePixelRatio >= 2 ? (window.screen.width * window.screen.height >= maxPX ? window.devicePixelRatio / 1.2 : window.devicePixelRatio / 1.5) * w$1 : w$1); //触屏或高分辨率的可能要放大些。但在手机上不能太大
  72197. //console.log('width2dPX', width2dPX)
  72198. var orthoView = new ExtendView();
  72199. class Magnifier extends Object3D {
  72200. //放大镜or望远镜
  72201. constructor(viewer) {
  72202. super();
  72203. this.width = this.height = width2dPX /* * window.devicePixelRatio */;
  72204. this.camera = new PerspectiveCamera(50, 1, 0.01, 10000); //fov aspect near far
  72205. this.camera.up = new Vector3(0, 0, 1);
  72206. this.viewport = new Viewport(null, this.camera, {
  72207. left: 0,
  72208. bottom: 0,
  72209. width: 1,
  72210. height: 1,
  72211. name: 'magnifier',
  72212. cameraLayers: ['magnifierContent'],
  72213. pixelRatio: 1
  72214. });
  72215. this.viewport.setResolution(this.width, this.height, 0, 0);
  72216. {
  72217. var density;
  72218. var sizeType;
  72219. var colorType;
  72220. var opacityBefore = new Map();
  72221. var sizeBefore = new Map();
  72222. var visiMap = new Map();
  72223. this.viewport.beforeRender = () => {
  72224. viewer.scene.pointclouds.forEach(e => {
  72225. //因为更改pointDensity时会自动变opacity,所以这项最先获取
  72226. visiMap.set(e, e.visible);
  72227. e.visible = Potree.Utils.getObjVisiByReason(e, 'datasetSelection'); //先将隐藏的点云显示
  72228. opacityBefore.set(e, e.temp.pointOpacity);
  72229. sizeBefore.set(e, e.temp.pointSize);
  72230. });
  72231. //使放大镜里的pointDensity是'magnifier' 最高质量。
  72232. density = Potree.settings.pointDensity;
  72233. Potree.settings.pointDensity = 'magnifier';
  72234. viewer.scene.pointclouds.forEach(e => {
  72235. //因为全景模式的pointSizeType是fixed所以要还原下
  72236. sizeType = e.material.pointSizeType;
  72237. e.material.pointSizeType = Potree.config.material.pointSizeType;
  72238. //材质
  72239. colorType = e.material.activeAttributeName;
  72240. e.material.activeAttributeName = 'rgba';
  72241. e.changePointOpacity(1);
  72242. //e.changePointSize(Potree.config.material.realPointSize, true)
  72243. });
  72244. };
  72245. this.viewport.afterRender = () => {
  72246. Potree.settings.pointDensity = density;
  72247. viewer.scene.pointclouds.forEach(e => {
  72248. e.visible = visiMap.get(e);
  72249. e.material.pointSizeType = sizeType;
  72250. e.material.activeAttributeName = colorType;
  72251. e.changePointOpacity(opacityBefore.get(e));
  72252. //e.changePointSize(sizeBefore.get(e))
  72253. });
  72254. };
  72255. }
  72256. this.renderTarget = new WebGLRenderTarget(this.width, this.height, {
  72257. minFilter: LinearFilter,
  72258. magFilter: LinearFilter,
  72259. format: RGBAFormat
  72260. /* type: THREE.FloatType,
  72261. minFilter: THREE.NearestFilter,
  72262. magFilter: THREE.NearestFilter,
  72263. */
  72264. });
  72265. this.rtEDL = new WebGLRenderTarget(this.width, this.height, {
  72266. //好像没用到? 因为这里不绘制测量线
  72267. minFilter: NearestFilter,
  72268. magFilter: NearestFilter,
  72269. format: RGBAFormat,
  72270. type: FloatType,
  72271. depthTexture: new DepthTexture(undefined, undefined, UnsignedIntType)
  72272. });
  72273. this.mesh = new Mesh(circleGeo, new MeshBasicMaterial({
  72274. side: DoubleSide,
  72275. map: this.renderTarget.texture,
  72276. transparent: true,
  72277. depthTest: !1
  72278. //depthWrite: !1,
  72279. }));
  72280. this.overlayMesh = new Mesh(circleGeo, new MeshBasicMaterial({
  72281. side: DoubleSide,
  72282. map: texLoader$d.load(Potree.resourcePath + '/textures/crosshair.png'),
  72283. transparent: true,
  72284. depthTest: !1
  72285. //depthWrite: !1,
  72286. }));
  72287. this.targetPoint = new Object3D();
  72288. this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({
  72289. color: "#ff0000",
  72290. transparent: true,
  72291. opacity: 0.7
  72292. })));
  72293. this.targetPoint.add(new Mesh(sphereGeo$1, new MeshBasicMaterial({
  72294. color: "#ff0000",
  72295. transparent: true,
  72296. opacity: 0.3,
  72297. depthTest: false //被遮挡层
  72298. })));
  72299. this.targetPoint.name = 'magnifierPointTarget';
  72300. viewer.scene.scene.add(this.targetPoint);
  72301. Potree.Utils.setObjectLayers(this.targetPoint, 'magnifierContent');
  72302. this.add(this.mesh);
  72303. this.add(this.overlayMesh);
  72304. this.position.set(-1000, -1000, -100000); //令它看不见
  72305. this.mesh.renderOrder = Potree.config.renderOrders.magnifier;
  72306. this.overlayMesh.renderOrder = Potree.config.renderOrders.magnifier + 1;
  72307. this.aimPos;
  72308. Potree.Utils.setObjectLayers(this, 'magnifier');
  72309. //viewer.inputHandler.addInputListener(this)
  72310. viewer.addEventListener('camera_changed', e => {
  72311. // 平移、滚轮时更新
  72312. if (e.viewport == viewer.mainViewport) this.update(); //不过intersectPoint没更新
  72313. });
  72314. this.mesh.layers.set(Potree.config.renderLayers.magnifier);
  72315. this.overlayMesh.layers.set(Potree.config.renderLayers.magnifier);
  72316. //this.layers.set(Potree.config.renderLayers.magnifier);//这句在外层写没用
  72317. this.dontRender = false;
  72318. viewer.addEventListener('global_drag', e => {
  72319. //拖拽时不渲染。主要是右键平移时渲染延迟了,会闪烁。
  72320. this.dontRender = true;
  72321. });
  72322. viewer.addEventListener('global_drop', e => {
  72323. this.dontRender = false;
  72324. });
  72325. viewer.addEventListener('global_mouseup', e => {
  72326. //测量时拖拽场景再mouseup
  72327. this.dontRender = false;
  72328. });
  72329. var updateVisi = e => {
  72330. if (e.hoverViewport == viewer.mainViewport) {
  72331. Potree.Utils.updateVisible(this, "atViewport", true);
  72332. this.update(e.intersect && e.intersect.location);
  72333. } else {
  72334. Potree.Utils.updateVisible(this, "atViewport", false); //小地图不显示
  72335. }
  72336. };
  72337. viewer.addEventListener('global_mousemove', updateVisi);
  72338. viewer.addEventListener('global_touchstart', updateVisi);
  72339. viewer.addEventListener('updateMagnifier', updateVisi);
  72340. /* viewer.addEventListener("beginSplitView",()=>{
  72341. this.updateVisible("splitView", false)
  72342. })
  72343. viewer.addEventListener("finishSplitView",()=>{
  72344. this.updateVisible("splitView", true)
  72345. }) */
  72346. this.addEventListener("setEnable", e => {
  72347. Potree.Utils.updateVisible(this, "enable", e.value); //界面开关
  72348. /* if(Potree.settings.displayMode == 'showPanos') && e.value){
  72349. Potree.settings.pointDensity = 'magnifier'
  72350. }else if() */
  72351. viewer.dispatchEvent('content_changed');
  72352. });
  72353. if (Potree.settings.isOfficial) {
  72354. Potree.Utils.updateVisible(this, "enable", false);
  72355. } else {
  72356. Potree.Utils.updateVisible(this, "measure", false);
  72357. viewer.addEventListener("measureMovePoint", () => {//测量开始
  72358. //Potree.Utils.updateVisible(this, "measure", true)
  72359. });
  72360. viewer.addEventListener("endMeasureMove", () => {
  72361. Potree.Utils.updateVisible(this, "measure", false);
  72362. viewer.dispatchEvent('content_changed');
  72363. });
  72364. }
  72365. this.addEventListener('isVisible', e => {
  72366. if (!this.visible) Potree.settings.pointDensity = Potree.settings.pointDensity; //恢复pointBudget
  72367. });
  72368. viewer.scene.view.addEventListener('flyingDone', () => {
  72369. if (!this.visible) return;
  72370. var pickWindowSize = 100;
  72371. var intersect = viewer.inputHandler.getIntersect({
  72372. viewport: viewer.mainViewport,
  72373. usePointcloud: true,
  72374. pickWindowSize
  72375. });
  72376. this.update(intersect && intersect.location);
  72377. });
  72378. }
  72379. //注意:在鼠标没有移动的时候,无法获取到最新的intersect, 放大镜内的内容可能是错误的。全景模式下更奇怪,原因未知
  72380. update(aimPos) {
  72381. //相机靠近 navvis的做法
  72382. var dontRender = this.dontRender || !(aimPos instanceof Vector3) || Potree.settings.displayMode == 'showPanos' && viewer.images360.flying;
  72383. aimPos = aimPos instanceof Vector3 ? aimPos : this.aimPos;
  72384. if (!aimPos || !this.visible) return;
  72385. var playerCamera = viewer.scene.getActiveCamera();
  72386. var playerPos = playerCamera.position; //viewer.scene.view.getPivot()
  72387. var dis = playerPos.distanceTo(aimPos);
  72388. var dirToCamera = new Vector3().subVectors(playerPos, aimPos).normalize();
  72389. var fareast = 300;
  72390. //相机位置
  72391. if (playerCamera.type == 'OrthographicCamera') {
  72392. var finalDisToAim = 2;
  72393. } else {
  72394. var finalDisToAim = dis > magDisMin ? dis > fareast ? magDisMax : (dis - magDisMin) / (fareast - magDisMin) * (magDisMax - magDisMin) + magDisMin : dis / 2; //dis>magDistance_ ? magDistance_ : dis / 2;
  72395. }
  72396. this.camera.fov = playerCamera.type == 'OrthographicCamera' ? 30 : playerCamera.fov / 2;
  72397. this.camera.updateProjectionMatrix();
  72398. if (playerCamera.type == 'OrthographicCamera') {
  72399. orthoView.position.copy(aimPos).sub(viewer.mainViewport.view.direction.multiplyScalar(finalDisToAim));
  72400. orthoView.yaw = viewer.mainViewport.view.yaw;
  72401. orthoView.pitch = viewer.mainViewport.view.pitch;
  72402. orthoView.applyToCamera(this.camera);
  72403. } else {
  72404. this.camera.position.copy(aimPos).add(dirToCamera.multiplyScalar(finalDisToAim));
  72405. this.camera.lookAt(aimPos);
  72406. }
  72407. //自身位置
  72408. //let pos2d = viewer.inputHandler.pointer.clone(); //跟随鼠标
  72409. var pos2d_ = Potree.Utils.getPos2d(aimPos, viewer.mainViewport, viewer.renderArea); //更新目标点的实时二维位置
  72410. var pos2d = pos2d_.vector;
  72411. var margin = width2dPX * 1.1 / viewer.mainViewport.resolution2.y * 2; //确保到鼠标的间距占放大镜的比例不变(检查mobile、上下分屏后的变化)
  72412. var screenPos = pos2d.clone().setY(pos2d.y + (pos2d.y > 0 ? -margin : margin));
  72413. var newPos = new Vector3(screenPos.x, screenPos.y, 0.8).unproject(playerCamera); //z:-1朝外
  72414. if (playerCamera.type != 'OrthographicCamera') {
  72415. var dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10); //这个数值要大于playerCamera.near
  72416. this.position.copy(playerPos.clone().add(dir));
  72417. } else {
  72418. viewer.navCubeViewer.splitScreen.setShiftTarget(viewer.mainViewport, viewer.bound.center);
  72419. viewer.mainViewport.targetPlane.setFromNormalAndCoplanarPoint(viewer.mainViewport.view.direction.clone(), viewer.bound.center);
  72420. viewer.mainViewport.targetPlane.projectPoint(newPos, viewer.mainViewport.shiftTarget);
  72421. this.position.copy(viewer.mainViewport.shiftTarget.clone());
  72422. //this.position.copy(playerPos.clone().add(dir))
  72423. }
  72424. var s = finalDisToAim * this.camera.fov / 30;
  72425. this.quaternion.copy(playerCamera.quaternion);
  72426. this.targetPoint.position.copy(aimPos);
  72427. this.targetPoint.scale.set(s, s, s);
  72428. this.aimPos = aimPos;
  72429. var scale = math.getScaleForConstantSize({
  72430. //
  72431. width2d: width2dPX,
  72432. camera: viewer.scene.getActiveCamera(),
  72433. position: this.getWorldPosition(new Vector3()),
  72434. resolution: viewer.mainViewport.resolution2
  72435. });
  72436. this.scale.set(scale, scale, scale);
  72437. if (!dontRender) {
  72438. this.waitRender = true;
  72439. }
  72440. viewer.dispatchEvent('content_changed');
  72441. }
  72442. /* update(aimPos){ //仅改fov的版本
  72443. aimPos = aimPos instanceof THREE.Vector3 ? aimPos : this.aimPos
  72444. if(!aimPos || !this.visible)return
  72445. //相机位置
  72446. var playerCamera = viewer.scene.getActiveCamera()
  72447. var playerPos = playerCamera.position;//viewer.scene.view.getPivot()
  72448. var dis = playerPos.distanceTo(aimPos);
  72449. if(dis<magDisMin){
  72450. this.camera.fov = maxFov
  72451. }else{
  72452. this.camera.fov = THREE.Math.radToDeg(Math.atan(radius_ / dis )) * 2 //radius_是能看到的范围半径。当dis大于magDisMin时就放大,否则维持fov为maxFov
  72453. }
  72454. this.camera.updateProjectionMatrix()
  72455. this.camera.position.copy(playerPos)
  72456. this.camera.lookAt(aimPos)
  72457. this.quaternion.copy(playerCamera.quaternion);
  72458. let pointer = viewer.inputHandler.pointer.clone();
  72459. let margin = 0.4, maxY = 0.4
  72460. let screenPos = pointer.clone().setY(pointer.y + (pointer.y>maxY ? -margin : margin ))
  72461. let newPos = new THREE.Vector3(screenPos.x,screenPos.y,0.8).unproject(playerCamera); //z:-1朝外
  72462. let dir = newPos.clone().sub(playerPos).normalize().multiplyScalar(10);//这个数值要大于playerCamera.near
  72463. this.position.copy(playerPos.clone().add(dir))
  72464. this.aimPos = aimPos
  72465. this.targetPoint.position.copy(aimPos);
  72466. var scale = math.getScaleForConstantSize({//
  72467. width2d : width2dPX,
  72468. camera:viewer.scene.getActiveCamera(), position: this.getWorldPosition(new THREE.Vector3()),
  72469. resolution: viewer.mainViewport.resolution2
  72470. })
  72471. this.scale.set(scale, scale, scale);
  72472. if(!this.dontRender){
  72473. this.waitRender = true
  72474. }
  72475. }//位置需要计算,不仅仅是点云,所以需要深度图
  72476. */
  72477. render() {
  72478. if (!this.visible || !this.waitRender && !viewer.needRender) return; //viewer.needRender为true要渲染是因为可能是点云node加载完
  72479. viewer.render({
  72480. target: this.renderTarget,
  72481. viewports: [this.viewport],
  72482. camera: this.camera,
  72483. magnifier: true,
  72484. rtEDL: this.rtEDL
  72485. /* width :this.renderTarget.width,
  72486. height: this.renderTarget.height, */
  72487. });
  72488. this.waitRender = false;
  72489. viewer.dispatchEvent('content_changed');
  72490. }
  72491. }
  72492. /*
  72493. 如果遇到放大镜内点云很不正常,应该是深度图错误(可能全景和点云没匹配上)。
  72494. */
  72495. var texLoader$e = new TextureLoader();
  72496. var defaultOpacity = 0.6;
  72497. var Buttons$2 = Potree.defines.Buttons;
  72498. //鼠标指示小圆片
  72499. class Reticule extends Mesh {
  72500. constructor(viewer) {
  72501. var defaultTex = texLoader$e.load(Potree.resourcePath + '/textures/whiteCircle.png' /* reticule-256x256.png' */);
  72502. super(new PlaneBufferGeometry(0.11, 0.11, 1, 1), new MeshBasicMaterial({
  72503. side: DoubleSide,
  72504. map: defaultTex,
  72505. transparent: true,
  72506. depthTest: !1,
  72507. opacity: defaultOpacity
  72508. //depthWrite: !1,
  72509. }));
  72510. this.name = 'reticule';
  72511. this.defaultTex = defaultTex;
  72512. this.crosshairTex = texLoader$e.load(Potree.resourcePath + '/textures/reticule_cross_hair.png');
  72513. this.forbitTex = texLoader$e.load(Potree.resourcePath + '/textures/pic-forbid.png');
  72514. this.defaultTex.anisotropy = 4;
  72515. this.crosshairTex.anisotropy = 4;
  72516. this.forbitTex.anisotropy = 4;
  72517. //this.layers.set(0/* RenderLayers.RETICULE */);
  72518. this.renderOrder = Potree.config.renderOrders.reticule;
  72519. this.layers.set(Potree.config.renderLayers.marker);
  72520. this.direction = new Vector3();
  72521. this.mouseLastMoveTime = Date.now();
  72522. this.hoverViewport;
  72523. this.matrixMap = new Map();
  72524. this.matrixAutoUpdate = false;
  72525. this.hide(0);
  72526. //viewer.inputHandler.addInputListener(this);
  72527. Potree.settings.intersectWhenHover && viewer.addEventListener('global_mousemove', this.move.bind(this));
  72528. //viewer.addEventListener('global_click',this.move.bind(this))
  72529. viewer.addEventListener('global_mousedown', this.move.bind(this)); //主要针对触屏
  72530. this.state = {};
  72531. var startCrossStyle = () => {
  72532. this.state.cross = true;
  72533. this.judgeTex();
  72534. };
  72535. var endCrossStyle = () => {
  72536. this.state.cross = false;
  72537. this.judgeTex();
  72538. };
  72539. viewer.addEventListener('measureMovePoint', startCrossStyle);
  72540. viewer.addEventListener('endMeasureMove', endCrossStyle);
  72541. viewer.addEventListener('startBuildEntity', startCrossStyle);
  72542. viewer.addEventListener('endBuildEntity', endCrossStyle);
  72543. viewer.addEventListener('start_inserting_tag', startCrossStyle);
  72544. viewer.addEventListener('endTagMove', endCrossStyle);
  72545. viewer.addEventListener('reticule_forbit', e => {
  72546. if (this.state.forbit != e.v) {
  72547. console.log('change forbit ', e.v);
  72548. }
  72549. this.state.forbit = e.v;
  72550. this.judgeTex();
  72551. });
  72552. Potree.Utils.setObjectLayers(this, 'sceneObjects');
  72553. }
  72554. judgeTex() {
  72555. if (this.state.forbit) {
  72556. this.material.map = this.forbitTex;
  72557. } else if (this.state.cross) {
  72558. this.material.map = this.crosshairTex;
  72559. } else {
  72560. this.material.map = this.defaultTex;
  72561. }
  72562. viewer.mapViewer && viewer.mapViewer.dispatchEvent({
  72563. type: 'content_changed'
  72564. });
  72565. }
  72566. move(e) {
  72567. if (e.type == "global_mousemove" && (e.isTouch || e.buttons != Buttons$2.NONE) && !this.state.cross) {
  72568. return; //按下时不更新,除非拖拽测量
  72569. }
  72570. this.mouseLastMoveTime = Date.now();
  72571. this.updatePosition(e.intersect, e.hoverViewport);
  72572. }
  72573. hide() {
  72574. var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 500;
  72575. if (this.hidden) return;
  72576. this.hidden = !0;
  72577. transitions.start(lerp.property(this.material, "opacity", 0, () => {
  72578. //progress
  72579. this.dispatchEvent({
  72580. type: 'update'
  72581. });
  72582. //viewer.dispatchEvent('content_changed')
  72583. }), duration, () => {
  72584. //done
  72585. this.dispatchEvent({
  72586. type: 'update',
  72587. visible: false
  72588. });
  72589. });
  72590. this.dispatchEvent({
  72591. type: 'update',
  72592. visible: false
  72593. });
  72594. setTimeout(() => {}, duration);
  72595. }
  72596. show() {
  72597. var duration = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300;
  72598. if (!Potree.Utils.getObjVisiByReason(this, 'force')) return;
  72599. //console.log("show Reticule")
  72600. this.hidden = !1;
  72601. if (this.material.opacity <= 0) {
  72602. transitions.start(lerp.property(this.material, "opacity", defaultOpacity, () => {
  72603. //progress
  72604. this.dispatchEvent({
  72605. type: 'update'
  72606. });
  72607. //viewer.dispatchEvent('content_changed')
  72608. }), duration, () => {
  72609. //done
  72610. this.dispatchEvent({
  72611. type: 'update',
  72612. visible: false
  72613. });
  72614. });
  72615. this.dispatchEvent({
  72616. type: 'update',
  72617. visible: true
  72618. });
  72619. }
  72620. }
  72621. //鼠标静止一段时间它就会消失
  72622. updateVisible() {
  72623. Date.now() - this.mouseLastMoveTime > 1500 && !this.hidden && this.hide();
  72624. }
  72625. updateScale(viewport) {
  72626. var s,
  72627. camera = viewport.camera;
  72628. if (camera.type == "OrthographicCamera") {
  72629. var sizeInfo = this.state.cross ? {
  72630. width2d: 500
  72631. } : {
  72632. minSize: 100,
  72633. maxSize: 400,
  72634. nearBound: 100,
  72635. farBound: 700
  72636. };
  72637. s = math.getScaleForConstantSize($.extend(sizeInfo, {
  72638. position: this.position,
  72639. camera,
  72640. resolution: viewport.resolution /* 2 */
  72641. }));
  72642. } else {
  72643. var n = camera.position.distanceTo(this.position);
  72644. s = 0.8 * Math.log2(n + 1); //底数为2 ( Math.log()底数为e )
  72645. if (this.state.cross) {
  72646. //测量时更精细些
  72647. s /= viewer.images360.zoomLevel;
  72648. }
  72649. }
  72650. this.scale.set(s, s, s);
  72651. }
  72652. updateAtViewports(viewport) {
  72653. //当多个viewports时更新。更新大小等
  72654. if (viewport.name == 'magnifier') return;
  72655. if (this.orthoPos && this.hoverViewport && this.hoverViewport.name == 'mapViewport' && viewport != this.hoverViewport) {
  72656. //若是在地图上更新,在其他viewport要隐藏。因为在地图上无法得知高度。
  72657. Potree.Utils.updateVisible(this, 'hoverMap', false);
  72658. return;
  72659. }
  72660. Potree.Utils.updateVisible(this, 'hoverMap', true);
  72661. if (viewport.name == 'mapViewport') {
  72662. Potree.Utils.setObjectLayers(this, "bothMapAndScene");
  72663. } else {
  72664. //通常地图不显示reticule,只有在特殊编辑时才显示
  72665. Potree.Utils.setObjectLayers(this, 'sceneObjects');
  72666. }
  72667. var matrix = this.matrixMap.get(viewport);
  72668. if (!matrix) {
  72669. this.updateScale(viewport);
  72670. this.updateMatrix();
  72671. //this.updateMatrixWorld()
  72672. this.matrixMap.set(viewport, this.matrix.clone());
  72673. } else {
  72674. this.matrix.copy(matrix);
  72675. //this.updateMatrixWorld()
  72676. }
  72677. }
  72678. updatePosition(intersect, viewport) {
  72679. //在地图(当地图融合到viewer时)和场景里都显示且完全相同(大小可能不同)
  72680. if (Potree.Utils.getObjVisiByReason(this, 'force')) {
  72681. //没有被强制隐藏,如进入某个页面后强制不显示
  72682. if (!intersect /* || !intersect.point.normal */) {
  72683. return; //this.hide();
  72684. }
  72685. var atMap = !intersect.location;
  72686. var location = intersect.location || intersect.orthoIntersect.clone();
  72687. var normal;
  72688. this.orthoPos = atMap;
  72689. //地图上要瞬间变化 , 因为要使needRender为true很麻烦
  72690. this.show(atMap ? 0 : 300);
  72691. if (atMap) {
  72692. normal = new Vector3(0, 0, 1); //地图无normal
  72693. location.setZ(0); //低于相机高度即可
  72694. this.direction = normal.clone();
  72695. } else {
  72696. /* if(intersect.point){
  72697. if(intersect.pointcloud){
  72698. normal = new THREE.Vector3().fromArray(intersect.point.normal ).applyMatrix4( intersect.pointcloud.rotateMatrix );
  72699. }else{//mesh
  72700. normal = new THREE.Vector3().copy(intersect.point.normal).applyQuaternion(intersect.object.quaternion)
  72701. }
  72702. }else{
  72703. normal = intersect.normal //when showPanos
  72704. } */
  72705. normal = intersect.normal;
  72706. if (normal) {
  72707. var ratio = /* Potree.settings.useDepthTex ? 1 : */0.2;
  72708. this.direction = this.direction.multiplyScalar(1 - ratio);
  72709. this.direction.add(normal.clone().multiplyScalar(ratio));
  72710. }
  72711. //this.direction = normal.clone() //改为瞬间变化,否则刚hover上某个点时看起来不太对
  72712. }
  72713. this.position.copy(location); /* .add(normal.clone().multiplyScalar(.01)); */
  72714. this.updateMatrix(); //lookAt之前要保证得到matrix
  72715. this.lookAt(this.position.clone().add(this.direction));
  72716. this.hoverViewport = viewport; //记录下最近一次hover过的viewport
  72717. this.updateScale(viewport);
  72718. {
  72719. //存储matrix,节省计算
  72720. this.updateMatrix();
  72721. //this.updateMatrixWorld()
  72722. this.matrixMap.clear(); //重新计算
  72723. this.matrixMap.set(viewport, this.matrix.clone());
  72724. //别处会updateMatrixWorld
  72725. }
  72726. this.dispatchEvent({
  72727. type: 'update'
  72728. });
  72729. //为什么navvis在校准数据集时每个viewport里reticule的朝向都刚好垂直于屏幕,似乎限定在了一定范围内,还是在pick时就只pick范围内的点?
  72730. }
  72731. }
  72732. //navvis在地图等地方看reticule是有厚度的
  72733. /* updateMatrixWorld(force){
  72734. console.log('updateMatrixWorld', force)
  72735. super.updateMatrixWorld(force)
  72736. } */
  72737. }
  72738. var OBJLoader = function () {
  72739. // o object_name | g group_name
  72740. var object_pattern = /^[og]\s*(.+)?/;
  72741. // mtllib file_reference
  72742. var material_library_pattern = /^mtllib /;
  72743. // usemtl material_name
  72744. var material_use_pattern = /^usemtl /;
  72745. // usemap map_name
  72746. var map_use_pattern = /^usemap /;
  72747. var vA = new Vector3();
  72748. var vB = new Vector3();
  72749. var vC = new Vector3();
  72750. var ab = new Vector3();
  72751. var cb = new Vector3();
  72752. function ParserState() {
  72753. var state = {
  72754. objects: [],
  72755. object: {},
  72756. vertices: [],
  72757. normals: [],
  72758. colors: [],
  72759. uvs: [],
  72760. materials: {},
  72761. materialLibraries: [],
  72762. startObject: function startObject(name, fromDeclaration) {
  72763. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  72764. // file. We need to use it for the first parsed g/o to keep things in sync.
  72765. if (this.object && this.object.fromDeclaration === false) {
  72766. this.object.name = name;
  72767. this.object.fromDeclaration = fromDeclaration !== false;
  72768. return;
  72769. }
  72770. var previousMaterial = this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined;
  72771. if (this.object && typeof this.object._finalize === 'function') {
  72772. this.object._finalize(true);
  72773. }
  72774. this.object = {
  72775. name: name || '',
  72776. fromDeclaration: fromDeclaration !== false,
  72777. geometry: {
  72778. vertices: [],
  72779. normals: [],
  72780. colors: [],
  72781. uvs: [],
  72782. hasUVIndices: false
  72783. },
  72784. materials: [],
  72785. smooth: true,
  72786. startMaterial: function startMaterial(name, libraries) {
  72787. var previous = this._finalize(false);
  72788. // New usemtl declaration overwrites an inherited material, except if faces were declared
  72789. // after the material, then it must be preserved for proper MultiMaterial continuation.
  72790. if (previous && (previous.inherited || previous.groupCount <= 0)) {
  72791. this.materials.splice(previous.index, 1);
  72792. }
  72793. var material = {
  72794. index: this.materials.length,
  72795. name: name || '',
  72796. mtllib: Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : '',
  72797. smooth: previous !== undefined ? previous.smooth : this.smooth,
  72798. groupStart: previous !== undefined ? previous.groupEnd : 0,
  72799. groupEnd: -1,
  72800. groupCount: -1,
  72801. inherited: false,
  72802. clone: function clone(index) {
  72803. var cloned = {
  72804. index: typeof index === 'number' ? index : this.index,
  72805. name: this.name,
  72806. mtllib: this.mtllib,
  72807. smooth: this.smooth,
  72808. groupStart: 0,
  72809. groupEnd: -1,
  72810. groupCount: -1,
  72811. inherited: false
  72812. };
  72813. cloned.clone = this.clone.bind(cloned);
  72814. return cloned;
  72815. }
  72816. };
  72817. this.materials.push(material);
  72818. return material;
  72819. },
  72820. currentMaterial: function currentMaterial() {
  72821. if (this.materials.length > 0) {
  72822. return this.materials[this.materials.length - 1];
  72823. }
  72824. return undefined;
  72825. },
  72826. _finalize: function _finalize(end) {
  72827. var lastMultiMaterial = this.currentMaterial();
  72828. if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {
  72829. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  72830. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  72831. lastMultiMaterial.inherited = false;
  72832. }
  72833. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  72834. if (end && this.materials.length > 1) {
  72835. for (var mi = this.materials.length - 1; mi >= 0; mi--) {
  72836. if (this.materials[mi].groupCount <= 0) {
  72837. this.materials.splice(mi, 1);
  72838. }
  72839. }
  72840. }
  72841. // Guarantee at least one empty material, this makes the creation later more straight forward.
  72842. if (end && this.materials.length === 0) {
  72843. this.materials.push({
  72844. name: '',
  72845. smooth: this.smooth
  72846. });
  72847. }
  72848. return lastMultiMaterial;
  72849. }
  72850. };
  72851. // Inherit previous objects material.
  72852. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  72853. // If a usemtl declaration is encountered while this new object is being parsed, it will
  72854. // overwrite the inherited material. Exception being that there was already face declarations
  72855. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  72856. if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function') {
  72857. var declared = previousMaterial.clone(0);
  72858. declared.inherited = true;
  72859. this.object.materials.push(declared);
  72860. }
  72861. this.objects.push(this.object);
  72862. },
  72863. finalize: function finalize() {
  72864. if (this.object && typeof this.object._finalize === 'function') {
  72865. this.object._finalize(true);
  72866. }
  72867. },
  72868. parseVertexIndex: function parseVertexIndex(value, len) {
  72869. var index = parseInt(value, 10);
  72870. return (index >= 0 ? index - 1 : index + len / 3) * 3;
  72871. },
  72872. parseNormalIndex: function parseNormalIndex(value, len) {
  72873. var index = parseInt(value, 10);
  72874. return (index >= 0 ? index - 1 : index + len / 3) * 3;
  72875. },
  72876. parseUVIndex: function parseUVIndex(value, len) {
  72877. var index = parseInt(value, 10);
  72878. return (index >= 0 ? index - 1 : index + len / 2) * 2;
  72879. },
  72880. addVertex: function addVertex(a, b, c) {
  72881. var src = this.vertices;
  72882. var dst = this.object.geometry.vertices;
  72883. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  72884. dst.push(src[b + 0], src[b + 1], src[b + 2]);
  72885. dst.push(src[c + 0], src[c + 1], src[c + 2]);
  72886. },
  72887. addVertexPoint: function addVertexPoint(a) {
  72888. var src = this.vertices;
  72889. var dst = this.object.geometry.vertices;
  72890. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  72891. },
  72892. addVertexLine: function addVertexLine(a) {
  72893. var src = this.vertices;
  72894. var dst = this.object.geometry.vertices;
  72895. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  72896. },
  72897. addNormal: function addNormal(a, b, c) {
  72898. var src = this.normals;
  72899. var dst = this.object.geometry.normals;
  72900. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  72901. dst.push(src[b + 0], src[b + 1], src[b + 2]);
  72902. dst.push(src[c + 0], src[c + 1], src[c + 2]);
  72903. },
  72904. addFaceNormal: function addFaceNormal(a, b, c) {
  72905. var src = this.vertices;
  72906. var dst = this.object.geometry.normals;
  72907. vA.fromArray(src, a);
  72908. vB.fromArray(src, b);
  72909. vC.fromArray(src, c);
  72910. cb.subVectors(vC, vB);
  72911. ab.subVectors(vA, vB);
  72912. cb.cross(ab);
  72913. cb.normalize();
  72914. dst.push(cb.x, cb.y, cb.z);
  72915. dst.push(cb.x, cb.y, cb.z);
  72916. dst.push(cb.x, cb.y, cb.z);
  72917. },
  72918. addColor: function addColor(a, b, c) {
  72919. var src = this.colors;
  72920. var dst = this.object.geometry.colors;
  72921. if (src[a] !== undefined) dst.push(src[a + 0], src[a + 1], src[a + 2]);
  72922. if (src[b] !== undefined) dst.push(src[b + 0], src[b + 1], src[b + 2]);
  72923. if (src[c] !== undefined) dst.push(src[c + 0], src[c + 1], src[c + 2]);
  72924. },
  72925. addUV: function addUV(a, b, c) {
  72926. var src = this.uvs;
  72927. var dst = this.object.geometry.uvs;
  72928. dst.push(src[a + 0], src[a + 1]);
  72929. dst.push(src[b + 0], src[b + 1]);
  72930. dst.push(src[c + 0], src[c + 1]);
  72931. },
  72932. addDefaultUV: function addDefaultUV() {
  72933. var dst = this.object.geometry.uvs;
  72934. dst.push(0, 0);
  72935. dst.push(0, 0);
  72936. dst.push(0, 0);
  72937. },
  72938. addUVLine: function addUVLine(a) {
  72939. var src = this.uvs;
  72940. var dst = this.object.geometry.uvs;
  72941. dst.push(src[a + 0], src[a + 1]);
  72942. },
  72943. addFace: function addFace(a, b, c, ua, ub, uc, na, nb, nc) {
  72944. var vLen = this.vertices.length;
  72945. var ia = this.parseVertexIndex(a, vLen);
  72946. var ib = this.parseVertexIndex(b, vLen);
  72947. var ic = this.parseVertexIndex(c, vLen);
  72948. this.addVertex(ia, ib, ic);
  72949. this.addColor(ia, ib, ic);
  72950. // normals
  72951. if (na !== undefined && na !== '') {
  72952. var nLen = this.normals.length;
  72953. ia = this.parseNormalIndex(na, nLen);
  72954. ib = this.parseNormalIndex(nb, nLen);
  72955. ic = this.parseNormalIndex(nc, nLen);
  72956. this.addNormal(ia, ib, ic);
  72957. } else {
  72958. this.addFaceNormal(ia, ib, ic);
  72959. }
  72960. // uvs
  72961. if (ua !== undefined && ua !== '') {
  72962. var uvLen = this.uvs.length;
  72963. ia = this.parseUVIndex(ua, uvLen);
  72964. ib = this.parseUVIndex(ub, uvLen);
  72965. ic = this.parseUVIndex(uc, uvLen);
  72966. this.addUV(ia, ib, ic);
  72967. this.object.geometry.hasUVIndices = true;
  72968. } else {
  72969. // add placeholder values (for inconsistent face definitions)
  72970. this.addDefaultUV();
  72971. }
  72972. },
  72973. addPointGeometry: function addPointGeometry(vertices) {
  72974. this.object.geometry.type = 'Points';
  72975. var vLen = this.vertices.length;
  72976. for (var vi = 0, l = vertices.length; vi < l; vi++) {
  72977. var index = this.parseVertexIndex(vertices[vi], vLen);
  72978. this.addVertexPoint(index);
  72979. this.addColor(index);
  72980. }
  72981. },
  72982. addLineGeometry: function addLineGeometry(vertices, uvs) {
  72983. this.object.geometry.type = 'Line';
  72984. var vLen = this.vertices.length;
  72985. var uvLen = this.uvs.length;
  72986. for (var vi = 0, l = vertices.length; vi < l; vi++) {
  72987. this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
  72988. }
  72989. for (var uvi = 0, l = uvs.length; uvi < l; uvi++) {
  72990. this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen));
  72991. }
  72992. }
  72993. };
  72994. state.startObject('', false);
  72995. return state;
  72996. }
  72997. //
  72998. function OBJLoader(manager) {
  72999. Loader.call(this, manager);
  73000. this.materials = null;
  73001. }
  73002. OBJLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  73003. constructor: OBJLoader,
  73004. load: function load(url, onLoad, onProgress, onError) {
  73005. var scope = this;
  73006. var loader = new FileLoader(this.manager);
  73007. loader.setPath(this.path);
  73008. loader.setRequestHeader(this.requestHeader);
  73009. loader.setWithCredentials(this.withCredentials);
  73010. loader.load(url, function (text, total) {
  73011. // xzw add total
  73012. try {
  73013. onLoad(scope.parse(text), total);
  73014. } catch (e) {
  73015. if (onError) {
  73016. onError(e);
  73017. } else {
  73018. console.error(e);
  73019. }
  73020. scope.manager.itemError(url);
  73021. }
  73022. }, onProgress, onError);
  73023. },
  73024. setMaterials: function setMaterials(materials) {
  73025. this.materials = materials;
  73026. return this;
  73027. },
  73028. parse: function parse(text) {
  73029. var state = new ParserState();
  73030. if (text.indexOf('\r\n') !== -1) {
  73031. // This is faster than String.split with regex that splits on both
  73032. text = text.replace(/\r\n/g, '\n');
  73033. }
  73034. if (text.indexOf('\\\n') !== -1) {
  73035. // join lines separated by a line continuation character (\)
  73036. text = text.replace(/\\\n/g, '');
  73037. }
  73038. var lines = text.split('\n');
  73039. var line = '',
  73040. lineFirstChar = '';
  73041. var lineLength = 0;
  73042. var result = [];
  73043. // Faster to just trim left side of the line. Use if available.
  73044. var trimLeft = typeof ''.trimLeft === 'function';
  73045. for (var i = 0, l = lines.length; i < l; i++) {
  73046. line = lines[i];
  73047. line = trimLeft ? line.trimLeft() : line.trim();
  73048. lineLength = line.length;
  73049. if (lineLength === 0) continue;
  73050. lineFirstChar = line.charAt(0);
  73051. // @todo invoke passed in handler if any
  73052. if (lineFirstChar === '#') continue;
  73053. if (lineFirstChar === 'v') {
  73054. var data = line.split(/\s+/);
  73055. switch (data[0]) {
  73056. case 'v':
  73057. state.vertices.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3]));
  73058. if (data.length >= 7) {
  73059. state.colors.push(parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6]));
  73060. } else {
  73061. // if no colors are defined, add placeholders so color and vertex indices match
  73062. state.colors.push(undefined, undefined, undefined);
  73063. }
  73064. break;
  73065. case 'vn':
  73066. state.normals.push(parseFloat(data[1]), parseFloat(data[2]), parseFloat(data[3]));
  73067. break;
  73068. case 'vt':
  73069. state.uvs.push(parseFloat(data[1]), parseFloat(data[2]));
  73070. break;
  73071. }
  73072. } else if (lineFirstChar === 'f') {
  73073. var lineData = line.substr(1).trim();
  73074. var vertexData = lineData.split(/\s+/);
  73075. var faceVertices = [];
  73076. // Parse the face vertex data into an easy to work with format
  73077. for (var j = 0, jl = vertexData.length; j < jl; j++) {
  73078. var vertex = vertexData[j];
  73079. if (vertex.length > 0) {
  73080. var vertexParts = vertex.split('/');
  73081. faceVertices.push(vertexParts);
  73082. }
  73083. }
  73084. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  73085. var v1 = faceVertices[0];
  73086. for (var j = 1, jl = faceVertices.length - 1; j < jl; j++) {
  73087. var v2 = faceVertices[j];
  73088. var v3 = faceVertices[j + 1];
  73089. state.addFace(v1[0], v2[0], v3[0], v1[1], v2[1], v3[1], v1[2], v2[2], v3[2]);
  73090. }
  73091. } else if (lineFirstChar === 'l') {
  73092. var lineParts = line.substring(1).trim().split(' ');
  73093. var lineVertices = [],
  73094. lineUVs = [];
  73095. if (line.indexOf('/') === -1) {
  73096. lineVertices = lineParts;
  73097. } else {
  73098. for (var li = 0, llen = lineParts.length; li < llen; li++) {
  73099. var parts = lineParts[li].split('/');
  73100. if (parts[0] !== '') lineVertices.push(parts[0]);
  73101. if (parts[1] !== '') lineUVs.push(parts[1]);
  73102. }
  73103. }
  73104. state.addLineGeometry(lineVertices, lineUVs);
  73105. } else if (lineFirstChar === 'p') {
  73106. var lineData = line.substr(1).trim();
  73107. var pointData = lineData.split(' ');
  73108. state.addPointGeometry(pointData);
  73109. } else if ((result = object_pattern.exec(line)) !== null) {
  73110. // o object_name
  73111. // or
  73112. // g group_name
  73113. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  73114. // var name = result[ 0 ].substr( 1 ).trim();
  73115. var name = (' ' + result[0].substr(1).trim()).substr(1);
  73116. state.startObject(name);
  73117. } else if (material_use_pattern.test(line)) {
  73118. // material
  73119. state.object.startMaterial(line.substring(7).trim(), state.materialLibraries);
  73120. } else if (material_library_pattern.test(line)) {
  73121. // mtl file
  73122. state.materialLibraries.push(line.substring(7).trim());
  73123. } else if (map_use_pattern.test(line)) {
  73124. // the line is parsed but ignored since the loader assumes textures are defined MTL files
  73125. // (according to https://www.okino.com/conv/imp_wave.htm, 'usemap' is the old-style Wavefront texture reference method)
  73126. console.warn('THREE.OBJLoader: Rendering identifier "usemap" not supported. Textures must be defined in MTL files.');
  73127. } else if (lineFirstChar === 's') {
  73128. result = line.split(' ');
  73129. // smooth shading
  73130. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  73131. // but does not define a usemtl for each face set.
  73132. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  73133. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  73134. // where explicit usemtl defines geometry groups.
  73135. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  73136. /*
  73137. * http://paulbourke.net/dataformats/obj/
  73138. * or
  73139. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  73140. *
  73141. * From chapter "Grouping" Syntax explanation "s group_number":
  73142. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  73143. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  73144. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  73145. * than 0."
  73146. */
  73147. if (result.length > 1) {
  73148. var value = result[1].trim().toLowerCase();
  73149. state.object.smooth = value !== '0' && value !== 'off';
  73150. } else {
  73151. // ZBrush can produce "s" lines #11707
  73152. state.object.smooth = true;
  73153. }
  73154. var material = state.object.currentMaterial();
  73155. if (material) material.smooth = state.object.smooth;
  73156. } else {
  73157. // Handle null terminated files without exception
  73158. if (line === '\0') continue;
  73159. console.warn('THREE.OBJLoader: Unexpected line: "' + line + '"');
  73160. }
  73161. }
  73162. state.finalize();
  73163. var container = new Group();
  73164. container.materialLibraries = [].concat(state.materialLibraries);
  73165. var hasPrimitives = !(state.objects.length === 1 && state.objects[0].geometry.vertices.length === 0);
  73166. if (hasPrimitives === true) {
  73167. for (var i = 0, l = state.objects.length; i < l; i++) {
  73168. var object = state.objects[i];
  73169. var geometry = object.geometry;
  73170. var materials = object.materials;
  73171. var isLine = geometry.type === 'Line';
  73172. var isPoints = geometry.type === 'Points';
  73173. var hasVertexColors = false;
  73174. // Skip o/g line declarations that did not follow with any faces
  73175. if (geometry.vertices.length === 0) continue;
  73176. var buffergeometry = new BufferGeometry();
  73177. buffergeometry.setAttribute('position', new Float32BufferAttribute(geometry.vertices, 3));
  73178. if (geometry.normals.length > 0) {
  73179. buffergeometry.setAttribute('normal', new Float32BufferAttribute(geometry.normals, 3));
  73180. }
  73181. if (geometry.colors.length > 0) {
  73182. hasVertexColors = true;
  73183. buffergeometry.setAttribute('color', new Float32BufferAttribute(geometry.colors, 3));
  73184. }
  73185. if (geometry.hasUVIndices === true) {
  73186. buffergeometry.setAttribute('uv', new Float32BufferAttribute(geometry.uvs, 2));
  73187. }
  73188. // Create materials
  73189. var createdMaterials = [];
  73190. for (var mi = 0, miLen = materials.length; mi < miLen; mi++) {
  73191. var sourceMaterial = materials[mi];
  73192. var materialHash = sourceMaterial.name + '_' + sourceMaterial.smooth + '_' + hasVertexColors;
  73193. var material = state.materials[materialHash];
  73194. if (this.materials !== null) {
  73195. material = this.materials.create(sourceMaterial.name);
  73196. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  73197. if (isLine && material && !(material instanceof LineBasicMaterial)) {
  73198. var materialLine = new LineBasicMaterial();
  73199. Material.prototype.copy.call(materialLine, material);
  73200. materialLine.color.copy(material.color);
  73201. material = materialLine;
  73202. } else if (isPoints && material && !(material instanceof PointsMaterial)) {
  73203. var materialPoints = new PointsMaterial({
  73204. size: 10,
  73205. sizeAttenuation: false
  73206. });
  73207. Material.prototype.copy.call(materialPoints, material);
  73208. materialPoints.color.copy(material.color);
  73209. materialPoints.map = material.map;
  73210. material = materialPoints;
  73211. }
  73212. }
  73213. if (material === undefined) {
  73214. if (isLine) {
  73215. material = new LineBasicMaterial();
  73216. } else if (isPoints) {
  73217. material = new PointsMaterial({
  73218. size: 1,
  73219. sizeAttenuation: false
  73220. });
  73221. } else {
  73222. material = new MeshPhongMaterial();
  73223. }
  73224. material.name = sourceMaterial.name;
  73225. material.flatShading = sourceMaterial.smooth ? false : true;
  73226. material.vertexColors = hasVertexColors;
  73227. state.materials[materialHash] = material;
  73228. }
  73229. createdMaterials.push(material);
  73230. }
  73231. // Create mesh
  73232. var mesh;
  73233. if (createdMaterials.length > 1) {
  73234. for (var mi = 0, miLen = materials.length; mi < miLen; mi++) {
  73235. var sourceMaterial = materials[mi];
  73236. buffergeometry.addGroup(sourceMaterial.groupStart, sourceMaterial.groupCount, mi);
  73237. }
  73238. if (isLine) {
  73239. mesh = new LineSegments(buffergeometry, createdMaterials);
  73240. } else if (isPoints) {
  73241. mesh = new Points(buffergeometry, createdMaterials);
  73242. } else {
  73243. mesh = new Mesh(buffergeometry, createdMaterials);
  73244. }
  73245. } else {
  73246. if (isLine) {
  73247. mesh = new LineSegments(buffergeometry, createdMaterials[0]);
  73248. } else if (isPoints) {
  73249. mesh = new Points(buffergeometry, createdMaterials[0]);
  73250. } else {
  73251. mesh = new Mesh(buffergeometry, createdMaterials[0]);
  73252. }
  73253. }
  73254. mesh.name = object.name;
  73255. container.add(mesh);
  73256. }
  73257. } else {
  73258. // if there is only the default parser state object with no geometry data, interpret data as point cloud
  73259. if (state.vertices.length > 0) {
  73260. var material = new PointsMaterial({
  73261. size: 1,
  73262. sizeAttenuation: false
  73263. });
  73264. var buffergeometry = new BufferGeometry();
  73265. buffergeometry.setAttribute('position', new Float32BufferAttribute(state.vertices, 3));
  73266. if (state.colors.length > 0 && state.colors[0] !== undefined) {
  73267. buffergeometry.setAttribute('color', new Float32BufferAttribute(state.colors, 3));
  73268. material.vertexColors = true;
  73269. }
  73270. var points = new Points(buffergeometry, material);
  73271. container.add(points);
  73272. }
  73273. }
  73274. return container;
  73275. }
  73276. });
  73277. return OBJLoader;
  73278. }();
  73279. /**
  73280. * Loads a Wavefront .mtl file specifying materials
  73281. */
  73282. var MTLLoader = function MTLLoader(manager) {
  73283. Loader.call(this, manager);
  73284. };
  73285. MTLLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  73286. constructor: MTLLoader,
  73287. /**
  73288. * Loads and parses a MTL asset from a URL.
  73289. *
  73290. * @param {String} url - URL to the MTL file.
  73291. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  73292. * @param {Function} [onProgress] - Callback for download progress.
  73293. * @param {Function} [onError] - Callback for download errors.
  73294. *
  73295. * @see setPath setResourcePath
  73296. *
  73297. * @note In order for relative texture references to resolve correctly
  73298. * you must call setResourcePath() explicitly prior to load.
  73299. */
  73300. load: function load(url, onLoad, onProgress, onError) {
  73301. var scope = this;
  73302. var path = this.path === '' ? LoaderUtils.extractUrlBase(url) : this.path;
  73303. var loader = new FileLoader(this.manager);
  73304. loader.setPath(this.path);
  73305. loader.setRequestHeader(this.requestHeader);
  73306. loader.setWithCredentials(this.withCredentials);
  73307. loader.load(url, function (text) {
  73308. try {
  73309. onLoad(scope.parse(text, path));
  73310. } catch (e) {
  73311. if (onError) {
  73312. onError(e);
  73313. } else {
  73314. console.error(e);
  73315. }
  73316. scope.manager.itemError(url);
  73317. }
  73318. }, onProgress, onError);
  73319. },
  73320. setMaterialOptions: function setMaterialOptions(value) {
  73321. this.materialOptions = value;
  73322. return this;
  73323. },
  73324. /**
  73325. * Parses a MTL file.
  73326. *
  73327. * @param {String} text - Content of MTL file
  73328. * @return {MTLLoader.MaterialCreator}
  73329. *
  73330. * @see setPath setResourcePath
  73331. *
  73332. * @note In order for relative texture references to resolve correctly
  73333. * you must call setResourcePath() explicitly prior to parse.
  73334. */
  73335. parse: function parse(text, path) {
  73336. var lines = text.split('\n');
  73337. var info = {};
  73338. var delimiter_pattern = /\s+/;
  73339. var materialsInfo = {};
  73340. for (var i = 0; i < lines.length; i++) {
  73341. var line = lines[i];
  73342. line = line.trim();
  73343. if (line.length === 0 || line.charAt(0) === '#') {
  73344. // Blank line or comment ignore
  73345. continue;
  73346. }
  73347. var pos = line.indexOf(' ');
  73348. var key = pos >= 0 ? line.substring(0, pos) : line;
  73349. key = key.toLowerCase();
  73350. var value = pos >= 0 ? line.substring(pos + 1) : '';
  73351. value = value.trim();
  73352. if (key === 'newmtl') {
  73353. // New material
  73354. info = {
  73355. name: value
  73356. };
  73357. materialsInfo[value] = info;
  73358. } else {
  73359. if (key === 'ka' || key === 'kd' || key === 'ks' || key === 'ke') {
  73360. var ss = value.split(delimiter_pattern, 3);
  73361. info[key] = [parseFloat(ss[0]), parseFloat(ss[1]), parseFloat(ss[2])];
  73362. } else {
  73363. info[key] = value;
  73364. }
  73365. }
  73366. }
  73367. var materialCreator = new MTLLoader.MaterialCreator(this.resourcePath || path, this.materialOptions);
  73368. materialCreator.setCrossOrigin(this.crossOrigin);
  73369. materialCreator.setManager(this.manager);
  73370. materialCreator.setMaterials(materialsInfo);
  73371. return materialCreator;
  73372. }
  73373. });
  73374. /**
  73375. * Create a new MTLLoader.MaterialCreator
  73376. * @param baseUrl - Url relative to which textures are loaded
  73377. * @param options - Set of options on how to construct the materials
  73378. * side: Which side to apply the material
  73379. * FrontSide (default), THREE.BackSide, THREE.DoubleSide
  73380. * wrap: What type of wrapping to apply for textures
  73381. * RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  73382. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  73383. * Default: false, assumed to be already normalized
  73384. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  73385. * Default: false
  73386. * @constructor
  73387. */
  73388. MTLLoader.MaterialCreator = function (baseUrl, options) {
  73389. this.baseUrl = baseUrl || '';
  73390. this.options = options;
  73391. this.materialsInfo = {};
  73392. this.materials = {};
  73393. this.materialsArray = [];
  73394. this.nameLookup = {};
  73395. this.side = this.options && this.options.side ? this.options.side : FrontSide;
  73396. this.wrap = this.options && this.options.wrap ? this.options.wrap : RepeatWrapping;
  73397. };
  73398. MTLLoader.MaterialCreator.prototype = {
  73399. constructor: MTLLoader.MaterialCreator,
  73400. crossOrigin: 'anonymous',
  73401. setCrossOrigin: function setCrossOrigin(value) {
  73402. this.crossOrigin = value;
  73403. return this;
  73404. },
  73405. setManager: function setManager(value) {
  73406. this.manager = value;
  73407. },
  73408. setMaterials: function setMaterials(materialsInfo) {
  73409. this.materialsInfo = this.convert(materialsInfo);
  73410. this.materials = {};
  73411. this.materialsArray = [];
  73412. this.nameLookup = {};
  73413. },
  73414. convert: function convert(materialsInfo) {
  73415. if (!this.options) return materialsInfo;
  73416. var converted = {};
  73417. for (var mn in materialsInfo) {
  73418. // Convert materials info into normalized form based on options
  73419. var mat = materialsInfo[mn];
  73420. var covmat = {};
  73421. converted[mn] = covmat;
  73422. for (var prop in mat) {
  73423. var save = true;
  73424. var value = mat[prop];
  73425. var lprop = prop.toLowerCase();
  73426. switch (lprop) {
  73427. case 'kd':
  73428. case 'ka':
  73429. case 'ks':
  73430. // Diffuse color (color under white light) using RGB values
  73431. if (this.options && this.options.normalizeRGB) {
  73432. value = [value[0] / 255, value[1] / 255, value[2] / 255];
  73433. }
  73434. if (this.options && this.options.ignoreZeroRGBs) {
  73435. if (value[0] === 0 && value[1] === 0 && value[2] === 0) {
  73436. // ignore
  73437. save = false;
  73438. }
  73439. }
  73440. break;
  73441. default:
  73442. break;
  73443. }
  73444. if (save) {
  73445. covmat[lprop] = value;
  73446. }
  73447. }
  73448. }
  73449. return converted;
  73450. },
  73451. preload: function preload() {
  73452. for (var mn in this.materialsInfo) {
  73453. this.create(mn);
  73454. }
  73455. },
  73456. getIndex: function getIndex(materialName) {
  73457. return this.nameLookup[materialName];
  73458. },
  73459. getAsArray: function getAsArray() {
  73460. var index = 0;
  73461. for (var mn in this.materialsInfo) {
  73462. this.materialsArray[index] = this.create(mn);
  73463. this.nameLookup[mn] = index;
  73464. index++;
  73465. }
  73466. return this.materialsArray;
  73467. },
  73468. create: function create(materialName) {
  73469. if (this.materials[materialName] === undefined) {
  73470. this.createMaterial_(materialName);
  73471. }
  73472. return this.materials[materialName];
  73473. },
  73474. createMaterial_: function createMaterial_(materialName) {
  73475. // Create material
  73476. var scope = this;
  73477. var mat = this.materialsInfo[materialName];
  73478. var params = {
  73479. name: materialName,
  73480. side: this.side
  73481. };
  73482. function resolveURL(baseUrl, url) {
  73483. if (typeof url !== 'string' || url === '') return '';
  73484. // Absolute URL
  73485. if (/^https?:\/\//i.test(url)) return url;
  73486. return baseUrl + url;
  73487. }
  73488. function setMapForType(mapType, value) {
  73489. if (params[mapType]) return; // Keep the first encountered texture
  73490. var texParams = scope.getTextureParams(value, params);
  73491. var map = scope.loadTexture(resolveURL(scope.baseUrl, texParams.url));
  73492. map.repeat.copy(texParams.scale);
  73493. map.offset.copy(texParams.offset);
  73494. map.wrapS = scope.wrap;
  73495. map.wrapT = scope.wrap;
  73496. params[mapType] = map;
  73497. }
  73498. for (var prop in mat) {
  73499. var value = mat[prop];
  73500. var n;
  73501. if (value === '') continue;
  73502. switch (prop.toLowerCase()) {
  73503. // Ns is material specular exponent
  73504. case 'kd':
  73505. // Diffuse color (color under white light) using RGB values
  73506. params.color = new Color().fromArray(value);
  73507. break;
  73508. case 'ks':
  73509. // Specular color (color when light is reflected from shiny surface) using RGB values
  73510. //params.specular = new Color().fromArray( value );
  73511. //console.log('specular',value)
  73512. break;
  73513. case 'ke':
  73514. // Emissive using RGB values
  73515. params.emissive = new Color().fromArray(value);
  73516. break;
  73517. case 'map_kd':
  73518. // Diffuse texture map
  73519. setMapForType('map', value);
  73520. break;
  73521. case 'map_ks':
  73522. // Specular map
  73523. setMapForType('specularMap', value);
  73524. break;
  73525. case 'map_ke':
  73526. // Emissive map
  73527. setMapForType('emissiveMap', value);
  73528. break;
  73529. case 'norm':
  73530. setMapForType('normalMap', value);
  73531. break;
  73532. case 'map_bump':
  73533. case 'bump':
  73534. // Bump texture map
  73535. setMapForType('bumpMap', value);
  73536. break;
  73537. case 'map_d':
  73538. // Alpha map
  73539. setMapForType('alphaMap', value);
  73540. params.transparent = true;
  73541. break;
  73542. case 'ns':
  73543. // The specular exponent (defines the focus of the specular highlight)
  73544. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  73545. //params.shininess = parseFloat( value );
  73546. //console.log('shininess',value)
  73547. break;
  73548. case 'd':
  73549. n = parseFloat(value);
  73550. if (n < 1) {
  73551. params.opacity = n;
  73552. params.transparent = true;
  73553. }
  73554. break;
  73555. case 'tr':
  73556. n = parseFloat(value);
  73557. if (this.options && this.options.invertTrProperty) n = 1 - n;
  73558. if (n > 0) {
  73559. params.opacity = 1 - n;
  73560. params.transparent = true;
  73561. }
  73562. break;
  73563. default:
  73564. break;
  73565. }
  73566. }
  73567. this.materials[materialName] = new MeshStandardMaterial(params); //MeshPhongMaterial( params );
  73568. return this.materials[materialName];
  73569. },
  73570. getTextureParams: function getTextureParams(value, matParams) {
  73571. var texParams = {
  73572. scale: new Vector2(1, 1),
  73573. offset: new Vector2(0, 0)
  73574. };
  73575. var items = value.split(/\s+/);
  73576. var pos;
  73577. pos = items.indexOf('-bm');
  73578. if (pos >= 0) {
  73579. matParams.bumpScale = parseFloat(items[pos + 1]);
  73580. items.splice(pos, 2);
  73581. }
  73582. pos = items.indexOf('-s');
  73583. if (pos >= 0) {
  73584. texParams.scale.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2]));
  73585. items.splice(pos, 4); // we expect 3 parameters here!
  73586. }
  73587. pos = items.indexOf('-o');
  73588. if (pos >= 0) {
  73589. texParams.offset.set(parseFloat(items[pos + 1]), parseFloat(items[pos + 2]));
  73590. items.splice(pos, 4); // we expect 3 parameters here!
  73591. }
  73592. texParams.url = items.join(' ').trim();
  73593. return texParams;
  73594. },
  73595. loadTexture: function loadTexture(url, mapping, onLoad, onProgress, onError) {
  73596. var texture;
  73597. var manager = this.manager !== undefined ? this.manager : DefaultLoadingManager;
  73598. var loader = manager.getHandler(url);
  73599. if (loader === null) {
  73600. loader = new TextureLoader(manager);
  73601. }
  73602. if (loader.setCrossOrigin) loader.setCrossOrigin(this.crossOrigin);
  73603. texture = loader.load(url, onLoad, onProgress, onError);
  73604. if (mapping !== undefined) texture.mapping = mapping;
  73605. return texture;
  73606. }
  73607. };
  73608. //2022.11.11 copyfrom : https://unpkg.com/three@0.146.0/examples/jsm/loaders/DRACOLoader.js
  73609. var _taskCache = new WeakMap();
  73610. class DRACOLoader extends Loader {
  73611. constructor(manager) {
  73612. super(manager);
  73613. this.decoderPath = '';
  73614. this.decoderConfig = {};
  73615. this.decoderBinary = null;
  73616. this.decoderPending = null;
  73617. this.workerLimit = 4;
  73618. this.workerPool = [];
  73619. this.workerNextTaskID = 1;
  73620. this.workerSourceURL = '';
  73621. this.defaultAttributeIDs = {
  73622. position: 'POSITION',
  73623. normal: 'NORMAL',
  73624. color: 'COLOR',
  73625. uv: 'TEX_COORD'
  73626. };
  73627. this.defaultAttributeTypes = {
  73628. position: 'Float32Array',
  73629. normal: 'Float32Array',
  73630. color: 'Float32Array',
  73631. uv: 'Float32Array'
  73632. };
  73633. }
  73634. setDecoderPath(path) {
  73635. this.decoderPath = path;
  73636. return this;
  73637. }
  73638. setDecoderConfig(config) {
  73639. this.decoderConfig = config;
  73640. return this;
  73641. }
  73642. setWorkerLimit(workerLimit) {
  73643. this.workerLimit = workerLimit;
  73644. return this;
  73645. }
  73646. load(url, onLoad, onProgress, onError) {
  73647. var loader = new FileLoader(this.manager);
  73648. loader.setPath(this.path);
  73649. loader.setResponseType('arraybuffer');
  73650. loader.setRequestHeader(this.requestHeader);
  73651. loader.setWithCredentials(this.withCredentials);
  73652. loader.load(url, buffer => {
  73653. this.decodeDracoFile(buffer, onLoad).catch(onError);
  73654. }, onProgress, onError);
  73655. }
  73656. decodeDracoFile(buffer, callback, attributeIDs, attributeTypes) {
  73657. var taskConfig = {
  73658. attributeIDs: attributeIDs || this.defaultAttributeIDs,
  73659. attributeTypes: attributeTypes || this.defaultAttributeTypes,
  73660. useUniqueIDs: !!attributeIDs
  73661. };
  73662. return this.decodeGeometry(buffer, taskConfig).then(callback);
  73663. }
  73664. decodeGeometry(buffer, taskConfig) {
  73665. var taskKey = JSON.stringify(taskConfig);
  73666. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  73667. // again from this thread.
  73668. if (_taskCache.has(buffer)) {
  73669. var cachedTask = _taskCache.get(buffer);
  73670. if (cachedTask.key === taskKey) {
  73671. return cachedTask.promise;
  73672. } else if (buffer.byteLength === 0) {
  73673. // Technically, it would be possible to wait for the previous task to complete,
  73674. // transfer the buffer back, and decode again with the second configuration. That
  73675. // is complex, and I don't know of any reason to decode a Draco buffer twice in
  73676. // different ways, so this is left unimplemented.
  73677. throw new Error('THREE.DRACOLoader: Unable to re-decode a buffer with different ' + 'settings. Buffer has already been transferred.');
  73678. }
  73679. }
  73680. //
  73681. var worker;
  73682. var taskID = this.workerNextTaskID++;
  73683. var taskCost = buffer.byteLength;
  73684. // Obtain a worker and assign a task, and construct a geometry instance
  73685. // when the task completes.
  73686. var geometryPending = this._getWorker(taskID, taskCost).then(_worker => {
  73687. worker = _worker;
  73688. return new Promise((resolve, reject) => {
  73689. worker._callbacks[taskID] = {
  73690. resolve,
  73691. reject
  73692. };
  73693. worker.postMessage({
  73694. type: 'decode',
  73695. id: taskID,
  73696. taskConfig,
  73697. buffer
  73698. }, [buffer]);
  73699. // this.debug();
  73700. });
  73701. }).then(message => this._createGeometry(message.geometry));
  73702. // Remove task from the task list.
  73703. // Note: replaced '.finally()' with '.catch().then()' block - iOS 11 support (#19416)
  73704. geometryPending.catch(() => true).then(() => {
  73705. if (worker && taskID) {
  73706. this._releaseTask(worker, taskID);
  73707. // this.debug();
  73708. }
  73709. });
  73710. // Cache the task result.
  73711. _taskCache.set(buffer, {
  73712. key: taskKey,
  73713. promise: geometryPending
  73714. });
  73715. return geometryPending;
  73716. }
  73717. _createGeometry(geometryData) {
  73718. var geometry = new BufferGeometry();
  73719. if (geometryData.index) {
  73720. geometry.setIndex(new BufferAttribute(geometryData.index.array, 1));
  73721. }
  73722. for (var i = 0; i < geometryData.attributes.length; i++) {
  73723. var attribute = geometryData.attributes[i];
  73724. var name = attribute.name;
  73725. var array = attribute.array;
  73726. var itemSize = attribute.itemSize;
  73727. geometry.setAttribute(name, new BufferAttribute(array, itemSize));
  73728. }
  73729. return geometry;
  73730. }
  73731. _loadLibrary(url, responseType) {
  73732. var loader = new FileLoader(this.manager);
  73733. loader.setPath(this.decoderPath);
  73734. loader.setResponseType(responseType);
  73735. loader.setWithCredentials(this.withCredentials);
  73736. return new Promise((resolve, reject) => {
  73737. loader.load(url, resolve, undefined, reject);
  73738. });
  73739. }
  73740. preload() {
  73741. this._initDecoder();
  73742. return this;
  73743. }
  73744. _initDecoder() {
  73745. if (this.decoderPending) return this.decoderPending;
  73746. var useJS = typeof WebAssembly !== 'object' || this.decoderConfig.type === 'js';
  73747. var librariesPending = [];
  73748. if (useJS) {
  73749. librariesPending.push(this._loadLibrary('draco_decoder.js', 'text'));
  73750. } else {
  73751. librariesPending.push(this._loadLibrary('draco_wasm_wrapper.js', 'text'));
  73752. librariesPending.push(this._loadLibrary('draco_decoder.wasm', 'arraybuffer'));
  73753. }
  73754. this.decoderPending = Promise.all(librariesPending).then(libraries => {
  73755. var jsContent = libraries[0];
  73756. if (!useJS) {
  73757. this.decoderConfig.wasmBinary = libraries[1];
  73758. }
  73759. var fn = DRACOWorker.toString();
  73760. var body = ['/* draco decoder */', jsContent, '', '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
  73761. this.workerSourceURL = URL.createObjectURL(new Blob([body]));
  73762. });
  73763. return this.decoderPending;
  73764. }
  73765. _getWorker(taskID, taskCost) {
  73766. return this._initDecoder().then(() => {
  73767. if (this.workerPool.length < this.workerLimit) {
  73768. var _worker2 = new Worker(this.workerSourceURL);
  73769. _worker2._callbacks = {};
  73770. _worker2._taskCosts = {};
  73771. _worker2._taskLoad = 0;
  73772. _worker2.postMessage({
  73773. type: 'init',
  73774. decoderConfig: this.decoderConfig
  73775. });
  73776. _worker2.onmessage = function (e) {
  73777. var message = e.data;
  73778. switch (message.type) {
  73779. case 'decode':
  73780. _worker2._callbacks[message.id].resolve(message);
  73781. break;
  73782. case 'error':
  73783. _worker2._callbacks[message.id].reject(message);
  73784. break;
  73785. default:
  73786. console.error('THREE.DRACOLoader: Unexpected message, "' + message.type + '"');
  73787. }
  73788. };
  73789. this.workerPool.push(_worker2);
  73790. } else {
  73791. this.workerPool.sort(function (a, b) {
  73792. return a._taskLoad > b._taskLoad ? -1 : 1;
  73793. });
  73794. }
  73795. var worker = this.workerPool[this.workerPool.length - 1];
  73796. worker._taskCosts[taskID] = taskCost;
  73797. worker._taskLoad += taskCost;
  73798. return worker;
  73799. });
  73800. }
  73801. _releaseTask(worker, taskID) {
  73802. worker._taskLoad -= worker._taskCosts[taskID];
  73803. delete worker._callbacks[taskID];
  73804. delete worker._taskCosts[taskID];
  73805. }
  73806. debug() {
  73807. console.log('Task load: ', this.workerPool.map(worker => worker._taskLoad));
  73808. }
  73809. dispose() {
  73810. for (var i = 0; i < this.workerPool.length; ++i) {
  73811. this.workerPool[i].terminate();
  73812. }
  73813. this.workerPool.length = 0;
  73814. return this;
  73815. }
  73816. }
  73817. /* WEB WORKER */
  73818. function DRACOWorker() {
  73819. var decoderConfig;
  73820. var decoderPending;
  73821. onmessage = function onmessage(e) {
  73822. var message = e.data;
  73823. switch (message.type) {
  73824. case 'init':
  73825. decoderConfig = message.decoderConfig;
  73826. decoderPending = new Promise(function (resolve /*, reject*/) {
  73827. decoderConfig.onModuleLoaded = function (draco) {
  73828. // Module is Promise-like. Wrap before resolving to avoid loop.
  73829. resolve({
  73830. draco: draco
  73831. });
  73832. };
  73833. DracoDecoderModule(decoderConfig); // eslint-disable-line no-undef
  73834. });
  73835. break;
  73836. case 'decode':
  73837. var buffer = message.buffer;
  73838. var taskConfig = message.taskConfig;
  73839. decoderPending.then(module => {
  73840. var draco = module.draco;
  73841. var decoder = new draco.Decoder();
  73842. var decoderBuffer = new draco.DecoderBuffer();
  73843. decoderBuffer.Init(new Int8Array(buffer), buffer.byteLength);
  73844. try {
  73845. var geometry = decodeGeometry(draco, decoder, decoderBuffer, taskConfig);
  73846. var buffers = geometry.attributes.map(attr => attr.array.buffer);
  73847. if (geometry.index) buffers.push(geometry.index.array.buffer);
  73848. self.postMessage({
  73849. type: 'decode',
  73850. id: message.id,
  73851. geometry
  73852. }, buffers);
  73853. } catch (error) {
  73854. console.error(error);
  73855. self.postMessage({
  73856. type: 'error',
  73857. id: message.id,
  73858. error: error.message
  73859. });
  73860. } finally {
  73861. draco.destroy(decoderBuffer);
  73862. draco.destroy(decoder);
  73863. }
  73864. });
  73865. break;
  73866. }
  73867. };
  73868. function decodeGeometry(draco, decoder, decoderBuffer, taskConfig) {
  73869. var attributeIDs = taskConfig.attributeIDs;
  73870. var attributeTypes = taskConfig.attributeTypes;
  73871. var dracoGeometry;
  73872. var decodingStatus;
  73873. var geometryType = decoder.GetEncodedGeometryType(decoderBuffer);
  73874. if (geometryType === draco.TRIANGULAR_MESH) {
  73875. dracoGeometry = new draco.Mesh();
  73876. decodingStatus = decoder.DecodeBufferToMesh(decoderBuffer, dracoGeometry);
  73877. } else if (geometryType === draco.POINT_CLOUD) {
  73878. dracoGeometry = new draco.PointCloud();
  73879. decodingStatus = decoder.DecodeBufferToPointCloud(decoderBuffer, dracoGeometry);
  73880. } else {
  73881. throw new Error('THREE.DRACOLoader: Unexpected geometry type.');
  73882. }
  73883. if (!decodingStatus.ok() || dracoGeometry.ptr === 0) {
  73884. throw new Error('THREE.DRACOLoader: Decoding failed: ' + decodingStatus.error_msg());
  73885. }
  73886. var geometry = {
  73887. index: null,
  73888. attributes: []
  73889. };
  73890. // Gather all vertex attributes.
  73891. for (var attributeName in attributeIDs) {
  73892. var attributeType = self[attributeTypes[attributeName]];
  73893. var attribute = void 0;
  73894. var attributeID = void 0;
  73895. // A Draco file may be created with default vertex attributes, whose attribute IDs
  73896. // are mapped 1:1 from their semantic name (POSITION, NORMAL, ...). Alternatively,
  73897. // a Draco file may contain a custom set of attributes, identified by known unique
  73898. // IDs. glTF files always do the latter, and `.drc` files typically do the former.
  73899. if (taskConfig.useUniqueIDs) {
  73900. attributeID = attributeIDs[attributeName];
  73901. attribute = decoder.GetAttributeByUniqueId(dracoGeometry, attributeID);
  73902. } else {
  73903. attributeID = decoder.GetAttributeId(dracoGeometry, draco[attributeIDs[attributeName]]);
  73904. if (attributeID === -1) continue;
  73905. attribute = decoder.GetAttribute(dracoGeometry, attributeID);
  73906. }
  73907. geometry.attributes.push(decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute));
  73908. }
  73909. // Add index.
  73910. if (geometryType === draco.TRIANGULAR_MESH) {
  73911. geometry.index = decodeIndex(draco, decoder, dracoGeometry);
  73912. }
  73913. draco.destroy(dracoGeometry);
  73914. return geometry;
  73915. }
  73916. function decodeIndex(draco, decoder, dracoGeometry) {
  73917. var numFaces = dracoGeometry.num_faces();
  73918. var numIndices = numFaces * 3;
  73919. var byteLength = numIndices * 4;
  73920. var ptr = draco._malloc(byteLength);
  73921. decoder.GetTrianglesUInt32Array(dracoGeometry, byteLength, ptr);
  73922. var index = new Uint32Array(draco.HEAPF32.buffer, ptr, numIndices).slice();
  73923. draco._free(ptr);
  73924. return {
  73925. array: index,
  73926. itemSize: 1
  73927. };
  73928. }
  73929. function decodeAttribute(draco, decoder, dracoGeometry, attributeName, attributeType, attribute) {
  73930. var numComponents = attribute.num_components();
  73931. var numPoints = dracoGeometry.num_points();
  73932. var numValues = numPoints * numComponents;
  73933. var byteLength = numValues * attributeType.BYTES_PER_ELEMENT;
  73934. var dataType = getDracoDataType(draco, attributeType);
  73935. var ptr = draco._malloc(byteLength);
  73936. decoder.GetAttributeDataArrayForAllPoints(dracoGeometry, attribute, dataType, byteLength, ptr);
  73937. var array = new attributeType(draco.HEAPF32.buffer, ptr, numValues).slice();
  73938. draco._free(ptr);
  73939. return {
  73940. name: attributeName,
  73941. array: array,
  73942. itemSize: numComponents
  73943. };
  73944. }
  73945. function getDracoDataType(draco, attributeType) {
  73946. switch (attributeType) {
  73947. case Float32Array:
  73948. return draco.DT_FLOAT32;
  73949. case Int8Array:
  73950. return draco.DT_INT8;
  73951. case Int16Array:
  73952. return draco.DT_INT16;
  73953. case Int32Array:
  73954. return draco.DT_INT32;
  73955. case Uint8Array:
  73956. return draco.DT_UINT8;
  73957. case Uint16Array:
  73958. return draco.DT_UINT16;
  73959. case Uint32Array:
  73960. return draco.DT_UINT32;
  73961. }
  73962. }
  73963. }
  73964. /**
  73965. * @author Deepkolos / https://github.com/deepkolos
  73966. */
  73967. //用于KTX2Loader
  73968. class WorkerPool$1 {
  73969. constructor() {
  73970. var pool = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 4;
  73971. this.pool = pool;
  73972. this.queue = [];
  73973. this.workers = [];
  73974. this.workersResolve = [];
  73975. this.workerStatus = 0;
  73976. }
  73977. _initWorker(workerId) {
  73978. if (!this.workers[workerId]) {
  73979. var worker = this.workerCreator();
  73980. worker.addEventListener('message', this._onMessage.bind(this, workerId));
  73981. this.workers[workerId] = worker;
  73982. }
  73983. }
  73984. _getIdleWorker() {
  73985. for (var i = 0; i < this.pool; i++) if (!(this.workerStatus & 1 << i)) return i;
  73986. return -1;
  73987. }
  73988. _onMessage(workerId, msg) {
  73989. var resolve = this.workersResolve[workerId];
  73990. resolve && resolve(msg);
  73991. if (this.queue.length) {
  73992. var {
  73993. resolve: _resolve,
  73994. msg: _msg,
  73995. transfer
  73996. } = this.queue.shift();
  73997. this.workersResolve[workerId] = _resolve;
  73998. this.workers[workerId].postMessage(_msg, transfer);
  73999. } else {
  74000. this.workerStatus ^= 1 << workerId;
  74001. }
  74002. }
  74003. setWorkerCreator(workerCreator) {
  74004. this.workerCreator = workerCreator;
  74005. }
  74006. setWorkerLimit(pool) {
  74007. this.pool = pool;
  74008. }
  74009. postMessage(msg, transfer) {
  74010. return new Promise(resolve => {
  74011. var workerId = this._getIdleWorker();
  74012. if (workerId !== -1) {
  74013. this._initWorker(workerId);
  74014. this.workerStatus |= 1 << workerId;
  74015. this.workersResolve[workerId] = resolve;
  74016. this.workers[workerId].postMessage(msg, transfer);
  74017. } else {
  74018. this.queue.push({
  74019. resolve,
  74020. msg,
  74021. transfer
  74022. });
  74023. }
  74024. });
  74025. }
  74026. dispose() {
  74027. this.workers.forEach(worker => worker.terminate());
  74028. this.workersResolve.length = 0;
  74029. this.workers.length = 0;
  74030. this.queue.length = 0;
  74031. this.workerStatus = 0;
  74032. }
  74033. }
  74034. var t = 0,
  74035. e$1 = 1,
  74036. n$1 = 2,
  74037. i$2 = 3,
  74038. s = 0,
  74039. a$1 = 0,
  74040. r = 2,
  74041. o$1 = 0,
  74042. l$1 = 1,
  74043. f = 160,
  74044. U$1 = 161,
  74045. c$2 = 162,
  74046. h$2 = 163,
  74047. _$1 = 0,
  74048. p = 1,
  74049. g = 0,
  74050. y = 1,
  74051. x$2 = 2,
  74052. u$2 = 3,
  74053. b$1 = 4,
  74054. d = 5,
  74055. m = 6,
  74056. w$2 = 7,
  74057. D = 8,
  74058. B = 9,
  74059. L = 10,
  74060. A = 11,
  74061. k = 12,
  74062. v = 13,
  74063. S$1 = 14,
  74064. I = 15,
  74065. O = 16,
  74066. T$1 = 17,
  74067. V = 18,
  74068. E = 0,
  74069. F = 1,
  74070. P = 2,
  74071. C = 3,
  74072. z = 4,
  74073. M$1 = 5,
  74074. W = 6,
  74075. N = 7,
  74076. H = 8,
  74077. K = 9,
  74078. X = 10,
  74079. j = 11,
  74080. R = 0,
  74081. Y = 1,
  74082. q = 2,
  74083. G = 13,
  74084. J = 14,
  74085. Q = 15,
  74086. Z = 128,
  74087. $$1 = 64,
  74088. tt = 32,
  74089. et = 16,
  74090. nt = 0,
  74091. it = 1,
  74092. st = 2,
  74093. at = 3,
  74094. rt = 4,
  74095. ot = 5,
  74096. lt = 6,
  74097. ft = 7,
  74098. Ut = 8,
  74099. ct = 9,
  74100. ht = 10,
  74101. _t = 13,
  74102. pt = 14,
  74103. gt = 15,
  74104. yt = 16,
  74105. xt = 17,
  74106. ut = 20,
  74107. bt = 21,
  74108. dt = 22,
  74109. mt = 23,
  74110. wt = 24,
  74111. Dt = 27,
  74112. Bt = 28,
  74113. Lt = 29,
  74114. At = 30,
  74115. kt = 31,
  74116. vt = 34,
  74117. St = 35,
  74118. It = 36,
  74119. Ot = 37,
  74120. Tt = 38,
  74121. Vt = 41,
  74122. Et = 42,
  74123. Ft = 43,
  74124. Pt = 44,
  74125. Ct = 45,
  74126. zt = 48,
  74127. Mt = 49,
  74128. Wt = 50,
  74129. Nt = 58,
  74130. Ht = 59,
  74131. Kt = 62,
  74132. Xt = 63,
  74133. jt = 64,
  74134. Rt = 65,
  74135. Yt = 68,
  74136. qt = 69,
  74137. Gt = 70,
  74138. Jt = 71,
  74139. Qt = 74,
  74140. Zt = 75,
  74141. $t = 76,
  74142. te = 77,
  74143. ee = 78,
  74144. ne = 81,
  74145. ie = 82,
  74146. se = 83,
  74147. ae = 84,
  74148. re = 85,
  74149. oe = 88,
  74150. le = 89,
  74151. fe = 90,
  74152. Ue = 91,
  74153. ce = 92,
  74154. he = 95,
  74155. _e = 96,
  74156. pe = 97,
  74157. ge = 98,
  74158. ye = 99,
  74159. xe = 100,
  74160. ue = 101,
  74161. be = 102,
  74162. de = 103,
  74163. me = 104,
  74164. we = 105,
  74165. De = 106,
  74166. Be = 107,
  74167. Le = 108,
  74168. Ae = 109,
  74169. ke = 110,
  74170. ve = 111,
  74171. Se = 112,
  74172. Ie = 113,
  74173. Oe = 114,
  74174. Te = 115,
  74175. Ve = 116,
  74176. Ee = 117,
  74177. Fe = 118,
  74178. Pe = 119,
  74179. Ce = 120,
  74180. ze = 121,
  74181. Me = 122,
  74182. We = 123,
  74183. Ne = 124,
  74184. He = 125,
  74185. Ke = 126,
  74186. Xe = 127,
  74187. je = 128,
  74188. Re = 129,
  74189. Ye = 130,
  74190. qe = 131,
  74191. Ge = 132,
  74192. Je = 133,
  74193. Qe = 134,
  74194. Ze = 135,
  74195. $e = 136,
  74196. tn = 137,
  74197. en = 138,
  74198. nn = 139,
  74199. sn = 140,
  74200. an = 141,
  74201. rn = 142,
  74202. on = 143,
  74203. ln = 144,
  74204. fn = 145,
  74205. Un = 146,
  74206. cn = 147,
  74207. hn = 148,
  74208. _n = 149,
  74209. pn = 150,
  74210. gn = 151,
  74211. yn = 152,
  74212. xn = 153,
  74213. un = 154,
  74214. bn = 155,
  74215. dn = 156,
  74216. mn = 157,
  74217. wn = 158,
  74218. Dn = 159,
  74219. Bn = 160,
  74220. Ln = 161,
  74221. An = 162,
  74222. kn = 163,
  74223. vn = 164,
  74224. Sn = 165,
  74225. In = 166,
  74226. On = 167,
  74227. Tn = 168,
  74228. Vn = 169,
  74229. En = 170,
  74230. Fn = 171,
  74231. Pn = 172,
  74232. Cn = 173,
  74233. zn = 174,
  74234. Mn = 175,
  74235. Wn = 176,
  74236. Nn = 177,
  74237. Hn = 178,
  74238. Kn = 179,
  74239. Xn = 180,
  74240. jn = 181,
  74241. Rn = 182,
  74242. Yn = 183,
  74243. qn = 184,
  74244. Gn = 1000156007,
  74245. Jn = 1000156008,
  74246. Qn = 1000156009,
  74247. Zn = 1000156010,
  74248. $n = 1000156011,
  74249. ti = 1000156017,
  74250. ei = 1000156018,
  74251. ni = 1000156019,
  74252. ii = 1000156020,
  74253. si = 1000156021,
  74254. ai = 1000054e3,
  74255. ri = 1000054001,
  74256. oi = 1000054002,
  74257. li = 1000054003,
  74258. fi = 1000054004,
  74259. Ui = 1000054005,
  74260. ci = 1000054006,
  74261. hi = 1000054007,
  74262. _i = 1000066e3,
  74263. pi = 1000066001,
  74264. gi = 1000066002,
  74265. yi = 1000066003,
  74266. xi = 1000066004,
  74267. ui = 1000066005,
  74268. bi = 1000066006,
  74269. di = 1000066007,
  74270. mi = 1000066008,
  74271. wi = 1000066009,
  74272. Di = 1000066010,
  74273. Bi = 1000066011,
  74274. Li = 1000066012,
  74275. Ai = 1000066013,
  74276. ki = 100034e4,
  74277. vi = 1000340001;
  74278. class Si {
  74279. constructor() {
  74280. this.vkFormat = 0, this.typeSize = 1, this.pixelWidth = 0, this.pixelHeight = 0, this.pixelDepth = 0, this.layerCount = 0, this.faceCount = 1, this.supercompressionScheme = 0, this.levels = [], this.dataFormatDescriptor = [{
  74281. vendorId: 0,
  74282. descriptorType: 0,
  74283. descriptorBlockSize: 0,
  74284. versionNumber: 2,
  74285. colorModel: 0,
  74286. colorPrimaries: 1,
  74287. transferFunction: 2,
  74288. flags: 0,
  74289. texelBlockDimension: [0, 0, 0, 0],
  74290. bytesPlane: [0, 0, 0, 0, 0, 0, 0, 0],
  74291. samples: []
  74292. }], this.keyValue = {}, this.globalData = null;
  74293. }
  74294. }
  74295. class Ii {
  74296. constructor(t, e, n, i) {
  74297. this._dataView = new DataView(t.buffer, t.byteOffset + e, n), this._littleEndian = i, this._offset = 0;
  74298. }
  74299. _nextUint8() {
  74300. var t = this._dataView.getUint8(this._offset);
  74301. return this._offset += 1, t;
  74302. }
  74303. _nextUint16() {
  74304. var t = this._dataView.getUint16(this._offset, this._littleEndian);
  74305. return this._offset += 2, t;
  74306. }
  74307. _nextUint32() {
  74308. var t = this._dataView.getUint32(this._offset, this._littleEndian);
  74309. return this._offset += 4, t;
  74310. }
  74311. _nextUint64() {
  74312. var t = this._dataView.getUint32(this._offset, this._littleEndian) + 2 ** 32 * this._dataView.getUint32(this._offset + 4, this._littleEndian);
  74313. return this._offset += 8, t;
  74314. }
  74315. _nextInt32() {
  74316. var t = this._dataView.getInt32(this._offset, this._littleEndian);
  74317. return this._offset += 4, t;
  74318. }
  74319. _skip(t) {
  74320. return this._offset += t, this;
  74321. }
  74322. _scan(t) {
  74323. var e = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  74324. var n = this._offset;
  74325. var i = 0;
  74326. for (; this._dataView.getUint8(this._offset) !== e && i < t;) i++, this._offset++;
  74327. return i < t && this._offset++, new Uint8Array(this._dataView.buffer, this._dataView.byteOffset + n, i);
  74328. }
  74329. }
  74330. var Oi = new Uint8Array([0]),
  74331. Ti = [171, 75, 84, 88, 32, 50, 48, 187, 13, 10, 26, 10];
  74332. function Vi(t) {
  74333. return "undefined" != typeof TextEncoder ? new TextEncoder().encode(t) : Buffer.from(t);
  74334. }
  74335. function Ei(t) {
  74336. return "undefined" != typeof TextDecoder ? new TextDecoder().decode(t) : Buffer.from(t).toString("utf8");
  74337. }
  74338. function Fi(t) {
  74339. var e = 0;
  74340. for (var _n2 of t) e += _n2.byteLength;
  74341. var n = new Uint8Array(e);
  74342. var i = 0;
  74343. for (var _e2 of t) n.set(new Uint8Array(_e2), i), i += _e2.byteLength;
  74344. return n;
  74345. }
  74346. function Pi(t) {
  74347. var e = new Uint8Array(t.buffer, t.byteOffset, Ti.length);
  74348. if (e[0] !== Ti[0] || e[1] !== Ti[1] || e[2] !== Ti[2] || e[3] !== Ti[3] || e[4] !== Ti[4] || e[5] !== Ti[5] || e[6] !== Ti[6] || e[7] !== Ti[7] || e[8] !== Ti[8] || e[9] !== Ti[9] || e[10] !== Ti[10] || e[11] !== Ti[11]) throw new Error("Missing KTX 2.0 identifier.");
  74349. var n = new Si(),
  74350. i = 17 * Uint32Array.BYTES_PER_ELEMENT,
  74351. s = new Ii(t, Ti.length, i, !0);
  74352. n.vkFormat = s._nextUint32(), n.typeSize = s._nextUint32(), n.pixelWidth = s._nextUint32(), n.pixelHeight = s._nextUint32(), n.pixelDepth = s._nextUint32(), n.layerCount = s._nextUint32(), n.faceCount = s._nextUint32();
  74353. var a = s._nextUint32();
  74354. n.supercompressionScheme = s._nextUint32();
  74355. var r = s._nextUint32(),
  74356. o = s._nextUint32(),
  74357. l = s._nextUint32(),
  74358. f = s._nextUint32(),
  74359. U = s._nextUint64(),
  74360. c = s._nextUint64(),
  74361. h = new Ii(t, Ti.length + i, 3 * a * 8, !0);
  74362. for (var _e3 = 0; _e3 < a; _e3++) n.levels.push({
  74363. levelData: new Uint8Array(t.buffer, t.byteOffset + h._nextUint64(), h._nextUint64()),
  74364. uncompressedByteLength: h._nextUint64()
  74365. });
  74366. var _ = new Ii(t, r, o, !0),
  74367. p = {
  74368. vendorId: _._skip(4)._nextUint16(),
  74369. descriptorType: _._nextUint16(),
  74370. versionNumber: _._nextUint16(),
  74371. descriptorBlockSize: _._nextUint16(),
  74372. colorModel: _._nextUint8(),
  74373. colorPrimaries: _._nextUint8(),
  74374. transferFunction: _._nextUint8(),
  74375. flags: _._nextUint8(),
  74376. texelBlockDimension: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()],
  74377. bytesPlane: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()],
  74378. samples: []
  74379. },
  74380. g = (p.descriptorBlockSize / 4 - 6) / 4;
  74381. for (var _t2 = 0; _t2 < g; _t2++) {
  74382. var _e4 = {
  74383. bitOffset: _._nextUint16(),
  74384. bitLength: _._nextUint8(),
  74385. channelType: _._nextUint8(),
  74386. samplePosition: [_._nextUint8(), _._nextUint8(), _._nextUint8(), _._nextUint8()],
  74387. sampleLower: -Infinity,
  74388. sampleUpper: Infinity
  74389. };
  74390. 64 & _e4.channelType ? (_e4.sampleLower = _._nextInt32(), _e4.sampleUpper = _._nextInt32()) : (_e4.sampleLower = _._nextUint32(), _e4.sampleUpper = _._nextUint32()), p.samples[_t2] = _e4;
  74391. }
  74392. n.dataFormatDescriptor.length = 0, n.dataFormatDescriptor.push(p);
  74393. var y = new Ii(t, l, f, !0);
  74394. for (; y._offset < f;) {
  74395. var _t3 = y._nextUint32(),
  74396. _e5 = y._scan(_t3),
  74397. _i2 = Ei(_e5),
  74398. _s = y._scan(_t3 - _e5.byteLength);
  74399. n.keyValue[_i2] = _i2.match(/^ktx/i) ? Ei(_s) : _s, y._offset % 4 && y._skip(4 - y._offset % 4);
  74400. }
  74401. if (c <= 0) return n;
  74402. var x = new Ii(t, U, c, !0),
  74403. u = x._nextUint16(),
  74404. b = x._nextUint16(),
  74405. d = x._nextUint32(),
  74406. m = x._nextUint32(),
  74407. w = x._nextUint32(),
  74408. D = x._nextUint32(),
  74409. B = [];
  74410. for (var _t4 = 0; _t4 < a; _t4++) B.push({
  74411. imageFlags: x._nextUint32(),
  74412. rgbSliceByteOffset: x._nextUint32(),
  74413. rgbSliceByteLength: x._nextUint32(),
  74414. alphaSliceByteOffset: x._nextUint32(),
  74415. alphaSliceByteLength: x._nextUint32()
  74416. });
  74417. var L = U + x._offset,
  74418. A = L + d,
  74419. k = A + m,
  74420. v = k + w,
  74421. S = new Uint8Array(t.buffer, t.byteOffset + L, d),
  74422. I = new Uint8Array(t.buffer, t.byteOffset + A, m),
  74423. O = new Uint8Array(t.buffer, t.byteOffset + k, w),
  74424. T = new Uint8Array(t.buffer, t.byteOffset + v, D);
  74425. return n.globalData = {
  74426. endpointCount: u,
  74427. selectorCount: b,
  74428. imageDescs: B,
  74429. endpointsData: S,
  74430. selectorsData: I,
  74431. tablesData: O,
  74432. extendedData: T
  74433. }, n;
  74434. }
  74435. function Ci() {
  74436. return (Ci = Object.assign || function (t) {
  74437. for (var e = 1; e < arguments.length; e++) {
  74438. var n = arguments[e];
  74439. for (var i in n) Object.prototype.hasOwnProperty.call(n, i) && (t[i] = n[i]);
  74440. }
  74441. return t;
  74442. }).apply(this, arguments);
  74443. }
  74444. var zi = {
  74445. keepWriter: !1
  74446. };
  74447. function Mi(t) {
  74448. var e = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  74449. e = Ci({}, zi, e);
  74450. var n = new ArrayBuffer(0);
  74451. if (t.globalData) {
  74452. var _e6 = new ArrayBuffer(20 + 5 * t.globalData.imageDescs.length * 4),
  74453. _i3 = new DataView(_e6);
  74454. _i3.setUint16(0, t.globalData.endpointCount, !0), _i3.setUint16(2, t.globalData.selectorCount, !0), _i3.setUint32(4, t.globalData.endpointsData.byteLength, !0), _i3.setUint32(8, t.globalData.selectorsData.byteLength, !0), _i3.setUint32(12, t.globalData.tablesData.byteLength, !0), _i3.setUint32(16, t.globalData.extendedData.byteLength, !0);
  74455. for (var _e7 = 0; _e7 < t.globalData.imageDescs.length; _e7++) {
  74456. var _n3 = t.globalData.imageDescs[_e7];
  74457. _i3.setUint32(20 + 5 * _e7 * 4 + 0, _n3.imageFlags, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 4, _n3.rgbSliceByteOffset, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 8, _n3.rgbSliceByteLength, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 12, _n3.alphaSliceByteOffset, !0), _i3.setUint32(20 + 5 * _e7 * 4 + 16, _n3.alphaSliceByteLength, !0);
  74458. }
  74459. n = Fi([_e6, t.globalData.endpointsData, t.globalData.selectorsData, t.globalData.tablesData, t.globalData.extendedData]);
  74460. }
  74461. var i = [];
  74462. var s = t.keyValue;
  74463. e.keepWriter || (s = Ci({}, t.keyValue, {
  74464. KTXwriter: "KTX-Parse v0.3.1"
  74465. }));
  74466. for (var _t5 in s) {
  74467. var _e8 = s[_t5],
  74468. _n4 = Vi(_t5),
  74469. _a = "string" == typeof _e8 ? Vi(_e8) : _e8,
  74470. _r = _n4.byteLength + 1 + _a.byteLength + 1,
  74471. _o = _r % 4 ? 4 - _r % 4 : 0;
  74472. i.push(Fi([new Uint32Array([_r]), _n4, Oi, _a, Oi, new Uint8Array(_o).fill(0)]));
  74473. }
  74474. var a = Fi(i);
  74475. if (1 !== t.dataFormatDescriptor.length || 0 !== t.dataFormatDescriptor[0].descriptorType) throw new Error("Only BASICFORMAT Data Format Descriptor output supported.");
  74476. var r = t.dataFormatDescriptor[0],
  74477. o = new ArrayBuffer(28 + 16 * r.samples.length),
  74478. l = new DataView(o),
  74479. f = 24 + 16 * r.samples.length;
  74480. if (l.setUint32(0, o.byteLength, !0), l.setUint16(4, r.vendorId, !0), l.setUint16(6, r.descriptorType, !0), l.setUint16(8, r.versionNumber, !0), l.setUint16(10, f, !0), l.setUint8(12, r.colorModel), l.setUint8(13, r.colorPrimaries), l.setUint8(14, r.transferFunction), l.setUint8(15, r.flags), !Array.isArray(r.texelBlockDimension)) throw new Error("texelBlockDimension is now an array. For dimensionality `d`, set `d - 1`.");
  74481. l.setUint8(16, r.texelBlockDimension[0]), l.setUint8(17, r.texelBlockDimension[1]), l.setUint8(18, r.texelBlockDimension[2]), l.setUint8(19, r.texelBlockDimension[3]);
  74482. for (var _t6 = 0; _t6 < 8; _t6++) l.setUint8(20 + _t6, r.bytesPlane[_t6]);
  74483. for (var _t7 = 0; _t7 < r.samples.length; _t7++) {
  74484. var _e9 = r.samples[_t7],
  74485. _n5 = 28 + 16 * _t7;
  74486. if (_e9.channelID) throw new Error("channelID has been renamed to channelType.");
  74487. l.setUint16(_n5 + 0, _e9.bitOffset, !0), l.setUint8(_n5 + 2, _e9.bitLength), l.setUint8(_n5 + 3, _e9.channelType), l.setUint8(_n5 + 4, _e9.samplePosition[0]), l.setUint8(_n5 + 5, _e9.samplePosition[1]), l.setUint8(_n5 + 6, _e9.samplePosition[2]), l.setUint8(_n5 + 7, _e9.samplePosition[3]), 64 & _e9.channelType ? (l.setInt32(_n5 + 8, _e9.sampleLower, !0), l.setInt32(_n5 + 12, _e9.sampleUpper, !0)) : (l.setUint32(_n5 + 8, _e9.sampleLower, !0), l.setUint32(_n5 + 12, _e9.sampleUpper, !0));
  74488. }
  74489. var U = Ti.length + 68 + 3 * t.levels.length * 8,
  74490. c = U + o.byteLength;
  74491. var h = n.byteLength > 0 ? c + a.byteLength : 0;
  74492. h % 8 && (h += 8 - h % 8);
  74493. var _ = [],
  74494. p = new DataView(new ArrayBuffer(3 * t.levels.length * 8));
  74495. var g = (h || c + a.byteLength) + n.byteLength;
  74496. for (var _e10 = 0; _e10 < t.levels.length; _e10++) {
  74497. var _n6 = t.levels[_e10];
  74498. _.push(_n6.levelData), p.setBigUint64(24 * _e10 + 0, BigInt(g), !0), p.setBigUint64(24 * _e10 + 8, BigInt(_n6.levelData.byteLength), !0), p.setBigUint64(24 * _e10 + 16, BigInt(_n6.uncompressedByteLength), !0), g += _n6.levelData.byteLength;
  74499. }
  74500. var y = new ArrayBuffer(68),
  74501. x = new DataView(y);
  74502. return x.setUint32(0, t.vkFormat, !0), x.setUint32(4, t.typeSize, !0), x.setUint32(8, t.pixelWidth, !0), x.setUint32(12, t.pixelHeight, !0), x.setUint32(16, t.pixelDepth, !0), x.setUint32(20, t.layerCount, !0), x.setUint32(24, t.faceCount, !0), x.setUint32(28, t.levels.length, !0), x.setUint32(32, t.supercompressionScheme, !0), x.setUint32(36, U, !0), x.setUint32(40, o.byteLength, !0), x.setUint32(44, c, !0), x.setUint32(48, a.byteLength, !0), x.setBigUint64(52, BigInt(n.byteLength > 0 ? h : 0), !0), x.setBigUint64(60, BigInt(n.byteLength), !0), new Uint8Array(Fi([new Uint8Array(Ti).buffer, y, p.buffer, o, a, h > 0 ? new ArrayBuffer(h - (c + a.byteLength)) : new ArrayBuffer(0), n, ..._]));
  74503. }
  74504. /**
  74505. * @author Don McCurdy / https://www.donmccurdy.com
  74506. */
  74507. var init, instance, heap;
  74508. var importObject = {
  74509. env: {
  74510. emscripten_notify_memory_growth: function emscripten_notify_memory_growth(index) {
  74511. heap = new Uint8Array(instance.exports.memory.buffer);
  74512. }
  74513. }
  74514. };
  74515. /**
  74516. * ZSTD (Zstandard) decoder.
  74517. *
  74518. * Compiled from https://github.com/facebook/zstd/tree/dev/contrib/single_file_libs, with the
  74519. * following steps:
  74520. *
  74521. * ```
  74522. * ./combine.sh -r ../../lib -o zstddeclib.c zstddeclib-in.c
  74523. * emcc zstddeclib.c -Oz -s EXPORTED_FUNCTIONS="['_ZSTD_decompress', '_ZSTD_findDecompressedSize', '_ZSTD_isError', '_malloc', '_free']" -s ALLOW_MEMORY_GROWTH=1 -s MALLOC=emmalloc -o zstddec.wasm
  74524. * base64 zstddec.wasm > zstddec.txt
  74525. * ```
  74526. *
  74527. * The base64 string written to `zstddec.txt` is embedded as the `wasm` variable at the bottom
  74528. * of this file. The rest of this file is written by hand, in order to avoid an additional JS
  74529. * wrapper generated by Emscripten.
  74530. */
  74531. class ZSTDDecoder {
  74532. init() {
  74533. if (!init) {
  74534. init = fetch('data:application/wasm;base64,' + wasm).then(response => response.arrayBuffer()).then(arrayBuffer => WebAssembly.instantiate(arrayBuffer, importObject)).then(result => {
  74535. instance = result.instance;
  74536. importObject.env.emscripten_notify_memory_growth(0); // initialize heap.
  74537. });
  74538. }
  74539. return init;
  74540. }
  74541. decode(array) {
  74542. var uncompressedSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  74543. // Write compressed data into WASM memory.
  74544. var compressedSize = array.byteLength;
  74545. var compressedPtr = instance.exports.malloc(compressedSize);
  74546. heap.set(array, compressedPtr);
  74547. // Decompress into WASM memory.
  74548. uncompressedSize = uncompressedSize || Number(instance.exports.ZSTD_findDecompressedSize(compressedPtr, compressedSize));
  74549. var uncompressedPtr = instance.exports.malloc(uncompressedSize);
  74550. var actualSize = instance.exports.ZSTD_decompress(uncompressedPtr, uncompressedSize, compressedPtr, compressedSize);
  74551. // Read decompressed data and free WASM memory.
  74552. var dec = heap.slice(uncompressedPtr, uncompressedPtr + actualSize);
  74553. instance.exports.free(compressedPtr);
  74554. instance.exports.free(uncompressedPtr);
  74555. return dec;
  74556. }
  74557. }
  74558. /**
  74559. * BSD License
  74560. *
  74561. * For Zstandard software
  74562. *
  74563. * Copyright (c) 2016-present, Yann Collet, Facebook, Inc. All rights reserved.
  74564. *
  74565. * Redistribution and use in source and binary forms, with or without modification,
  74566. * are permitted provided that the following conditions are met:
  74567. *
  74568. * * Redistributions of source code must retain the above copyright notice, this
  74569. * list of conditions and the following disclaimer.
  74570. *
  74571. * * Redistributions in binary form must reproduce the above copyright notice,
  74572. * this list of conditions and the following disclaimer in the documentation
  74573. * and/or other materials provided with the distribution.
  74574. *
  74575. * * Neither the name Facebook nor the names of its contributors may be used to
  74576. * endorse or promote products derived from this software without specific
  74577. * prior written permission.
  74578. *
  74579. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  74580. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  74581. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  74582. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  74583. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  74584. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  74585. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  74586. * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  74587. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  74588. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  74589. */
  74590. var wasm = 'AGFzbQEAAAABpQEVYAF/AX9gAn9/AGADf39/AX9gBX9/f39/AX9gAX8AYAJ/fwF/YAR/f39/AX9gA39/fwBgBn9/f39/fwF/YAd/f39/f39/AX9gAn9/AX5gAn5+AX5gAABgBX9/f39/AGAGf39/f39/AGAIf39/f39/f38AYAl/f39/f39/f38AYAABf2AIf39/f39/f38Bf2ANf39/f39/f39/f39/fwF/YAF/AX4CJwEDZW52H2Vtc2NyaXB0ZW5fbm90aWZ5X21lbW9yeV9ncm93dGgABANpaAEFAAAFAgEFCwACAQABAgIFBQcAAwABDgsBAQcAEhMHAAUBDAQEAAANBwQCAgYCBAgDAwMDBgEACQkHBgICAAYGAgQUBwYGAwIGAAMCAQgBBwUGCgoEEQAEBAEIAwgDBQgDEA8IAAcABAUBcAECAgUEAQCAAgYJAX8BQaCgwAILB2AHBm1lbW9yeQIABm1hbGxvYwAoBGZyZWUAJgxaU1REX2lzRXJyb3IAaBlaU1REX2ZpbmREZWNvbXByZXNzZWRTaXplAFQPWlNURF9kZWNvbXByZXNzAEoGX3N0YXJ0ACQJBwEAQQELASQKussBaA8AIAAgACgCBCABajYCBAsZACAAKAIAIAAoAgRBH3F0QQAgAWtBH3F2CwgAIABBiH9LC34BBH9BAyEBIAAoAgQiA0EgTQRAIAAoAggiASAAKAIQTwRAIAAQDQ8LIAAoAgwiAiABRgRAQQFBAiADQSBJGw8LIAAgASABIAJrIANBA3YiBCABIARrIAJJIgEbIgJrIgQ2AgggACADIAJBA3RrNgIEIAAgBCgAADYCAAsgAQsUAQF/IAAgARACIQIgACABEAEgAgv3AQECfyACRQRAIABCADcCACAAQQA2AhAgAEIANwIIQbh/DwsgACABNgIMIAAgAUEEajYCECACQQRPBEAgACABIAJqIgFBfGoiAzYCCCAAIAMoAAA2AgAgAUF/ai0AACIBBEAgAEEIIAEQFGs2AgQgAg8LIABBADYCBEF/DwsgACABNgIIIAAgAS0AACIDNgIAIAJBfmoiBEEBTQRAIARBAWtFBEAgACABLQACQRB0IANyIgM2AgALIAAgAS0AAUEIdCADajYCAAsgASACakF/ai0AACIBRQRAIABBADYCBEFsDwsgAEEoIAEQFCACQQN0ams2AgQgAgsWACAAIAEpAAA3AAAgACABKQAINwAICy8BAX8gAUECdEGgHWooAgAgACgCAEEgIAEgACgCBGprQR9xdnEhAiAAIAEQASACCyEAIAFCz9bTvtLHq9lCfiAAfEIfiUKHla+vmLbem55/fgsdAQF/IAAoAgggACgCDEYEfyAAKAIEQSBGBUEACwuCBAEDfyACQYDAAE8EQCAAIAEgAhBnIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAkEBSARAIAAhAgwBCyAAQQNxRQRAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADTw0BIAJBA3ENAAsLAkAgA0F8cSIEQcAASQ0AIAIgBEFAaiIFSw0AA0AgAiABKAIANgIAIAIgASgCBDYCBCACIAEoAgg2AgggAiABKAIMNgIMIAIgASgCEDYCECACIAEoAhQ2AhQgAiABKAIYNgIYIAIgASgCHDYCHCACIAEoAiA2AiAgAiABKAIkNgIkIAIgASgCKDYCKCACIAEoAiw2AiwgAiABKAIwNgIwIAIgASgCNDYCNCACIAEoAjg2AjggAiABKAI8NgI8IAFBQGshASACQUBrIgIgBU0NAAsLIAIgBE8NAQNAIAIgASgCADYCACABQQRqIQEgAkEEaiICIARJDQALDAELIANBBEkEQCAAIQIMAQsgA0F8aiIEIABJBEAgACECDAELIAAhAgNAIAIgAS0AADoAACACIAEtAAE6AAEgAiABLQACOgACIAIgAS0AAzoAAyABQQRqIQEgAkEEaiICIARNDQALCyACIANJBEADQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAiADRw0ACwsgAAsMACAAIAEpAAA3AAALQQECfyAAKAIIIgEgACgCEEkEQEEDDwsgACAAKAIEIgJBB3E2AgQgACABIAJBA3ZrIgE2AgggACABKAAANgIAQQALDAAgACABKAIANgAAC/cCAQJ/AkAgACABRg0AAkAgASACaiAASwRAIAAgAmoiBCABSw0BCyAAIAEgAhALDwsgACABc0EDcSEDAkACQCAAIAFJBEAgAwRAIAAhAwwDCyAAQQNxRQRAIAAhAwwCCyAAIQMDQCACRQ0EIAMgAS0AADoAACABQQFqIQEgAkF/aiECIANBAWoiA0EDcQ0ACwwBCwJAIAMNACAEQQNxBEADQCACRQ0FIAAgAkF/aiICaiIDIAEgAmotAAA6AAAgA0EDcQ0ACwsgAkEDTQ0AA0AgACACQXxqIgJqIAEgAmooAgA2AgAgAkEDSw0ACwsgAkUNAgNAIAAgAkF/aiICaiABIAJqLQAAOgAAIAINAAsMAgsgAkEDTQ0AIAIhBANAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIARBfGoiBEEDSw0ACyACQQNxIQILIAJFDQADQCADIAEtAAA6AAAgA0EBaiEDIAFBAWohASACQX9qIgINAAsLIAAL8wICAn8BfgJAIAJFDQAgACACaiIDQX9qIAE6AAAgACABOgAAIAJBA0kNACADQX5qIAE6AAAgACABOgABIANBfWogAToAACAAIAE6AAIgAkEHSQ0AIANBfGogAToAACAAIAE6AAMgAkEJSQ0AIABBACAAa0EDcSIEaiIDIAFB/wFxQYGChAhsIgE2AgAgAyACIARrQXxxIgRqIgJBfGogATYCACAEQQlJDQAgAyABNgIIIAMgATYCBCACQXhqIAE2AgAgAkF0aiABNgIAIARBGUkNACADIAE2AhggAyABNgIUIAMgATYCECADIAE2AgwgAkFwaiABNgIAIAJBbGogATYCACACQWhqIAE2AgAgAkFkaiABNgIAIAQgA0EEcUEYciIEayICQSBJDQAgAa0iBUIghiAFhCEFIAMgBGohAQNAIAEgBTcDGCABIAU3AxAgASAFNwMIIAEgBTcDACABQSBqIQEgAkFgaiICQR9LDQALCyAACy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAIajYCACADCy8BAn8gACgCBCAAKAIAQQJ0aiICLQACIQMgACACLwEAIAEgAi0AAxAFajYCACADCx8AIAAgASACKAIEEAg2AgAgARAEGiAAIAJBCGo2AgQLCAAgAGdBH3MLugUBDX8jAEEQayIKJAACfyAEQQNNBEAgCkEANgIMIApBDGogAyAEEAsaIAAgASACIApBDGpBBBAVIgBBbCAAEAMbIAAgACAESxsMAQsgAEEAIAEoAgBBAXRBAmoQECENQVQgAygAACIGQQ9xIgBBCksNABogAiAAQQVqNgIAIAMgBGoiAkF8aiEMIAJBeWohDiACQXtqIRAgAEEGaiELQQQhBSAGQQR2IQRBICAAdCIAQQFyIQkgASgCACEPQQAhAiADIQYCQANAIAlBAkggAiAPS3JFBEAgAiEHAkAgCARAA0AgBEH//wNxQf//A0YEQCAHQRhqIQcgBiAQSQR/IAZBAmoiBigAACAFdgUgBUEQaiEFIARBEHYLIQQMAQsLA0AgBEEDcSIIQQNGBEAgBUECaiEFIARBAnYhBCAHQQNqIQcMAQsLIAcgCGoiByAPSw0EIAVBAmohBQNAIAIgB0kEQCANIAJBAXRqQQA7AQAgAkEBaiECDAELCyAGIA5LQQAgBiAFQQN1aiIHIAxLG0UEQCAHKAAAIAVBB3EiBXYhBAwCCyAEQQJ2IQQLIAYhBwsCfyALQX9qIAQgAEF/anEiBiAAQQF0QX9qIgggCWsiEUkNABogBCAIcSIEQQAgESAEIABIG2shBiALCyEIIA0gAkEBdGogBkF/aiIEOwEAIAlBASAGayAEIAZBAUgbayEJA0AgCSAASARAIABBAXUhACALQX9qIQsMAQsLAn8gByAOS0EAIAcgBSAIaiIFQQN1aiIGIAxLG0UEQCAFQQdxDAELIAUgDCIGIAdrQQN0awshBSACQQFqIQIgBEUhCCAGKAAAIAVBH3F2IQQMAQsLQWwgCUEBRyAFQSBKcg0BGiABIAJBf2o2AgAgBiAFQQdqQQN1aiADawwBC0FQCyEAIApBEGokACAACwkAQQFBBSAAGwsMACAAIAEoAAA2AAALqgMBCn8jAEHwAGsiCiQAIAJBAWohDiAAQQhqIQtBgIAEIAVBf2p0QRB1IQxBACECQQEhBkEBIAV0IglBf2oiDyEIA0AgAiAORkUEQAJAIAEgAkEBdCINai8BACIHQf//A0YEQCALIAhBA3RqIAI2AgQgCEF/aiEIQQEhBwwBCyAGQQAgDCAHQRB0QRB1ShshBgsgCiANaiAHOwEAIAJBAWohAgwBCwsgACAFNgIEIAAgBjYCACAJQQN2IAlBAXZqQQNqIQxBACEAQQAhBkEAIQIDQCAGIA5GBEADQAJAIAAgCUYNACAKIAsgAEEDdGoiASgCBCIGQQF0aiICIAIvAQAiAkEBajsBACABIAUgAhAUayIIOgADIAEgAiAIQf8BcXQgCWs7AQAgASAEIAZBAnQiAmooAgA6AAIgASACIANqKAIANgIEIABBAWohAAwBCwsFIAEgBkEBdGouAQAhDUEAIQcDQCAHIA1ORQRAIAsgAkEDdGogBjYCBANAIAIgDGogD3EiAiAISw0ACyAHQQFqIQcMAQsLIAZBAWohBgwBCwsgCkHwAGokAAsjAEIAIAEQCSAAhUKHla+vmLbem55/fkLj3MqV/M7y9YV/fAsQACAAQn43AwggACABNgIACyQBAX8gAARAIAEoAgQiAgRAIAEoAgggACACEQEADwsgABAmCwsfACAAIAEgAi8BABAINgIAIAEQBBogACACQQRqNgIEC0oBAX9BoCAoAgAiASAAaiIAQX9MBEBBiCBBMDYCAEF/DwsCQCAAPwBBEHRNDQAgABBmDQBBiCBBMDYCAEF/DwtBoCAgADYCACABC9cBAQh/Qbp/IQoCQCACKAIEIgggAigCACIJaiIOIAEgAGtLDQBBbCEKIAkgBCADKAIAIgtrSw0AIAAgCWoiBCACKAIIIgxrIQ0gACABQWBqIg8gCyAJQQAQKSADIAkgC2o2AgACQAJAIAwgBCAFa00EQCANIQUMAQsgDCAEIAZrSw0CIAcgDSAFayIAaiIBIAhqIAdNBEAgBCABIAgQDxoMAgsgBCABQQAgAGsQDyEBIAIgACAIaiIINgIEIAEgAGshBAsgBCAPIAUgCEEBECkLIA4hCgsgCgubAgEBfyMAQYABayINJAAgDSADNgJ8AkAgAkEDSwRAQX8hCQwBCwJAAkACQAJAIAJBAWsOAwADAgELIAZFBEBBuH8hCQwEC0FsIQkgBS0AACICIANLDQMgACAHIAJBAnQiAmooAgAgAiAIaigCABA7IAEgADYCAEEBIQkMAwsgASAJNgIAQQAhCQwCCyAKRQRAQWwhCQwCC0EAIQkgC0UgDEEZSHINAUEIIAR0QQhqIQBBACECA0AgAiAATw0CIAJBQGshAgwAAAsAC0FsIQkgDSANQfwAaiANQfgAaiAFIAYQFSICEAMNACANKAJ4IgMgBEsNACAAIA0gDSgCfCAHIAggAxAYIAEgADYCACACIQkLIA1BgAFqJAAgCQsLACAAIAEgAhALGgsQACAALwAAIAAtAAJBEHRyCy8AAn9BuH8gAUEISQ0AGkFyIAAoAAQiAEF3Sw0AGkG4fyAAQQhqIgAgACABSxsLCwkAIAAgATsAAAsDAAELigYBBX8gACAAKAIAIgVBfnE2AgBBACAAIAVBAXZqQYQgKAIAIgQgAEYbIQECQAJAIAAoAgQiAkUNACACKAIAIgNBAXENACACQQhqIgUgA0EBdkF4aiIDQQggA0EISxtnQR9zQQJ0QYAfaiIDKAIARgRAIAMgAigCDDYCAAsgAigCCCIDBEAgAyACKAIMNgIECyACKAIMIgMEQCADIAIoAgg2AgALIAIgAigCACAAKAIAQX5xajYCAEGEICEAAkACQCABRQ0AIAEgAjYCBCABKAIAIgNBAXENASADQQF2QXhqIgNBCCADQQhLG2dBH3NBAnRBgB9qIgMoAgAgAUEIakYEQCADIAEoAgw2AgALIAEoAggiAwRAIAMgASgCDDYCBAsgASgCDCIDBEAgAyABKAIINgIAQYQgKAIAIQQLIAIgAigCACABKAIAQX5xajYCACABIARGDQAgASABKAIAQQF2akEEaiEACyAAIAI2AgALIAIoAgBBAXZBeGoiAEEIIABBCEsbZ0Efc0ECdEGAH2oiASgCACEAIAEgBTYCACACIAA2AgwgAkEANgIIIABFDQEgACAFNgIADwsCQCABRQ0AIAEoAgAiAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAigCACABQQhqRgRAIAIgASgCDDYCAAsgASgCCCICBEAgAiABKAIMNgIECyABKAIMIgIEQCACIAEoAgg2AgBBhCAoAgAhBAsgACAAKAIAIAEoAgBBfnFqIgI2AgACQCABIARHBEAgASABKAIAQQF2aiAANgIEIAAoAgAhAgwBC0GEICAANgIACyACQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgIoAgAhASACIABBCGoiAjYCACAAIAE2AgwgAEEANgIIIAFFDQEgASACNgIADwsgBUEBdkF4aiIBQQggAUEISxtnQR9zQQJ0QYAfaiICKAIAIQEgAiAAQQhqIgI2AgAgACABNgIMIABBADYCCCABRQ0AIAEgAjYCAAsLDgAgAARAIABBeGoQJQsLgAIBA38CQCAAQQ9qQXhxQYQgKAIAKAIAQQF2ayICEB1Bf0YNAAJAQYQgKAIAIgAoAgAiAUEBcQ0AIAFBAXZBeGoiAUEIIAFBCEsbZ0Efc0ECdEGAH2oiASgCACAAQQhqRgRAIAEgACgCDDYCAAsgACgCCCIBBEAgASAAKAIMNgIECyAAKAIMIgFFDQAgASAAKAIINgIAC0EBIQEgACAAKAIAIAJBAXRqIgI2AgAgAkEBcQ0AIAJBAXZBeGoiAkEIIAJBCEsbZ0Efc0ECdEGAH2oiAygCACECIAMgAEEIaiIDNgIAIAAgAjYCDCAAQQA2AgggAkUNACACIAM2AgALIAELtwIBA38CQAJAIABBASAAGyICEDgiAA0AAkACQEGEICgCACIARQ0AIAAoAgAiA0EBcQ0AIAAgA0EBcjYCACADQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgAgAEEIakYEQCABIAAoAgw2AgALIAAoAggiAQRAIAEgACgCDDYCBAsgACgCDCIBBEAgASAAKAIINgIACyACECchAkEAIQFBhCAoAgAhACACDQEgACAAKAIAQX5xNgIAQQAPCyACQQ9qQXhxIgMQHSICQX9GDQIgAkEHakF4cSIAIAJHBEAgACACaxAdQX9GDQMLAkBBhCAoAgAiAUUEQEGAICAANgIADAELIAAgATYCBAtBhCAgADYCACAAIANBAXRBAXI2AgAMAQsgAEUNAQsgAEEIaiEBCyABC7kDAQJ/IAAgA2ohBQJAIANBB0wEQANAIAAgBU8NAiAAIAItAAA6AAAgAEEBaiEAIAJBAWohAgwAAAsACyAEQQFGBEACQCAAIAJrIgZBB00EQCAAIAItAAA6AAAgACACLQABOgABIAAgAi0AAjoAAiAAIAItAAM6AAMgAEEEaiACIAZBAnQiBkHAHmooAgBqIgIQFyACIAZB4B5qKAIAayECDAELIAAgAhAMCyACQQhqIQIgAEEIaiEACwJAAkACQAJAIAUgAU0EQCAAIANqIQEgBEEBRyAAIAJrQQ9Kcg0BA0AgACACEAwgAkEIaiECIABBCGoiACABSQ0ACwwFCyAAIAFLBEAgACEBDAQLIARBAUcgACACa0EPSnINASAAIQMgAiEEA0AgAyAEEAwgBEEIaiEEIANBCGoiAyABSQ0ACwwCCwNAIAAgAhAHIAJBEGohAiAAQRBqIgAgAUkNAAsMAwsgACEDIAIhBANAIAMgBBAHIARBEGohBCADQRBqIgMgAUkNAAsLIAIgASAAa2ohAgsDQCABIAVPDQEgASACLQAAOgAAIAFBAWohASACQQFqIQIMAAALAAsLQQECfyAAIAAoArjgASIDNgLE4AEgACgCvOABIQQgACABNgK84AEgACABIAJqNgK44AEgACABIAQgA2tqNgLA4AELpgEBAX8gACAAKALs4QEQFjYCyOABIABCADcD+OABIABCADcDuOABIABBwOABakIANwMAIABBqNAAaiIBQYyAgOAANgIAIABBADYCmOIBIABCADcDiOEBIABCAzcDgOEBIABBrNABakHgEikCADcCACAAQbTQAWpB6BIoAgA2AgAgACABNgIMIAAgAEGYIGo2AgggACAAQaAwajYCBCAAIABBEGo2AgALYQEBf0G4fyEDAkAgAUEDSQ0AIAIgABAhIgFBA3YiADYCCCACIAFBAXE2AgQgAiABQQF2QQNxIgM2AgACQCADQX9qIgFBAksNAAJAIAFBAWsOAgEAAgtBbA8LIAAhAwsgAwsMACAAIAEgAkEAEC4LiAQCA38CfiADEBYhBCAAQQBBKBAQIQAgBCACSwRAIAQPCyABRQRAQX8PCwJAAkAgA0EBRg0AIAEoAAAiBkGo6r5pRg0AQXYhAyAGQXBxQdDUtMIBRw0BQQghAyACQQhJDQEgAEEAQSgQECEAIAEoAAQhASAAQQE2AhQgACABrTcDAEEADwsgASACIAMQLyIDIAJLDQAgACADNgIYQXIhAyABIARqIgVBf2otAAAiAkEIcQ0AIAJBIHEiBkUEQEFwIQMgBS0AACIFQacBSw0BIAVBB3GtQgEgBUEDdkEKaq2GIgdCA4h+IAd8IQggBEEBaiEECyACQQZ2IQMgAkECdiEFAkAgAkEDcUF/aiICQQJLBEBBACECDAELAkACQAJAIAJBAWsOAgECAAsgASAEai0AACECIARBAWohBAwCCyABIARqLwAAIQIgBEECaiEEDAELIAEgBGooAAAhAiAEQQRqIQQLIAVBAXEhBQJ+AkACQAJAIANBf2oiA0ECTQRAIANBAWsOAgIDAQtCfyAGRQ0DGiABIARqMQAADAMLIAEgBGovAACtQoACfAwCCyABIARqKAAArQwBCyABIARqKQAACyEHIAAgBTYCICAAIAI2AhwgACAHNwMAQQAhAyAAQQA2AhQgACAHIAggBhsiBzcDCCAAIAdCgIAIIAdCgIAIVBs+AhALIAMLWwEBf0G4fyEDIAIQFiICIAFNBH8gACACakF/ai0AACIAQQNxQQJ0QaAeaigCACACaiAAQQZ2IgFBAnRBsB5qKAIAaiAAQSBxIgBFaiABRSAAQQV2cWoFQbh/CwsdACAAKAKQ4gEQWiAAQQA2AqDiASAAQgA3A5DiAQu1AwEFfyMAQZACayIKJABBuH8hBgJAIAVFDQAgBCwAACIIQf8BcSEHAkAgCEF/TARAIAdBgn9qQQF2IgggBU8NAkFsIQYgB0GBf2oiBUGAAk8NAiAEQQFqIQdBACEGA0AgBiAFTwRAIAUhBiAIIQcMAwUgACAGaiAHIAZBAXZqIgQtAABBBHY6AAAgACAGQQFyaiAELQAAQQ9xOgAAIAZBAmohBgwBCwAACwALIAcgBU8NASAAIARBAWogByAKEFMiBhADDQELIAYhBEEAIQYgAUEAQTQQECEJQQAhBQNAIAQgBkcEQCAAIAZqIggtAAAiAUELSwRAQWwhBgwDBSAJIAFBAnRqIgEgASgCAEEBajYCACAGQQFqIQZBASAILQAAdEEBdSAFaiEFDAILAAsLQWwhBiAFRQ0AIAUQFEEBaiIBQQxLDQAgAyABNgIAQQFBASABdCAFayIDEBQiAXQgA0cNACAAIARqIAFBAWoiADoAACAJIABBAnRqIgAgACgCAEEBajYCACAJKAIEIgBBAkkgAEEBcXINACACIARBAWo2AgAgB0EBaiEGCyAKQZACaiQAIAYLxhEBDH8jAEHwAGsiBSQAQWwhCwJAIANBCkkNACACLwAAIQogAi8AAiEJIAIvAAQhByAFQQhqIAQQDgJAIAMgByAJIApqakEGaiIMSQ0AIAUtAAohCCAFQdgAaiACQQZqIgIgChAGIgsQAw0BIAVBQGsgAiAKaiICIAkQBiILEAMNASAFQShqIAIgCWoiAiAHEAYiCxADDQEgBUEQaiACIAdqIAMgDGsQBiILEAMNASAAIAFqIg9BfWohECAEQQRqIQZBASELIAAgAUEDakECdiIDaiIMIANqIgIgA2oiDiEDIAIhBCAMIQcDQCALIAMgEElxBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgCS0AAyELIAcgBiAFQUBrIAgQAkECdGoiCS8BADsAACAFQUBrIAktAAIQASAJLQADIQogBCAGIAVBKGogCBACQQJ0aiIJLwEAOwAAIAVBKGogCS0AAhABIAktAAMhCSADIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgDS0AAyENIAAgC2oiCyAGIAVB2ABqIAgQAkECdGoiAC8BADsAACAFQdgAaiAALQACEAEgAC0AAyEAIAcgCmoiCiAGIAVBQGsgCBACQQJ0aiIHLwEAOwAAIAVBQGsgBy0AAhABIActAAMhByAEIAlqIgkgBiAFQShqIAgQAkECdGoiBC8BADsAACAFQShqIAQtAAIQASAELQADIQQgAyANaiIDIAYgBUEQaiAIEAJBAnRqIg0vAQA7AAAgBUEQaiANLQACEAEgACALaiEAIAcgCmohByAEIAlqIQQgAyANLQADaiEDIAVB2ABqEA0gBUFAaxANciAFQShqEA1yIAVBEGoQDXJFIQsMAQsLIAQgDksgByACS3INAEFsIQsgACAMSw0BIAxBfWohCQNAQQAgACAJSSAFQdgAahAEGwRAIAAgBiAFQdgAaiAIEAJBAnRqIgovAQA7AAAgBUHYAGogCi0AAhABIAAgCi0AA2oiACAGIAVB2ABqIAgQAkECdGoiCi8BADsAACAFQdgAaiAKLQACEAEgACAKLQADaiEADAEFIAxBfmohCgNAIAVB2ABqEAQgACAKS3JFBEAgACAGIAVB2ABqIAgQAkECdGoiCS8BADsAACAFQdgAaiAJLQACEAEgACAJLQADaiEADAELCwNAIAAgCk0EQCAAIAYgBUHYAGogCBACQQJ0aiIJLwEAOwAAIAVB2ABqIAktAAIQASAAIAktAANqIQAMAQsLAkAgACAMTw0AIAAgBiAFQdgAaiAIEAIiAEECdGoiDC0AADoAACAMLQADQQFGBEAgBUHYAGogDC0AAhABDAELIAUoAlxBH0sNACAFQdgAaiAGIABBAnRqLQACEAEgBSgCXEEhSQ0AIAVBIDYCXAsgAkF9aiEMA0BBACAHIAxJIAVBQGsQBBsEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiIAIAYgBUFAayAIEAJBAnRqIgcvAQA7AAAgBUFAayAHLQACEAEgACAHLQADaiEHDAEFIAJBfmohDANAIAVBQGsQBCAHIAxLckUEQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwNAIAcgDE0EQCAHIAYgBUFAayAIEAJBAnRqIgAvAQA7AAAgBUFAayAALQACEAEgByAALQADaiEHDAELCwJAIAcgAk8NACAHIAYgBUFAayAIEAIiAEECdGoiAi0AADoAACACLQADQQFGBEAgBUFAayACLQACEAEMAQsgBSgCREEfSw0AIAVBQGsgBiAAQQJ0ai0AAhABIAUoAkRBIUkNACAFQSA2AkQLIA5BfWohAgNAQQAgBCACSSAFQShqEAQbBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2oiACAGIAVBKGogCBACQQJ0aiIELwEAOwAAIAVBKGogBC0AAhABIAAgBC0AA2ohBAwBBSAOQX5qIQIDQCAFQShqEAQgBCACS3JFBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsDQCAEIAJNBEAgBCAGIAVBKGogCBACQQJ0aiIALwEAOwAAIAVBKGogAC0AAhABIAQgAC0AA2ohBAwBCwsCQCAEIA5PDQAgBCAGIAVBKGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBKGogAi0AAhABDAELIAUoAixBH0sNACAFQShqIAYgAEECdGotAAIQASAFKAIsQSFJDQAgBUEgNgIsCwNAQQAgAyAQSSAFQRBqEAQbBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2oiACAGIAVBEGogCBACQQJ0aiICLwEAOwAAIAVBEGogAi0AAhABIAAgAi0AA2ohAwwBBSAPQX5qIQIDQCAFQRBqEAQgAyACS3JFBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsDQCADIAJNBEAgAyAGIAVBEGogCBACQQJ0aiIALwEAOwAAIAVBEGogAC0AAhABIAMgAC0AA2ohAwwBCwsCQCADIA9PDQAgAyAGIAVBEGogCBACIgBBAnRqIgItAAA6AAAgAi0AA0EBRgRAIAVBEGogAi0AAhABDAELIAUoAhRBH0sNACAFQRBqIAYgAEECdGotAAIQASAFKAIUQSFJDQAgBUEgNgIUCyABQWwgBUHYAGoQCiAFQUBrEApxIAVBKGoQCnEgBUEQahAKcRshCwwJCwAACwALAAALAAsAAAsACwAACwALQWwhCwsgBUHwAGokACALC7UEAQ5/IwBBEGsiBiQAIAZBBGogABAOQVQhBQJAIARB3AtJDQAgBi0ABCEHIANB8ARqQQBB7AAQECEIIAdBDEsNACADQdwJaiIJIAggBkEIaiAGQQxqIAEgAhAxIhAQA0UEQCAGKAIMIgQgB0sNASADQdwFaiEPIANBpAVqIREgAEEEaiESIANBqAVqIQEgBCEFA0AgBSICQX9qIQUgCCACQQJ0aigCAEUNAAsgAkEBaiEOQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgASALaiAKNgIAIAVBAWohBSAKIAxqIQoMAQsLIAEgCjYCAEEAIQUgBigCCCELA0AgBSALRkUEQCABIAUgCWotAAAiDEECdGoiDSANKAIAIg1BAWo2AgAgDyANQQF0aiINIAw6AAEgDSAFOgAAIAVBAWohBQwBCwtBACEBIANBADYCqAUgBEF/cyAHaiEJQQEhBQNAIAUgDk9FBEAgCCAFQQJ0IgtqKAIAIQwgAyALaiABNgIAIAwgBSAJanQgAWohASAFQQFqIQUMAQsLIAcgBEEBaiIBIAJrIgRrQQFqIQgDQEEBIQUgBCAIT0UEQANAIAUgDk9FBEAgBUECdCIJIAMgBEE0bGpqIAMgCWooAgAgBHY2AgAgBUEBaiEFDAELCyAEQQFqIQQMAQsLIBIgByAPIAogESADIAIgARBkIAZBAToABSAGIAc6AAYgACAGKAIENgIACyAQIQULIAZBEGokACAFC8ENAQt/IwBB8ABrIgUkAEFsIQkCQCADQQpJDQAgAi8AACEKIAIvAAIhDCACLwAEIQYgBUEIaiAEEA4CQCADIAYgCiAMampBBmoiDUkNACAFLQAKIQcgBUHYAGogAkEGaiICIAoQBiIJEAMNASAFQUBrIAIgCmoiAiAMEAYiCRADDQEgBUEoaiACIAxqIgIgBhAGIgkQAw0BIAVBEGogAiAGaiADIA1rEAYiCRADDQEgACABaiIOQX1qIQ8gBEEEaiEGQQEhCSAAIAFBA2pBAnYiAmoiCiACaiIMIAJqIg0hAyAMIQQgCiECA0AgCSADIA9JcQRAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAACAGIAVBQGsgBxACQQF0aiIILQAAIQsgBUFAayAILQABEAEgAiALOgAAIAYgBUEoaiAHEAJBAXRqIggtAAAhCyAFQShqIAgtAAEQASAEIAs6AAAgBiAFQRBqIAcQAkEBdGoiCC0AACELIAVBEGogCC0AARABIAMgCzoAACAGIAVB2ABqIAcQAkEBdGoiCC0AACELIAVB2ABqIAgtAAEQASAAIAs6AAEgBiAFQUBrIAcQAkEBdGoiCC0AACELIAVBQGsgCC0AARABIAIgCzoAASAGIAVBKGogBxACQQF0aiIILQAAIQsgBUEoaiAILQABEAEgBCALOgABIAYgBUEQaiAHEAJBAXRqIggtAAAhCyAFQRBqIAgtAAEQASADIAs6AAEgA0ECaiEDIARBAmohBCACQQJqIQIgAEECaiEAIAkgBUHYAGoQDUVxIAVBQGsQDUVxIAVBKGoQDUVxIAVBEGoQDUVxIQkMAQsLIAQgDUsgAiAMS3INAEFsIQkgACAKSw0BIApBfWohCQNAIAVB2ABqEAQgACAJT3JFBEAgBiAFQdgAaiAHEAJBAXRqIggtAAAhCyAFQdgAaiAILQABEAEgACALOgAAIAYgBUHYAGogBxACQQF0aiIILQAAIQsgBUHYAGogCC0AARABIAAgCzoAASAAQQJqIQAMAQsLA0AgBUHYAGoQBCAAIApPckUEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCwNAIAAgCkkEQCAGIAVB2ABqIAcQAkEBdGoiCS0AACEIIAVB2ABqIAktAAEQASAAIAg6AAAgAEEBaiEADAELCyAMQX1qIQADQCAFQUBrEAQgAiAAT3JFBEAgBiAFQUBrIAcQAkEBdGoiCi0AACEJIAVBQGsgCi0AARABIAIgCToAACAGIAVBQGsgBxACQQF0aiIKLQAAIQkgBUFAayAKLQABEAEgAiAJOgABIAJBAmohAgwBCwsDQCAFQUBrEAQgAiAMT3JFBEAgBiAFQUBrIAcQAkEBdGoiAC0AACEKIAVBQGsgAC0AARABIAIgCjoAACACQQFqIQIMAQsLA0AgAiAMSQRAIAYgBUFAayAHEAJBAXRqIgAtAAAhCiAFQUBrIAAtAAEQASACIAo6AAAgAkEBaiECDAELCyANQX1qIQADQCAFQShqEAQgBCAAT3JFBEAgBiAFQShqIAcQAkEBdGoiAi0AACEKIAVBKGogAi0AARABIAQgCjoAACAGIAVBKGogBxACQQF0aiICLQAAIQogBUEoaiACLQABEAEgBCAKOgABIARBAmohBAwBCwsDQCAFQShqEAQgBCANT3JFBEAgBiAFQShqIAcQAkEBdGoiAC0AACECIAVBKGogAC0AARABIAQgAjoAACAEQQFqIQQMAQsLA0AgBCANSQRAIAYgBUEoaiAHEAJBAXRqIgAtAAAhAiAFQShqIAAtAAEQASAEIAI6AAAgBEEBaiEEDAELCwNAIAVBEGoQBCADIA9PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIAYgBUEQaiAHEAJBAXRqIgAtAAAhAiAFQRBqIAAtAAEQASADIAI6AAEgA0ECaiEDDAELCwNAIAVBEGoQBCADIA5PckUEQCAGIAVBEGogBxACQQF0aiIALQAAIQIgBUEQaiAALQABEAEgAyACOgAAIANBAWohAwwBCwsDQCADIA5JBEAgBiAFQRBqIAcQAkEBdGoiAC0AACECIAVBEGogAC0AARABIAMgAjoAACADQQFqIQMMAQsLIAFBbCAFQdgAahAKIAVBQGsQCnEgBUEoahAKcSAFQRBqEApxGyEJDAELQWwhCQsgBUHwAGokACAJC8oCAQR/IwBBIGsiBSQAIAUgBBAOIAUtAAIhByAFQQhqIAIgAxAGIgIQA0UEQCAEQQRqIQIgACABaiIDQX1qIQQDQCAFQQhqEAQgACAET3JFBEAgAiAFQQhqIAcQAkEBdGoiBi0AACEIIAVBCGogBi0AARABIAAgCDoAACACIAVBCGogBxACQQF0aiIGLQAAIQggBUEIaiAGLQABEAEgACAIOgABIABBAmohAAwBCwsDQCAFQQhqEAQgACADT3JFBEAgAiAFQQhqIAcQAkEBdGoiBC0AACEGIAVBCGogBC0AARABIAAgBjoAACAAQQFqIQAMAQsLA0AgACADT0UEQCACIAVBCGogBxACQQF0aiIELQAAIQYgBUEIaiAELQABEAEgACAGOgAAIABBAWohAAwBCwsgAUFsIAVBCGoQChshAgsgBUEgaiQAIAILtgMBCX8jAEEQayIGJAAgBkEANgIMIAZBADYCCEFUIQQCQAJAIANBQGsiDCADIAZBCGogBkEMaiABIAIQMSICEAMNACAGQQRqIAAQDiAGKAIMIgcgBi0ABEEBaksNASAAQQRqIQogBkEAOgAFIAYgBzoABiAAIAYoAgQ2AgAgB0EBaiEJQQEhBANAIAQgCUkEQCADIARBAnRqIgEoAgAhACABIAU2AgAgACAEQX9qdCAFaiEFIARBAWohBAwBCwsgB0EBaiEHQQAhBSAGKAIIIQkDQCAFIAlGDQEgAyAFIAxqLQAAIgRBAnRqIgBBASAEdEEBdSILIAAoAgAiAWoiADYCACAHIARrIQhBACEEAkAgC0EDTQRAA0AgBCALRg0CIAogASAEakEBdGoiACAIOgABIAAgBToAACAEQQFqIQQMAAALAAsDQCABIABPDQEgCiABQQF0aiIEIAg6AAEgBCAFOgAAIAQgCDoAAyAEIAU6AAIgBCAIOgAFIAQgBToABCAEIAg6AAcgBCAFOgAGIAFBBGohAQwAAAsACyAFQQFqIQUMAAALAAsgAiEECyAGQRBqJAAgBAutAQECfwJAQYQgKAIAIABHIAAoAgBBAXYiAyABa0F4aiICQXhxQQhHcgR/IAIFIAMQJ0UNASACQQhqC0EQSQ0AIAAgACgCACICQQFxIAAgAWpBD2pBeHEiASAAa0EBdHI2AgAgASAANgIEIAEgASgCAEEBcSAAIAJBAXZqIAFrIgJBAXRyNgIAQYQgIAEgAkH/////B3FqQQRqQYQgKAIAIABGGyABNgIAIAEQJQsLygIBBX8CQAJAAkAgAEEIIABBCEsbZ0EfcyAAaUEBR2oiAUEESSAAIAF2cg0AIAFBAnRB/B5qKAIAIgJFDQADQCACQXhqIgMoAgBBAXZBeGoiBSAATwRAIAIgBUEIIAVBCEsbZ0Efc0ECdEGAH2oiASgCAEYEQCABIAIoAgQ2AgALDAMLIARBHksNASAEQQFqIQQgAigCBCICDQALC0EAIQMgAUEgTw0BA0AgAUECdEGAH2ooAgAiAkUEQCABQR5LIQIgAUEBaiEBIAJFDQEMAwsLIAIgAkF4aiIDKAIAQQF2QXhqIgFBCCABQQhLG2dBH3NBAnRBgB9qIgEoAgBGBEAgASACKAIENgIACwsgAigCACIBBEAgASACKAIENgIECyACKAIEIgEEQCABIAIoAgA2AgALIAMgAygCAEEBcjYCACADIAAQNwsgAwvhCwINfwV+IwBB8ABrIgckACAHIAAoAvDhASIINgJcIAEgAmohDSAIIAAoAoDiAWohDwJAAkAgBUUEQCABIQQMAQsgACgCxOABIRAgACgCwOABIREgACgCvOABIQ4gAEEBNgKM4QFBACEIA0AgCEEDRwRAIAcgCEECdCICaiAAIAJqQazQAWooAgA2AkQgCEEBaiEIDAELC0FsIQwgB0EYaiADIAQQBhADDQEgB0EsaiAHQRhqIAAoAgAQEyAHQTRqIAdBGGogACgCCBATIAdBPGogB0EYaiAAKAIEEBMgDUFgaiESIAEhBEEAIQwDQCAHKAIwIAcoAixBA3RqKQIAIhRCEIinQf8BcSEIIAcoAkAgBygCPEEDdGopAgAiFUIQiKdB/wFxIQsgBygCOCAHKAI0QQN0aikCACIWQiCIpyEJIBVCIIghFyAUQiCIpyECAkAgFkIQiKdB/wFxIgNBAk8EQAJAIAZFIANBGUlyRQRAIAkgB0EYaiADQSAgBygCHGsiCiAKIANLGyIKEAUgAyAKayIDdGohCSAHQRhqEAQaIANFDQEgB0EYaiADEAUgCWohCQwBCyAHQRhqIAMQBSAJaiEJIAdBGGoQBBoLIAcpAkQhGCAHIAk2AkQgByAYNwNIDAELAkAgA0UEQCACBEAgBygCRCEJDAMLIAcoAkghCQwBCwJAAkAgB0EYakEBEAUgCSACRWpqIgNBA0YEQCAHKAJEQX9qIgMgA0VqIQkMAQsgA0ECdCAHaigCRCIJIAlFaiEJIANBAUYNAQsgByAHKAJINgJMCwsgByAHKAJENgJIIAcgCTYCRAsgF6chAyALBEAgB0EYaiALEAUgA2ohAwsgCCALakEUTwRAIAdBGGoQBBoLIAgEQCAHQRhqIAgQBSACaiECCyAHQRhqEAQaIAcgB0EYaiAUQhiIp0H/AXEQCCAUp0H//wNxajYCLCAHIAdBGGogFUIYiKdB/wFxEAggFadB//8DcWo2AjwgB0EYahAEGiAHIAdBGGogFkIYiKdB/wFxEAggFqdB//8DcWo2AjQgByACNgJgIAcoAlwhCiAHIAk2AmggByADNgJkAkACQAJAIAQgAiADaiILaiASSw0AIAIgCmoiEyAPSw0AIA0gBGsgC0Egak8NAQsgByAHKQNoNwMQIAcgBykDYDcDCCAEIA0gB0EIaiAHQdwAaiAPIA4gESAQEB4hCwwBCyACIARqIQggBCAKEAcgAkERTwRAIARBEGohAgNAIAIgCkEQaiIKEAcgAkEQaiICIAhJDQALCyAIIAlrIQIgByATNgJcIAkgCCAOa0sEQCAJIAggEWtLBEBBbCELDAILIBAgAiAOayICaiIKIANqIBBNBEAgCCAKIAMQDxoMAgsgCCAKQQAgAmsQDyEIIAcgAiADaiIDNgJkIAggAmshCCAOIQILIAlBEE8EQCADIAhqIQMDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALDAELAkAgCUEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgCUECdCIDQcAeaigCAGoiAhAXIAIgA0HgHmooAgBrIQIgBygCZCEDDAELIAggAhAMCyADQQlJDQAgAyAIaiEDIAhBCGoiCCACQQhqIgJrQQ9MBEADQCAIIAIQDCACQQhqIQIgCEEIaiIIIANJDQAMAgALAAsDQCAIIAIQByACQRBqIQIgCEEQaiIIIANJDQALCyAHQRhqEAQaIAsgDCALEAMiAhshDCAEIAQgC2ogAhshBCAFQX9qIgUNAAsgDBADDQFBbCEMIAdBGGoQBEECSQ0BQQAhCANAIAhBA0cEQCAAIAhBAnQiAmpBrNABaiACIAdqKAJENgIAIAhBAWohCAwBCwsgBygCXCEIC0G6fyEMIA8gCGsiACANIARrSw0AIAQEfyAEIAggABALIABqBUEACyABayEMCyAHQfAAaiQAIAwLkRcCFn8FfiMAQdABayIHJAAgByAAKALw4QEiCDYCvAEgASACaiESIAggACgCgOIBaiETAkACQCAFRQRAIAEhAwwBCyAAKALE4AEhESAAKALA4AEhFSAAKAK84AEhDyAAQQE2AozhAUEAIQgDQCAIQQNHBEAgByAIQQJ0IgJqIAAgAmpBrNABaigCADYCVCAIQQFqIQgMAQsLIAcgETYCZCAHIA82AmAgByABIA9rNgJoQWwhECAHQShqIAMgBBAGEAMNASAFQQQgBUEESBshFyAHQTxqIAdBKGogACgCABATIAdBxABqIAdBKGogACgCCBATIAdBzABqIAdBKGogACgCBBATQQAhBCAHQeAAaiEMIAdB5ABqIQoDQCAHQShqEARBAksgBCAXTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEJIAcoAkggBygCREEDdGopAgAiH0IgiKchCCAeQiCIISAgHUIgiKchAgJAIB9CEIinQf8BcSIDQQJPBEACQCAGRSADQRlJckUEQCAIIAdBKGogA0EgIAcoAixrIg0gDSADSxsiDRAFIAMgDWsiA3RqIQggB0EoahAEGiADRQ0BIAdBKGogAxAFIAhqIQgMAQsgB0EoaiADEAUgCGohCCAHQShqEAQaCyAHKQJUISEgByAINgJUIAcgITcDWAwBCwJAIANFBEAgAgRAIAcoAlQhCAwDCyAHKAJYIQgMAQsCQAJAIAdBKGpBARAFIAggAkVqaiIDQQNGBEAgBygCVEF/aiIDIANFaiEIDAELIANBAnQgB2ooAlQiCCAIRWohCCADQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAg2AlQLICCnIQMgCQRAIAdBKGogCRAFIANqIQMLIAkgC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgAmohAgsgB0EoahAEGiAHIAcoAmggAmoiCSADajYCaCAKIAwgCCAJSxsoAgAhDSAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogB0EoaiAfQhiIp0H/AXEQCCEOIAdB8ABqIARBBHRqIgsgCSANaiAIazYCDCALIAg2AgggCyADNgIEIAsgAjYCACAHIA4gH6dB//8DcWo2AkQgBEEBaiEEDAELCyAEIBdIDQEgEkFgaiEYIAdB4ABqIRogB0HkAGohGyABIQMDQCAHQShqEARBAksgBCAFTnJFBEAgBygCQCAHKAI8QQN0aikCACIdQhCIp0H/AXEhCyAHKAJQIAcoAkxBA3RqKQIAIh5CEIinQf8BcSEIIAcoAkggBygCREEDdGopAgAiH0IgiKchCSAeQiCIISAgHUIgiKchDAJAIB9CEIinQf8BcSICQQJPBEACQCAGRSACQRlJckUEQCAJIAdBKGogAkEgIAcoAixrIgogCiACSxsiChAFIAIgCmsiAnRqIQkgB0EoahAEGiACRQ0BIAdBKGogAhAFIAlqIQkMAQsgB0EoaiACEAUgCWohCSAHQShqEAQaCyAHKQJUISEgByAJNgJUIAcgITcDWAwBCwJAIAJFBEAgDARAIAcoAlQhCQwDCyAHKAJYIQkMAQsCQAJAIAdBKGpBARAFIAkgDEVqaiICQQNGBEAgBygCVEF/aiICIAJFaiEJDAELIAJBAnQgB2ooAlQiCSAJRWohCSACQQFGDQELIAcgBygCWDYCXAsLIAcgBygCVDYCWCAHIAk2AlQLICCnIRQgCARAIAdBKGogCBAFIBRqIRQLIAggC2pBFE8EQCAHQShqEAQaCyALBEAgB0EoaiALEAUgDGohDAsgB0EoahAEGiAHIAcoAmggDGoiGSAUajYCaCAbIBogCSAZSxsoAgAhHCAHIAdBKGogHUIYiKdB/wFxEAggHadB//8DcWo2AjwgByAHQShqIB5CGIinQf8BcRAIIB6nQf//A3FqNgJMIAdBKGoQBBogByAHQShqIB9CGIinQf8BcRAIIB+nQf//A3FqNgJEIAcgB0HwAGogBEEDcUEEdGoiDSkDCCIdNwPIASAHIA0pAwAiHjcDwAECQAJAAkAgBygCvAEiDiAepyICaiIWIBNLDQAgAyAHKALEASIKIAJqIgtqIBhLDQAgEiADayALQSBqTw0BCyAHIAcpA8gBNwMQIAcgBykDwAE3AwggAyASIAdBCGogB0G8AWogEyAPIBUgERAeIQsMAQsgAiADaiEIIAMgDhAHIAJBEU8EQCADQRBqIQIDQCACIA5BEGoiDhAHIAJBEGoiAiAISQ0ACwsgCCAdpyIOayECIAcgFjYCvAEgDiAIIA9rSwRAIA4gCCAVa0sEQEFsIQsMAgsgESACIA9rIgJqIhYgCmogEU0EQCAIIBYgChAPGgwCCyAIIBZBACACaxAPIQggByACIApqIgo2AsQBIAggAmshCCAPIQILIA5BEE8EQCAIIApqIQoDQCAIIAIQByACQRBqIQIgCEEQaiIIIApJDQALDAELAkAgDkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgDkECdCIKQcAeaigCAGoiAhAXIAIgCkHgHmooAgBrIQIgBygCxAEhCgwBCyAIIAIQDAsgCkEJSQ0AIAggCmohCiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAKSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAKSQ0ACwsgCxADBEAgCyEQDAQFIA0gDDYCACANIBkgHGogCWs2AgwgDSAJNgIIIA0gFDYCBCAEQQFqIQQgAyALaiEDDAILAAsLIAQgBUgNASAEIBdrIQtBACEEA0AgCyAFSARAIAcgB0HwAGogC0EDcUEEdGoiAikDCCIdNwPIASAHIAIpAwAiHjcDwAECQAJAAkAgBygCvAEiDCAepyICaiIKIBNLDQAgAyAHKALEASIJIAJqIhBqIBhLDQAgEiADayAQQSBqTw0BCyAHIAcpA8gBNwMgIAcgBykDwAE3AxggAyASIAdBGGogB0G8AWogEyAPIBUgERAeIRAMAQsgAiADaiEIIAMgDBAHIAJBEU8EQCADQRBqIQIDQCACIAxBEGoiDBAHIAJBEGoiAiAISQ0ACwsgCCAdpyIGayECIAcgCjYCvAEgBiAIIA9rSwRAIAYgCCAVa0sEQEFsIRAMAgsgESACIA9rIgJqIgwgCWogEU0EQCAIIAwgCRAPGgwCCyAIIAxBACACaxAPIQggByACIAlqIgk2AsQBIAggAmshCCAPIQILIAZBEE8EQCAIIAlqIQYDQCAIIAIQByACQRBqIQIgCEEQaiIIIAZJDQALDAELAkAgBkEHTQRAIAggAi0AADoAACAIIAItAAE6AAEgCCACLQACOgACIAggAi0AAzoAAyAIQQRqIAIgBkECdCIGQcAeaigCAGoiAhAXIAIgBkHgHmooAgBrIQIgBygCxAEhCQwBCyAIIAIQDAsgCUEJSQ0AIAggCWohBiAIQQhqIgggAkEIaiICa0EPTARAA0AgCCACEAwgAkEIaiECIAhBCGoiCCAGSQ0ADAIACwALA0AgCCACEAcgAkEQaiECIAhBEGoiCCAGSQ0ACwsgEBADDQMgC0EBaiELIAMgEGohAwwBCwsDQCAEQQNHBEAgACAEQQJ0IgJqQazQAWogAiAHaigCVDYCACAEQQFqIQQMAQsLIAcoArwBIQgLQbp/IRAgEyAIayIAIBIgA2tLDQAgAwR/IAMgCCAAEAsgAGoFQQALIAFrIRALIAdB0AFqJAAgEAslACAAQgA3AgAgAEEAOwEIIABBADoACyAAIAE2AgwgACACOgAKC7QFAQN/IwBBMGsiBCQAIABB/wFqIgVBfWohBgJAIAMvAQIEQCAEQRhqIAEgAhAGIgIQAw0BIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahASOgAAIAMgBEEIaiAEQRhqEBI6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0FIAEgBEEQaiAEQRhqEBI6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBSABIARBCGogBEEYahASOgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEjoAACABIAJqIABrIQIMAwsgAyAEQRBqIARBGGoQEjoAAiADIARBCGogBEEYahASOgADIANBBGohAwwAAAsACyAEQRhqIAEgAhAGIgIQAw0AIARBEGogBEEYaiADEBwgBEEIaiAEQRhqIAMQHCAAIQMDQAJAIARBGGoQBCADIAZPckUEQCADIARBEGogBEEYahAROgAAIAMgBEEIaiAEQRhqEBE6AAEgBEEYahAERQ0BIANBAmohAwsgBUF+aiEFAn8DQEG6fyECIAMiASAFSw0EIAEgBEEQaiAEQRhqEBE6AAAgAUEBaiEDIARBGGoQBEEDRgRAQQIhAiAEQQhqDAILIAMgBUsNBCABIARBCGogBEEYahAROgABIAFBAmohA0EDIQIgBEEYahAEQQNHDQALIARBEGoLIQUgAyAFIARBGGoQEToAACABIAJqIABrIQIMAgsgAyAEQRBqIARBGGoQEToAAiADIARBCGogBEEYahAROgADIANBBGohAwwAAAsACyAEQTBqJAAgAgtpAQF/An8CQAJAIAJBB00NACABKAAAQbfIwuF+Rw0AIAAgASgABDYCmOIBQWIgAEEQaiABIAIQPiIDEAMNAhogAEKBgICAEDcDiOEBIAAgASADaiACIANrECoMAQsgACABIAIQKgtBAAsLrQMBBn8jAEGAAWsiAyQAQWIhCAJAIAJBCUkNACAAQZjQAGogAUEIaiIEIAJBeGogAEGY0AAQMyIFEAMiBg0AIANBHzYCfCADIANB/ABqIANB+ABqIAQgBCAFaiAGGyIEIAEgAmoiAiAEaxAVIgUQAw0AIAMoAnwiBkEfSw0AIAMoAngiB0EJTw0AIABBiCBqIAMgBkGAC0GADCAHEBggA0E0NgJ8IAMgA0H8AGogA0H4AGogBCAFaiIEIAIgBGsQFSIFEAMNACADKAJ8IgZBNEsNACADKAJ4IgdBCk8NACAAQZAwaiADIAZBgA1B4A4gBxAYIANBIzYCfCADIANB/ABqIANB+ABqIAQgBWoiBCACIARrEBUiBRADDQAgAygCfCIGQSNLDQAgAygCeCIHQQpPDQAgACADIAZBwBBB0BEgBxAYIAQgBWoiBEEMaiIFIAJLDQAgAiAFayEFQQAhAgNAIAJBA0cEQCAEKAAAIgZBf2ogBU8NAiAAIAJBAnRqQZzQAWogBjYCACACQQFqIQIgBEEEaiEEDAELCyAEIAFrIQgLIANBgAFqJAAgCAtGAQN/IABBCGohAyAAKAIEIQJBACEAA0AgACACdkUEQCABIAMgAEEDdGotAAJBFktqIQEgAEEBaiEADAELCyABQQggAmt0C4YDAQV/Qbh/IQcCQCADRQ0AIAItAAAiBEUEQCABQQA2AgBBAUG4fyADQQFGGw8LAn8gAkEBaiIFIARBGHRBGHUiBkF/Sg0AGiAGQX9GBEAgA0EDSA0CIAUvAABBgP4BaiEEIAJBA2oMAQsgA0ECSA0BIAItAAEgBEEIdHJBgIB+aiEEIAJBAmoLIQUgASAENgIAIAVBAWoiASACIANqIgNLDQBBbCEHIABBEGogACAFLQAAIgVBBnZBI0EJIAEgAyABa0HAEEHQEUHwEiAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBmCBqIABBCGogBUEEdkEDcUEfQQggASABIAZqIAgbIgEgAyABa0GAC0GADEGAFyAAKAKM4QEgACgCnOIBIAQQHyIGEAMiCA0AIABBoDBqIABBBGogBUECdkEDcUE0QQkgASABIAZqIAgbIgEgAyABa0GADUHgDkGQGSAAKAKM4QEgACgCnOIBIAQQHyIAEAMNACAAIAFqIAJrIQcLIAcLrQMBCn8jAEGABGsiCCQAAn9BUiACQf8BSw0AGkFUIANBDEsNABogAkEBaiELIABBBGohCUGAgAQgA0F/anRBEHUhCkEAIQJBASEEQQEgA3QiB0F/aiIMIQUDQCACIAtGRQRAAkAgASACQQF0Ig1qLwEAIgZB//8DRgRAIAkgBUECdGogAjoAAiAFQX9qIQVBASEGDAELIARBACAKIAZBEHRBEHVKGyEECyAIIA1qIAY7AQAgAkEBaiECDAELCyAAIAQ7AQIgACADOwEAIAdBA3YgB0EBdmpBA2ohBkEAIQRBACECA0AgBCALRkUEQCABIARBAXRqLgEAIQpBACEAA0AgACAKTkUEQCAJIAJBAnRqIAQ6AAIDQCACIAZqIAxxIgIgBUsNAAsgAEEBaiEADAELCyAEQQFqIQQMAQsLQX8gAg0AGkEAIQIDfyACIAdGBH9BAAUgCCAJIAJBAnRqIgAtAAJBAXRqIgEgAS8BACIBQQFqOwEAIAAgAyABEBRrIgU6AAMgACABIAVB/wFxdCAHazsBACACQQFqIQIMAQsLCyEFIAhBgARqJAAgBQvjBgEIf0FsIQcCQCACQQNJDQACQAJAAkACQCABLQAAIgNBA3EiCUEBaw4DAwEAAgsgACgCiOEBDQBBYg8LIAJBBUkNAkEDIQYgASgAACEFAn8CQAJAIANBAnZBA3EiCEF+aiIEQQFNBEAgBEEBaw0BDAILIAVBDnZB/wdxIQQgBUEEdkH/B3EhAyAIRQwCCyAFQRJ2IQRBBCEGIAVBBHZB//8AcSEDQQAMAQsgBUEEdkH//w9xIgNBgIAISw0DIAEtAARBCnQgBUEWdnIhBEEFIQZBAAshBSAEIAZqIgogAksNAgJAIANBgQZJDQAgACgCnOIBRQ0AQQAhAgNAIAJBg4ABSw0BIAJBQGshAgwAAAsACwJ/IAlBA0YEQCABIAZqIQEgAEHw4gFqIQIgACgCDCEGIAUEQCACIAMgASAEIAYQXwwCCyACIAMgASAEIAYQXQwBCyAAQbjQAWohAiABIAZqIQEgAEHw4gFqIQYgAEGo0ABqIQggBQRAIAggBiADIAEgBCACEF4MAQsgCCAGIAMgASAEIAIQXAsQAw0CIAAgAzYCgOIBIABBATYCiOEBIAAgAEHw4gFqNgLw4QEgCUECRgRAIAAgAEGo0ABqNgIMCyAAIANqIgBBiOMBakIANwAAIABBgOMBakIANwAAIABB+OIBakIANwAAIABB8OIBakIANwAAIAoPCwJ/AkACQAJAIANBAnZBA3FBf2oiBEECSw0AIARBAWsOAgACAQtBASEEIANBA3YMAgtBAiEEIAEvAABBBHYMAQtBAyEEIAEQIUEEdgsiAyAEaiIFQSBqIAJLBEAgBSACSw0CIABB8OIBaiABIARqIAMQCyEBIAAgAzYCgOIBIAAgATYC8OEBIAEgA2oiAEIANwAYIABCADcAECAAQgA3AAggAEIANwAAIAUPCyAAIAM2AoDiASAAIAEgBGo2AvDhASAFDwsCfwJAAkACQCADQQJ2QQNxQX9qIgRBAksNACAEQQFrDgIAAgELQQEhByADQQN2DAILQQIhByABLwAAQQR2DAELIAJBBEkgARAhIgJBj4CAAUtyDQFBAyEHIAJBBHYLIQIgAEHw4gFqIAEgB2otAAAgAkEgahAQIQEgACACNgKA4gEgACABNgLw4QEgB0EBaiEHCyAHC0sAIABC+erQ0OfJoeThADcDICAAQgA3AxggAELP1tO+0ser2UI3AxAgAELW64Lu6v2J9eAANwMIIABCADcDACAAQShqQQBBKBAQGgviAgICfwV+IABBKGoiASAAKAJIaiECAn4gACkDACIDQiBaBEAgACkDECIEQgeJIAApAwgiBUIBiXwgACkDGCIGQgyJfCAAKQMgIgdCEol8IAUQGSAEEBkgBhAZIAcQGQwBCyAAKQMYQsXP2bLx5brqJ3wLIAN8IQMDQCABQQhqIgAgAk0EQEIAIAEpAAAQCSADhUIbiUKHla+vmLbem55/fkLj3MqV/M7y9YV/fCEDIAAhAQwBCwsCQCABQQRqIgAgAksEQCABIQAMAQsgASgAAK1Ch5Wvr5i23puef34gA4VCF4lCz9bTvtLHq9lCfkL5893xmfaZqxZ8IQMLA0AgACACSQRAIAAxAABCxc/ZsvHluuonfiADhUILiUKHla+vmLbem55/fiEDIABBAWohAAwBCwsgA0IhiCADhULP1tO+0ser2UJ+IgNCHYggA4VC+fPd8Zn2masWfiIDQiCIIAOFC+8CAgJ/BH4gACAAKQMAIAKtfDcDAAJAAkAgACgCSCIDIAJqIgRBH00EQCABRQ0BIAAgA2pBKGogASACECAgACgCSCACaiEEDAELIAEgAmohAgJ/IAMEQCAAQShqIgQgA2ogAUEgIANrECAgACAAKQMIIAQpAAAQCTcDCCAAIAApAxAgACkAMBAJNwMQIAAgACkDGCAAKQA4EAk3AxggACAAKQMgIABBQGspAAAQCTcDICAAKAJIIQMgAEEANgJIIAEgA2tBIGohAQsgAUEgaiACTQsEQCACQWBqIQMgACkDICEFIAApAxghBiAAKQMQIQcgACkDCCEIA0AgCCABKQAAEAkhCCAHIAEpAAgQCSEHIAYgASkAEBAJIQYgBSABKQAYEAkhBSABQSBqIgEgA00NAAsgACAFNwMgIAAgBjcDGCAAIAc3AxAgACAINwMICyABIAJPDQEgAEEoaiABIAIgAWsiBBAgCyAAIAQ2AkgLCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQEBogAwVBun8LCy8BAX8gAEUEQEG2f0EAIAMbDwtBun8hBCADIAFNBH8gACACIAMQCxogAwVBun8LC6gCAQZ/IwBBEGsiByQAIABB2OABaikDAEKAgIAQViEIQbh/IQUCQCAEQf//B0sNACAAIAMgBBBCIgUQAyIGDQAgACgCnOIBIQkgACAHQQxqIAMgAyAFaiAGGyIKIARBACAFIAYbayIGEEAiAxADBEAgAyEFDAELIAcoAgwhBCABRQRAQbp/IQUgBEEASg0BCyAGIANrIQUgAyAKaiEDAkAgCQRAIABBADYCnOIBDAELAkACQAJAIARBBUgNACAAQdjgAWopAwBCgICACFgNAAwBCyAAQQA2ApziAQwBCyAAKAIIED8hBiAAQQA2ApziASAGQRRPDQELIAAgASACIAMgBSAEIAgQOSEFDAELIAAgASACIAMgBSAEIAgQOiEFCyAHQRBqJAAgBQtnACAAQdDgAWogASACIAAoAuzhARAuIgEQAwRAIAEPC0G4fyECAkAgAQ0AIABB7OABaigCACIBBEBBYCECIAAoApjiASABRw0BC0EAIQIgAEHw4AFqKAIARQ0AIABBkOEBahBDCyACCycBAX8QVyIERQRAQUAPCyAEIAAgASACIAMgBBBLEE8hACAEEFYgAAs/AQF/AkACQAJAIAAoAqDiAUEBaiIBQQJLDQAgAUEBaw4CAAECCyAAEDBBAA8LIABBADYCoOIBCyAAKAKU4gELvAMCB38BfiMAQRBrIgkkAEG4fyEGAkAgBCgCACIIQQVBCSAAKALs4QEiBRtJDQAgAygCACIHQQFBBSAFGyAFEC8iBRADBEAgBSEGDAELIAggBUEDakkNACAAIAcgBRBJIgYQAw0AIAEgAmohCiAAQZDhAWohCyAIIAVrIQIgBSAHaiEHIAEhBQNAIAcgAiAJECwiBhADDQEgAkF9aiICIAZJBEBBuH8hBgwCCyAJKAIAIghBAksEQEFsIQYMAgsgB0EDaiEHAn8CQAJAAkAgCEEBaw4CAgABCyAAIAUgCiAFayAHIAYQSAwCCyAFIAogBWsgByAGEEcMAQsgBSAKIAVrIActAAAgCSgCCBBGCyIIEAMEQCAIIQYMAgsgACgC8OABBEAgCyAFIAgQRQsgAiAGayECIAYgB2ohByAFIAhqIQUgCSgCBEUNAAsgACkD0OABIgxCf1IEQEFsIQYgDCAFIAFrrFINAQsgACgC8OABBEBBaiEGIAJBBEkNASALEEQhDCAHKAAAIAynRw0BIAdBBGohByACQXxqIQILIAMgBzYCACAEIAI2AgAgBSABayEGCyAJQRBqJAAgBgsuACAAECsCf0EAQQAQAw0AGiABRSACRXJFBEBBYiAAIAEgAhA9EAMNARoLQQALCzcAIAEEQCAAIAAoAsTgASABKAIEIAEoAghqRzYCnOIBCyAAECtBABADIAFFckUEQCAAIAEQWwsL0QIBB38jAEEQayIGJAAgBiAENgIIIAYgAzYCDCAFBEAgBSgCBCEKIAUoAgghCQsgASEIAkACQANAIAAoAuzhARAWIQsCQANAIAQgC0kNASADKAAAQXBxQdDUtMIBRgRAIAMgBBAiIgcQAw0EIAQgB2shBCADIAdqIQMMAQsLIAYgAzYCDCAGIAQ2AggCQCAFBEAgACAFEE5BACEHQQAQA0UNAQwFCyAAIAogCRBNIgcQAw0ECyAAIAgQUCAMQQFHQQAgACAIIAIgBkEMaiAGQQhqEEwiByIDa0EAIAMQAxtBCkdyRQRAQbh/IQcMBAsgBxADDQMgAiAHayECIAcgCGohCEEBIQwgBigCDCEDIAYoAgghBAwBCwsgBiADNgIMIAYgBDYCCEG4fyEHIAQNASAIIAFrIQcMAQsgBiADNgIMIAYgBDYCCAsgBkEQaiQAIAcLRgECfyABIAAoArjgASICRwRAIAAgAjYCxOABIAAgATYCuOABIAAoArzgASEDIAAgATYCvOABIAAgASADIAJrajYCwOABCwutAgIEfwF+IwBBQGoiBCQAAkACQCACQQhJDQAgASgAAEFwcUHQ1LTCAUcNACABIAIQIiEBIABCADcDCCAAQQA2AgQgACABNgIADAELIARBGGogASACEC0iAxADBEAgACADEBoMAQsgAwRAIABBuH8QGgwBCyACIAQoAjAiA2shAiABIANqIQMDQAJAIAAgAyACIARBCGoQLCIFEAMEfyAFBSACIAVBA2oiBU8NAUG4fwsQGgwCCyAGQQFqIQYgAiAFayECIAMgBWohAyAEKAIMRQ0ACyAEKAI4BEAgAkEDTQRAIABBuH8QGgwCCyADQQRqIQMLIAQoAighAiAEKQMYIQcgAEEANgIEIAAgAyABazYCACAAIAIgBmytIAcgB0J/URs3AwgLIARBQGskAAslAQF/IwBBEGsiAiQAIAIgACABEFEgAigCACEAIAJBEGokACAAC30BBH8jAEGQBGsiBCQAIARB/wE2AggCQCAEQRBqIARBCGogBEEMaiABIAIQFSIGEAMEQCAGIQUMAQtBVCEFIAQoAgwiB0EGSw0AIAMgBEEQaiAEKAIIIAcQQSIFEAMNACAAIAEgBmogAiAGayADEDwhBQsgBEGQBGokACAFC4cBAgJ/An5BABAWIQMCQANAIAEgA08EQAJAIAAoAABBcHFB0NS0wgFGBEAgACABECIiAhADRQ0BQn4PCyAAIAEQVSIEQn1WDQMgBCAFfCIFIARUIQJCfiEEIAINAyAAIAEQUiICEAMNAwsgASACayEBIAAgAmohAAwBCwtCfiAFIAEbIQQLIAQLPwIBfwF+IwBBMGsiAiQAAn5CfiACQQhqIAAgARAtDQAaQgAgAigCHEEBRg0AGiACKQMICyEDIAJBMGokACADC40BAQJ/IwBBMGsiASQAAkAgAEUNACAAKAKI4gENACABIABB/OEBaigCADYCKCABIAApAvThATcDICAAEDAgACgCqOIBIQIgASABKAIoNgIYIAEgASkDIDcDECACIAFBEGoQGyAAQQA2AqjiASABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALKgECfyMAQRBrIgAkACAAQQA2AgggAEIANwMAIAAQWCEBIABBEGokACABC4cBAQN/IwBBEGsiAiQAAkAgACgCAEUgACgCBEVzDQAgAiAAKAIINgIIIAIgACkCADcDAAJ/IAIoAgAiAQRAIAIoAghBqOMJIAERBQAMAQtBqOMJECgLIgFFDQAgASAAKQIANwL04QEgAUH84QFqIAAoAgg2AgAgARBZIAEhAwsgAkEQaiQAIAMLywEBAn8jAEEgayIBJAAgAEGBgIDAADYCtOIBIABBADYCiOIBIABBADYC7OEBIABCADcDkOIBIABBADYCpOMJIABBADYC3OIBIABCADcCzOIBIABBADYCvOIBIABBADYCxOABIABCADcCnOIBIABBpOIBakIANwIAIABBrOIBakEANgIAIAFCADcCECABQgA3AhggASABKQMYNwMIIAEgASkDEDcDACABKAIIQQh2QQFxIQIgAEEANgLg4gEgACACNgKM4gEgAUEgaiQAC3YBA38jAEEwayIBJAAgAARAIAEgAEHE0AFqIgIoAgA2AiggASAAKQK80AE3AyAgACgCACEDIAEgAigCADYCGCABIAApArzQATcDECADIAFBEGoQGyABIAEoAig2AgggASABKQMgNwMAIAAgARAbCyABQTBqJAALzAEBAX8gACABKAK00AE2ApjiASAAIAEoAgQiAjYCwOABIAAgAjYCvOABIAAgAiABKAIIaiICNgK44AEgACACNgLE4AEgASgCuNABBEAgAEKBgICAEDcDiOEBIAAgAUGk0ABqNgIMIAAgAUGUIGo2AgggACABQZwwajYCBCAAIAFBDGo2AgAgAEGs0AFqIAFBqNABaigCADYCACAAQbDQAWogAUGs0AFqKAIANgIAIABBtNABaiABQbDQAWooAgA2AgAPCyAAQgA3A4jhAQs7ACACRQRAQbp/DwsgBEUEQEFsDwsgAiAEEGAEQCAAIAEgAiADIAQgBRBhDwsgACABIAIgAyAEIAUQZQtGAQF/IwBBEGsiBSQAIAVBCGogBBAOAn8gBS0ACQRAIAAgASACIAMgBBAyDAELIAAgASACIAMgBBA0CyEAIAVBEGokACAACzQAIAAgAyAEIAUQNiIFEAMEQCAFDwsgBSAESQR/IAEgAiADIAVqIAQgBWsgABA1BUG4fwsLRgEBfyMAQRBrIgUkACAFQQhqIAQQDgJ/IAUtAAkEQCAAIAEgAiADIAQQYgwBCyAAIAEgAiADIAQQNQshACAFQRBqJAAgAAtZAQF/QQ8hAiABIABJBEAgAUEEdCAAbiECCyAAQQh2IgEgAkEYbCIAQYwIaigCAGwgAEGICGooAgBqIgJBA3YgAmogAEGACGooAgAgAEGECGooAgAgAWxqSQs3ACAAIAMgBCAFQYAQEDMiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQMgVBuH8LC78DAQN/IwBBIGsiBSQAIAVBCGogAiADEAYiAhADRQRAIAAgAWoiB0F9aiEGIAUgBBAOIARBBGohAiAFLQACIQMDQEEAIAAgBkkgBUEIahAEGwRAIAAgAiAFQQhqIAMQAkECdGoiBC8BADsAACAFQQhqIAQtAAIQASAAIAQtAANqIgQgAiAFQQhqIAMQAkECdGoiAC8BADsAACAFQQhqIAAtAAIQASAEIAAtAANqIQAMAQUgB0F+aiEEA0AgBUEIahAEIAAgBEtyRQRAIAAgAiAFQQhqIAMQAkECdGoiBi8BADsAACAFQQhqIAYtAAIQASAAIAYtAANqIQAMAQsLA0AgACAES0UEQCAAIAIgBUEIaiADEAJBAnRqIgYvAQA7AAAgBUEIaiAGLQACEAEgACAGLQADaiEADAELCwJAIAAgB08NACAAIAIgBUEIaiADEAIiA0ECdGoiAC0AADoAACAALQADQQFGBEAgBUEIaiAALQACEAEMAQsgBSgCDEEfSw0AIAVBCGogAiADQQJ0ai0AAhABIAUoAgxBIUkNACAFQSA2AgwLIAFBbCAFQQhqEAobIQILCwsgBUEgaiQAIAILkgIBBH8jAEFAaiIJJAAgCSADQTQQCyEDAkAgBEECSA0AIAMgBEECdGooAgAhCSADQTxqIAgQIyADQQE6AD8gAyACOgA+QQAhBCADKAI8IQoDQCAEIAlGDQEgACAEQQJ0aiAKNgEAIARBAWohBAwAAAsAC0EAIQkDQCAGIAlGRQRAIAMgBSAJQQF0aiIKLQABIgtBAnRqIgwoAgAhBCADQTxqIAotAABBCHQgCGpB//8DcRAjIANBAjoAPyADIAcgC2siCiACajoAPiAEQQEgASAKa3RqIQogAygCPCELA0AgACAEQQJ0aiALNgEAIARBAWoiBCAKSQ0ACyAMIAo2AgAgCUEBaiEJDAELCyADQUBrJAALowIBCX8jAEHQAGsiCSQAIAlBEGogBUE0EAsaIAcgBmshDyAHIAFrIRADQAJAIAMgCkcEQEEBIAEgByACIApBAXRqIgYtAAEiDGsiCGsiC3QhDSAGLQAAIQ4gCUEQaiAMQQJ0aiIMKAIAIQYgCyAPTwRAIAAgBkECdGogCyAIIAUgCEE0bGogCCAQaiIIQQEgCEEBShsiCCACIAQgCEECdGooAgAiCEEBdGogAyAIayAHIA4QYyAGIA1qIQgMAgsgCUEMaiAOECMgCUEBOgAPIAkgCDoADiAGIA1qIQggCSgCDCELA0AgBiAITw0CIAAgBkECdGogCzYBACAGQQFqIQYMAAALAAsgCUHQAGokAA8LIAwgCDYCACAKQQFqIQoMAAALAAs0ACAAIAMgBCAFEDYiBRADBEAgBQ8LIAUgBEkEfyABIAIgAyAFaiAEIAVrIAAQNAVBuH8LCyMAIAA/AEEQdGtB//8DakEQdkAAQX9GBEBBAA8LQQAQAEEBCzsBAX8gAgRAA0AgACABIAJBgCAgAkGAIEkbIgMQCyEAIAFBgCBqIQEgAEGAIGohACACIANrIgINAAsLCwYAIAAQAwsLqBUJAEGICAsNAQAAAAEAAAACAAAAAgBBoAgLswYBAAAAAQAAAAIAAAACAAAAJgAAAIIAAAAhBQAASgAAAGcIAAAmAAAAwAEAAIAAAABJBQAASgAAAL4IAAApAAAALAIAAIAAAABJBQAASgAAAL4IAAAvAAAAygIAAIAAAACKBQAASgAAAIQJAAA1AAAAcwMAAIAAAACdBQAASgAAAKAJAAA9AAAAgQMAAIAAAADrBQAASwAAAD4KAABEAAAAngMAAIAAAABNBgAASwAAAKoKAABLAAAAswMAAIAAAADBBgAATQAAAB8NAABNAAAAUwQAAIAAAAAjCAAAUQAAAKYPAABUAAAAmQQAAIAAAABLCQAAVwAAALESAABYAAAA2gQAAIAAAABvCQAAXQAAACMUAABUAAAARQUAAIAAAABUCgAAagAAAIwUAABqAAAArwUAAIAAAAB2CQAAfAAAAE4QAAB8AAAA0gIAAIAAAABjBwAAkQAAAJAHAACSAAAAAAAAAAEAAAABAAAABQAAAA0AAAAdAAAAPQAAAH0AAAD9AAAA/QEAAP0DAAD9BwAA/Q8AAP0fAAD9PwAA/X8AAP3/AAD9/wEA/f8DAP3/BwD9/w8A/f8fAP3/PwD9/38A/f//AP3//wH9//8D/f//B/3//w/9//8f/f//P/3//38AAAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABEAAAASAAAAEwAAABQAAAAVAAAAFgAAABcAAAAYAAAAGQAAABoAAAAbAAAAHAAAAB0AAAAeAAAAHwAAAAMAAAAEAAAABQAAAAYAAAAHAAAACAAAAAkAAAAKAAAACwAAAAwAAAANAAAADgAAAA8AAAAQAAAAEQAAABIAAAATAAAAFAAAABUAAAAWAAAAFwAAABgAAAAZAAAAGgAAABsAAAAcAAAAHQAAAB4AAAAfAAAAIAAAACEAAAAiAAAAIwAAACUAAAAnAAAAKQAAACsAAAAvAAAAMwAAADsAAABDAAAAUwAAAGMAAACDAAAAAwEAAAMCAAADBAAAAwgAAAMQAAADIAAAA0AAAAOAAAADAAEAQeAPC1EBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAEAAAABQAAAAcAAAAIAAAACQAAAAoAAAALAAAADAAAAA0AAAAOAAAADwAAABAAQcQQC4sBAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAABIAAAAUAAAAFgAAABgAAAAcAAAAIAAAACgAAAAwAAAAQAAAAIAAAAAAAQAAAAIAAAAEAAAACAAAABAAAAAgAAAAQAAAAIAAAAAAAQBBkBIL5gQBAAAAAQAAAAEAAAABAAAAAgAAAAIAAAADAAAAAwAAAAQAAAAGAAAABwAAAAgAAAAJAAAACgAAAAsAAAAMAAAADQAAAA4AAAAPAAAAEAAAAAEAAAAEAAAACAAAAAAAAAABAAEBBgAAAAAAAAQAAAAAEAAABAAAAAAgAAAFAQAAAAAAAAUDAAAAAAAABQQAAAAAAAAFBgAAAAAAAAUHAAAAAAAABQkAAAAAAAAFCgAAAAAAAAUMAAAAAAAABg4AAAAAAAEFEAAAAAAAAQUUAAAAAAABBRYAAAAAAAIFHAAAAAAAAwUgAAAAAAAEBTAAAAAgAAYFQAAAAAAABwWAAAAAAAAIBgABAAAAAAoGAAQAAAAADAYAEAAAIAAABAAAAAAAAAAEAQAAAAAAAAUCAAAAIAAABQQAAAAAAAAFBQAAACAAAAUHAAAAAAAABQgAAAAgAAAFCgAAAAAAAAULAAAAAAAABg0AAAAgAAEFEAAAAAAAAQUSAAAAIAABBRYAAAAAAAIFGAAAACAAAwUgAAAAAAADBSgAAAAAAAYEQAAAABAABgRAAAAAIAAHBYAAAAAAAAkGAAIAAAAACwYACAAAMAAABAAAAAAQAAAEAQAAACAAAAUCAAAAIAAABQMAAAAgAAAFBQAAACAAAAUGAAAAIAAABQgAAAAgAAAFCQAAACAAAAULAAAAIAAABQwAAAAAAAAGDwAAACAAAQUSAAAAIAABBRQAAAAgAAIFGAAAACAAAgUcAAAAIAADBSgAAAAgAAQFMAAAAAAAEAYAAAEAAAAPBgCAAAAAAA4GAEAAAAAADQYAIABBgBcLhwIBAAEBBQAAAAAAAAUAAAAAAAAGBD0AAAAAAAkF/QEAAAAADwX9fwAAAAAVBf3/HwAAAAMFBQAAAAAABwR9AAAAAAAMBf0PAAAAABIF/f8DAAAAFwX9/38AAAAFBR0AAAAAAAgE/QAAAAAADgX9PwAAAAAUBf3/DwAAAAIFAQAAABAABwR9AAAAAAALBf0HAAAAABEF/f8BAAAAFgX9/z8AAAAEBQ0AAAAQAAgE/QAAAAAADQX9HwAAAAATBf3/BwAAAAEFAQAAABAABgQ9AAAAAAAKBf0DAAAAABAF/f8AAAAAHAX9//8PAAAbBf3//wcAABoF/f//AwAAGQX9//8BAAAYBf3//wBBkBkLhgQBAAEBBgAAAAAAAAYDAAAAAAAABAQAAAAgAAAFBQAAAAAAAAUGAAAAAAAABQgAAAAAAAAFCQAAAAAAAAULAAAAAAAABg0AAAAAAAAGEAAAAAAAAAYTAAAAAAAABhYAAAAAAAAGGQAAAAAAAAYcAAAAAAAABh8AAAAAAAAGIgAAAAAAAQYlAAAAAAABBikAAAAAAAIGLwAAAAAAAwY7AAAAAAAEBlMAAAAAAAcGgwAAAAAACQYDAgAAEAAABAQAAAAAAAAEBQAAACAAAAUGAAAAAAAABQcAAAAgAAAFCQAAAAAAAAUKAAAAAAAABgwAAAAAAAAGDwAAAAAAAAYSAAAAAAAABhUAAAAAAAAGGAAAAAAAAAYbAAAAAAAABh4AAAAAAAAGIQAAAAAAAQYjAAAAAAABBicAAAAAAAIGKwAAAAAAAwYzAAAAAAAEBkMAAAAAAAUGYwAAAAAACAYDAQAAIAAABAQAAAAwAAAEBAAAABAAAAQFAAAAIAAABQcAAAAgAAAFCAAAACAAAAUKAAAAIAAABQsAAAAAAAAGDgAAAAAAAAYRAAAAAAAABhQAAAAAAAAGFwAAAAAAAAYaAAAAAAAABh0AAAAAAAAGIAAAAAAAEAYDAAEAAAAPBgOAAAAAAA4GA0AAAAAADQYDIAAAAAAMBgMQAAAAAAsGAwgAAAAACgYDBABBpB0L2QEBAAAAAwAAAAcAAAAPAAAAHwAAAD8AAAB/AAAA/wAAAP8BAAD/AwAA/wcAAP8PAAD/HwAA/z8AAP9/AAD//wAA//8BAP//AwD//wcA//8PAP//HwD//z8A//9/AP///wD///8B////A////wf///8P////H////z////9/AAAAAAEAAAACAAAABAAAAAAAAAACAAAABAAAAAgAAAAAAAAAAQAAAAIAAAABAAAABAAAAAQAAAAEAAAABAAAAAgAAAAIAAAACAAAAAcAAAAIAAAACQAAAAoAAAALAEGgIAsDwBBQ';
  74591. var _taskCache$1 = new WeakMap();
  74592. var _activeLoaders = 0;
  74593. var _zstd;
  74594. class KTX2Loader extends Loader {
  74595. constructor(manager) {
  74596. super(manager);
  74597. this.transcoderPath = '';
  74598. this.transcoderBinary = null;
  74599. this.transcoderPending = null;
  74600. this.workerPool = new WorkerPool$1();
  74601. this.workerSourceURL = '';
  74602. this.workerConfig = null;
  74603. if (typeof MSC_TRANSCODER !== 'undefined') {
  74604. console.warn('THREE.KTX2Loader: Please update to latest "basis_transcoder".' + ' "msc_basis_transcoder" is no longer supported in three.js r125+.');
  74605. }
  74606. }
  74607. setTranscoderPath(path) {
  74608. this.transcoderPath = path;
  74609. return this;
  74610. }
  74611. setWorkerLimit(num) {
  74612. this.workerPool.setWorkerLimit(num);
  74613. return this;
  74614. }
  74615. detectSupport(renderer) {
  74616. this.workerConfig = {
  74617. astcSupported: renderer.extensions.has('WEBGL_compressed_texture_astc'),
  74618. etc1Supported: renderer.extensions.has('WEBGL_compressed_texture_etc1'),
  74619. etc2Supported: renderer.extensions.has('WEBGL_compressed_texture_etc'),
  74620. dxtSupported: renderer.extensions.has('WEBGL_compressed_texture_s3tc'),
  74621. bptcSupported: renderer.extensions.has('EXT_texture_compression_bptc'),
  74622. pvrtcSupported: renderer.extensions.has('WEBGL_compressed_texture_pvrtc') || renderer.extensions.has('WEBKIT_WEBGL_compressed_texture_pvrtc')
  74623. };
  74624. if (renderer.capabilities.isWebGL2) {
  74625. // https://github.com/mrdoob/three.js/pull/22928
  74626. this.workerConfig.etc1Supported = false;
  74627. }
  74628. return this;
  74629. }
  74630. init() {
  74631. if (!this.transcoderPending) {
  74632. // Load transcoder wrapper.
  74633. var jsLoader = new FileLoader(this.manager);
  74634. jsLoader.setPath(this.transcoderPath);
  74635. jsLoader.setWithCredentials(this.withCredentials);
  74636. var jsContent = jsLoader.loadAsync('basis_transcoder.js');
  74637. // Load transcoder WASM binary.
  74638. var binaryLoader = new FileLoader(this.manager);
  74639. binaryLoader.setPath(this.transcoderPath);
  74640. binaryLoader.setResponseType('arraybuffer');
  74641. binaryLoader.setWithCredentials(this.withCredentials);
  74642. var binaryContent = binaryLoader.loadAsync('basis_transcoder.wasm');
  74643. this.transcoderPending = Promise.all([jsContent, binaryContent]).then(_ref => {
  74644. var [jsContent, binaryContent] = _ref;
  74645. var fn = KTX2Loader.BasisWorker.toString();
  74646. var body = ['/* constants */', 'let _EngineFormat = ' + JSON.stringify(KTX2Loader.EngineFormat), 'let _TranscoderFormat = ' + JSON.stringify(KTX2Loader.TranscoderFormat), 'let _BasisFormat = ' + JSON.stringify(KTX2Loader.BasisFormat), '/* basis_transcoder.js */', jsContent, '/* worker */', fn.substring(fn.indexOf('{') + 1, fn.lastIndexOf('}'))].join('\n');
  74647. this.workerSourceURL = URL.createObjectURL(new Blob([body]));
  74648. this.transcoderBinary = binaryContent;
  74649. this.workerPool.setWorkerCreator(() => {
  74650. var worker = new Worker(this.workerSourceURL);
  74651. var transcoderBinary = this.transcoderBinary.slice(0);
  74652. worker.postMessage({
  74653. type: 'init',
  74654. config: this.workerConfig,
  74655. transcoderBinary
  74656. }, [transcoderBinary]);
  74657. return worker;
  74658. });
  74659. });
  74660. if (_activeLoaders > 0) {
  74661. // Each instance loads a transcoder and allocates workers, increasing network and memory cost.
  74662. console.warn('THREE.KTX2Loader: Multiple active KTX2 loaders may cause performance issues.' + ' Use a single KTX2Loader instance, or call .dispose() on old instances.');
  74663. }
  74664. _activeLoaders++;
  74665. }
  74666. return this.transcoderPending;
  74667. }
  74668. load(url, onLoad, onProgress, onError) {
  74669. if (this.workerConfig === null) {
  74670. throw new Error('THREE.KTX2Loader: Missing initialization with `.detectSupport( renderer )`.');
  74671. }
  74672. var loader = new FileLoader(this.manager);
  74673. loader.setResponseType('arraybuffer');
  74674. loader.setWithCredentials(this.withCredentials);
  74675. loader.load(url, buffer => {
  74676. // Check for an existing task using this buffer. A transferred buffer cannot be transferred
  74677. // again from this thread.
  74678. if (_taskCache$1.has(buffer)) {
  74679. var cachedTask = _taskCache$1.get(buffer);
  74680. return cachedTask.promise.then(onLoad).catch(onError);
  74681. }
  74682. this._createTexture(buffer).then(texture => onLoad ? onLoad(texture) : null).catch(onError);
  74683. }, onProgress, onError);
  74684. }
  74685. _createTextureFrom(transcodeResult, container) {
  74686. var {
  74687. mipmaps,
  74688. width,
  74689. height,
  74690. format,
  74691. type,
  74692. error,
  74693. dfdTransferFn,
  74694. dfdFlags
  74695. } = transcodeResult;
  74696. if (type === 'error') return Promise.reject(error);
  74697. var texture = container.layerCount > 1 ? new CompressedArrayTexture(mipmaps, width, height, container.layerCount, format, UnsignedByteType) : new CompressedTexture(mipmaps, width, height, format, UnsignedByteType);
  74698. texture.minFilter = mipmaps.length === 1 ? LinearFilter : LinearMipmapLinearFilter;
  74699. texture.magFilter = LinearFilter;
  74700. texture.generateMipmaps = false;
  74701. texture.needsUpdate = true;
  74702. texture.encoding = dfdTransferFn === x$2 ? sRGBEncoding : LinearEncoding;
  74703. texture.premultiplyAlpha = !!(dfdFlags & p);
  74704. return texture;
  74705. }
  74706. /**
  74707. * @param {ArrayBuffer} buffer
  74708. * @param {object?} config
  74709. * @return {Promise<CompressedTexture|CompressedArrayTexture|DataTexture|Data3DTexture>}
  74710. */
  74711. _createTexture(buffer) {
  74712. var _arguments = arguments,
  74713. _this = this;
  74714. return _asyncToGenerator(function* () {
  74715. var config = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : {};
  74716. var container = Pi(new Uint8Array(buffer));
  74717. if (container.vkFormat !== nt) {
  74718. return createDataTexture(container);
  74719. }
  74720. //
  74721. var taskConfig = config;
  74722. var texturePending = _this.init().then(() => {
  74723. return _this.workerPool.postMessage({
  74724. type: 'transcode',
  74725. buffer,
  74726. taskConfig: taskConfig
  74727. }, [buffer]);
  74728. }).then(e => _this._createTextureFrom(e.data, container));
  74729. // Cache the task result.
  74730. _taskCache$1.set(buffer, {
  74731. promise: texturePending
  74732. });
  74733. return texturePending;
  74734. })();
  74735. }
  74736. dispose() {
  74737. this.workerPool.dispose();
  74738. if (this.workerSourceURL) URL.revokeObjectURL(this.workerSourceURL);
  74739. _activeLoaders--;
  74740. return this;
  74741. }
  74742. }
  74743. /* CONSTANTS */
  74744. KTX2Loader.BasisFormat = {
  74745. ETC1S: 0,
  74746. UASTC_4x4: 1
  74747. };
  74748. KTX2Loader.TranscoderFormat = {
  74749. ETC1: 0,
  74750. ETC2: 1,
  74751. BC1: 2,
  74752. BC3: 3,
  74753. BC4: 4,
  74754. BC5: 5,
  74755. BC7_M6_OPAQUE_ONLY: 6,
  74756. BC7_M5: 7,
  74757. PVRTC1_4_RGB: 8,
  74758. PVRTC1_4_RGBA: 9,
  74759. ASTC_4x4: 10,
  74760. ATC_RGB: 11,
  74761. ATC_RGBA_INTERPOLATED_ALPHA: 12,
  74762. RGBA32: 13,
  74763. RGB565: 14,
  74764. BGR565: 15,
  74765. RGBA4444: 16
  74766. };
  74767. KTX2Loader.EngineFormat = {
  74768. RGBAFormat: RGBAFormat,
  74769. RGBA_ASTC_4x4_Format: RGBA_ASTC_4x4_Format,
  74770. RGBA_BPTC_Format: RGBA_BPTC_Format,
  74771. RGBA_ETC2_EAC_Format: RGBA_ETC2_EAC_Format,
  74772. RGBA_PVRTC_4BPPV1_Format: RGBA_PVRTC_4BPPV1_Format,
  74773. RGBA_S3TC_DXT5_Format: RGBA_S3TC_DXT5_Format$1,
  74774. RGB_ETC1_Format: RGB_ETC1_Format,
  74775. RGB_ETC2_Format: RGB_ETC2_Format,
  74776. RGB_PVRTC_4BPPV1_Format: RGB_PVRTC_4BPPV1_Format,
  74777. RGB_S3TC_DXT1_Format: RGB_S3TC_DXT1_Format
  74778. };
  74779. /* WEB WORKER */
  74780. KTX2Loader.BasisWorker = function () {
  74781. var config;
  74782. var transcoderPending;
  74783. var BasisModule;
  74784. var EngineFormat = _EngineFormat; // eslint-disable-line no-undef
  74785. var TranscoderFormat = _TranscoderFormat; // eslint-disable-line no-undef
  74786. var BasisFormat = _BasisFormat; // eslint-disable-line no-undef
  74787. self.addEventListener('message', function (e) {
  74788. var message = e.data;
  74789. switch (message.type) {
  74790. case 'init':
  74791. config = message.config;
  74792. init(message.transcoderBinary);
  74793. break;
  74794. case 'transcode':
  74795. transcoderPending.then(() => {
  74796. try {
  74797. var {
  74798. width,
  74799. height,
  74800. hasAlpha,
  74801. mipmaps,
  74802. format,
  74803. dfdTransferFn,
  74804. dfdFlags
  74805. } = transcode(message.buffer);
  74806. var buffers = [];
  74807. for (var i = 0; i < mipmaps.length; ++i) {
  74808. buffers.push(mipmaps[i].data.buffer);
  74809. }
  74810. self.postMessage({
  74811. type: 'transcode',
  74812. id: message.id,
  74813. width,
  74814. height,
  74815. hasAlpha,
  74816. mipmaps,
  74817. format,
  74818. dfdTransferFn,
  74819. dfdFlags
  74820. }, buffers);
  74821. } catch (error) {
  74822. console.error(error);
  74823. self.postMessage({
  74824. type: 'error',
  74825. id: message.id,
  74826. error: error.message
  74827. });
  74828. }
  74829. });
  74830. break;
  74831. }
  74832. });
  74833. function init(wasmBinary) {
  74834. transcoderPending = new Promise(resolve => {
  74835. BasisModule = {
  74836. wasmBinary,
  74837. onRuntimeInitialized: resolve
  74838. };
  74839. BASIS(BasisModule); // eslint-disable-line no-undef
  74840. }).then(() => {
  74841. BasisModule.initializeBasis();
  74842. if (BasisModule.KTX2File === undefined) {
  74843. console.warn('THREE.KTX2Loader: Please update Basis Universal transcoder.');
  74844. }
  74845. });
  74846. }
  74847. function transcode(buffer) {
  74848. var ktx2File = new BasisModule.KTX2File(new Uint8Array(buffer));
  74849. function cleanup() {
  74850. ktx2File.close();
  74851. ktx2File.delete();
  74852. }
  74853. if (!ktx2File.isValid()) {
  74854. cleanup();
  74855. throw new Error('THREE.KTX2Loader: Invalid or unsupported .ktx2 file');
  74856. }
  74857. var basisFormat = ktx2File.isUASTC() ? BasisFormat.UASTC_4x4 : BasisFormat.ETC1S;
  74858. var width = ktx2File.getWidth();
  74859. var height = ktx2File.getHeight();
  74860. var layers = ktx2File.getLayers() || 1;
  74861. var levels = ktx2File.getLevels();
  74862. var hasAlpha = ktx2File.getHasAlpha();
  74863. var dfdTransferFn = ktx2File.getDFDTransferFunc();
  74864. var dfdFlags = ktx2File.getDFDFlags();
  74865. var {
  74866. transcoderFormat,
  74867. engineFormat
  74868. } = getTranscoderFormat(basisFormat, width, height, hasAlpha);
  74869. if (!width || !height || !levels) {
  74870. cleanup();
  74871. throw new Error('THREE.KTX2Loader: Invalid texture');
  74872. }
  74873. if (!ktx2File.startTranscoding()) {
  74874. cleanup();
  74875. throw new Error('THREE.KTX2Loader: .startTranscoding failed');
  74876. }
  74877. var mipmaps = [];
  74878. for (var mip = 0; mip < levels; mip++) {
  74879. var layerMips = [];
  74880. var mipWidth = void 0,
  74881. mipHeight = void 0;
  74882. for (var layer = 0; layer < layers; layer++) {
  74883. var levelInfo = ktx2File.getImageLevelInfo(mip, layer, 0);
  74884. mipWidth = levelInfo.origWidth;
  74885. mipHeight = levelInfo.origHeight;
  74886. var dst = new Uint8Array(ktx2File.getImageTranscodedSizeInBytes(mip, layer, 0, transcoderFormat));
  74887. var status = ktx2File.transcodeImage(dst, mip, layer, 0, transcoderFormat, 0, -1, -1);
  74888. if (!status) {
  74889. cleanup();
  74890. throw new Error('THREE.KTX2Loader: .transcodeImage failed.');
  74891. }
  74892. layerMips.push(dst);
  74893. }
  74894. mipmaps.push({
  74895. data: concat(layerMips),
  74896. width: mipWidth,
  74897. height: mipHeight
  74898. });
  74899. }
  74900. cleanup();
  74901. return {
  74902. width,
  74903. height,
  74904. hasAlpha,
  74905. mipmaps,
  74906. format: engineFormat,
  74907. dfdTransferFn,
  74908. dfdFlags
  74909. };
  74910. }
  74911. //
  74912. // Optimal choice of a transcoder target format depends on the Basis format (ETC1S or UASTC),
  74913. // device capabilities, and texture dimensions. The list below ranks the formats separately
  74914. // for ETC1S and UASTC.
  74915. //
  74916. // In some cases, transcoding UASTC to RGBA32 might be preferred for higher quality (at
  74917. // significant memory cost) compared to ETC1/2, BC1/3, and PVRTC. The transcoder currently
  74918. // chooses RGBA32 only as a last resort and does not expose that option to the caller.
  74919. var FORMAT_OPTIONS = [{
  74920. if: 'astcSupported',
  74921. basisFormat: [BasisFormat.UASTC_4x4],
  74922. transcoderFormat: [TranscoderFormat.ASTC_4x4, TranscoderFormat.ASTC_4x4],
  74923. engineFormat: [EngineFormat.RGBA_ASTC_4x4_Format, EngineFormat.RGBA_ASTC_4x4_Format],
  74924. priorityETC1S: Infinity,
  74925. priorityUASTC: 1,
  74926. needsPowerOfTwo: false
  74927. }, {
  74928. if: 'bptcSupported',
  74929. basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
  74930. transcoderFormat: [TranscoderFormat.BC7_M5, TranscoderFormat.BC7_M5],
  74931. engineFormat: [EngineFormat.RGBA_BPTC_Format, EngineFormat.RGBA_BPTC_Format],
  74932. priorityETC1S: 3,
  74933. priorityUASTC: 2,
  74934. needsPowerOfTwo: false
  74935. }, {
  74936. if: 'dxtSupported',
  74937. basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
  74938. transcoderFormat: [TranscoderFormat.BC1, TranscoderFormat.BC3],
  74939. engineFormat: [EngineFormat.RGB_S3TC_DXT1_Format, EngineFormat.RGBA_S3TC_DXT5_Format],
  74940. priorityETC1S: 4,
  74941. priorityUASTC: 5,
  74942. needsPowerOfTwo: false
  74943. }, {
  74944. if: 'etc2Supported',
  74945. basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
  74946. transcoderFormat: [TranscoderFormat.ETC1, TranscoderFormat.ETC2],
  74947. engineFormat: [EngineFormat.RGB_ETC2_Format, EngineFormat.RGBA_ETC2_EAC_Format],
  74948. priorityETC1S: 1,
  74949. priorityUASTC: 3,
  74950. needsPowerOfTwo: false
  74951. }, {
  74952. if: 'etc1Supported',
  74953. basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
  74954. transcoderFormat: [TranscoderFormat.ETC1],
  74955. engineFormat: [EngineFormat.RGB_ETC1_Format],
  74956. priorityETC1S: 2,
  74957. priorityUASTC: 4,
  74958. needsPowerOfTwo: false
  74959. }, {
  74960. if: 'pvrtcSupported',
  74961. basisFormat: [BasisFormat.ETC1S, BasisFormat.UASTC_4x4],
  74962. transcoderFormat: [TranscoderFormat.PVRTC1_4_RGB, TranscoderFormat.PVRTC1_4_RGBA],
  74963. engineFormat: [EngineFormat.RGB_PVRTC_4BPPV1_Format, EngineFormat.RGBA_PVRTC_4BPPV1_Format],
  74964. priorityETC1S: 5,
  74965. priorityUASTC: 6,
  74966. needsPowerOfTwo: true
  74967. }];
  74968. var ETC1S_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
  74969. return a.priorityETC1S - b.priorityETC1S;
  74970. });
  74971. var UASTC_OPTIONS = FORMAT_OPTIONS.sort(function (a, b) {
  74972. return a.priorityUASTC - b.priorityUASTC;
  74973. });
  74974. function getTranscoderFormat(basisFormat, width, height, hasAlpha) {
  74975. var transcoderFormat;
  74976. var engineFormat;
  74977. var options = basisFormat === BasisFormat.ETC1S ? ETC1S_OPTIONS : UASTC_OPTIONS;
  74978. for (var i = 0; i < options.length; i++) {
  74979. var opt = options[i];
  74980. if (!config[opt.if]) continue;
  74981. if (!opt.basisFormat.includes(basisFormat)) continue;
  74982. if (hasAlpha && opt.transcoderFormat.length < 2) continue;
  74983. if (opt.needsPowerOfTwo && !(isPowerOfTwo(width) && isPowerOfTwo(height))) continue;
  74984. transcoderFormat = opt.transcoderFormat[hasAlpha ? 1 : 0];
  74985. engineFormat = opt.engineFormat[hasAlpha ? 1 : 0];
  74986. return {
  74987. transcoderFormat,
  74988. engineFormat
  74989. };
  74990. }
  74991. console.warn('THREE.KTX2Loader: No suitable compressed texture format found. Decoding to RGBA32.');
  74992. transcoderFormat = TranscoderFormat.RGBA32;
  74993. engineFormat = EngineFormat.RGBAFormat;
  74994. return {
  74995. transcoderFormat,
  74996. engineFormat
  74997. };
  74998. }
  74999. function isPowerOfTwo(value) {
  75000. if (value <= 2) return true;
  75001. return (value & value - 1) === 0 && value !== 0;
  75002. }
  75003. /** Concatenates N byte arrays. */
  75004. function concat(arrays) {
  75005. var totalByteLength = 0;
  75006. for (var array of arrays) {
  75007. totalByteLength += array.byteLength;
  75008. }
  75009. var result = new Uint8Array(totalByteLength);
  75010. var byteOffset = 0;
  75011. for (var _array of arrays) {
  75012. result.set(_array, byteOffset);
  75013. byteOffset += _array.byteLength;
  75014. }
  75015. return result;
  75016. }
  75017. };
  75018. //
  75019. // DataTexture and Data3DTexture parsing.
  75020. var FORMAT_MAP = {
  75021. [Ae]: RGBAFormat,
  75022. [pe]: RGBAFormat,
  75023. [Ot]: RGBAFormat,
  75024. [Ft]: RGBAFormat,
  75025. [de]: RGFormat,
  75026. [se]: RGFormat,
  75027. [yt]: RGFormat,
  75028. [dt]: RGFormat,
  75029. [xe]: RedFormat,
  75030. [$t]: RedFormat,
  75031. [gt]: RedFormat,
  75032. [ct]: RedFormat
  75033. };
  75034. var TYPE_MAP = {
  75035. [Ae]: FloatType,
  75036. [pe]: HalfFloatType,
  75037. [Ot]: UnsignedByteType,
  75038. [Ft]: UnsignedByteType,
  75039. [de]: FloatType,
  75040. [se]: HalfFloatType,
  75041. [yt]: UnsignedByteType,
  75042. [dt]: UnsignedByteType,
  75043. [xe]: FloatType,
  75044. [$t]: HalfFloatType,
  75045. [gt]: UnsignedByteType,
  75046. [ct]: UnsignedByteType
  75047. };
  75048. var ENCODING_MAP = {
  75049. [Ft]: sRGBEncoding,
  75050. [dt]: sRGBEncoding,
  75051. [gt]: sRGBEncoding
  75052. };
  75053. function createDataTexture(_x) {
  75054. return _createDataTexture.apply(this, arguments);
  75055. }
  75056. function _createDataTexture() {
  75057. _createDataTexture = _asyncToGenerator(function* (container) {
  75058. var {
  75059. vkFormat,
  75060. pixelWidth,
  75061. pixelHeight,
  75062. pixelDepth
  75063. } = container;
  75064. if (FORMAT_MAP[vkFormat] === undefined) {
  75065. throw new Error('THREE.KTX2Loader: Unsupported vkFormat.');
  75066. }
  75067. var level = container.levels[0];
  75068. var levelData;
  75069. var view;
  75070. if (container.supercompressionScheme === t) {
  75071. levelData = level.levelData;
  75072. } else if (container.supercompressionScheme === n$1) {
  75073. if (!_zstd) {
  75074. _zstd = new Promise( /*#__PURE__*/function () {
  75075. var _ref2 = _asyncToGenerator(function* (resolve) {
  75076. var zstd = new ZSTDDecoder();
  75077. yield zstd.init();
  75078. resolve(zstd);
  75079. });
  75080. return function (_x2) {
  75081. return _ref2.apply(this, arguments);
  75082. };
  75083. }());
  75084. }
  75085. levelData = (yield _zstd).decode(level.levelData, level.uncompressedByteLength);
  75086. } else {
  75087. throw new Error('THREE.KTX2Loader: Unsupported supercompressionScheme.');
  75088. }
  75089. if (TYPE_MAP[vkFormat] === FloatType) {
  75090. view = new Float32Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Float32Array.BYTES_PER_ELEMENT);
  75091. } else if (TYPE_MAP[vkFormat] === HalfFloatType) {
  75092. view = new Uint16Array(levelData.buffer, levelData.byteOffset, levelData.byteLength / Uint16Array.BYTES_PER_ELEMENT);
  75093. } else {
  75094. view = levelData;
  75095. }
  75096. //
  75097. var texture = pixelDepth === 0 ? new DataTexture(view, pixelWidth, pixelHeight) : new Data3DTexture(view, pixelWidth, pixelHeight, pixelDepth);
  75098. texture.type = TYPE_MAP[vkFormat];
  75099. texture.format = FORMAT_MAP[vkFormat];
  75100. texture.encoding = ENCODING_MAP[vkFormat] || LinearEncoding;
  75101. texture.needsUpdate = true;
  75102. //
  75103. return Promise.resolve(texture);
  75104. });
  75105. return _createDataTexture.apply(this, arguments);
  75106. }
  75107. // This file is part of meshoptimizer library and is distributed under the terms of MIT License.
  75108. // Copyright (C) 2016-2020, by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
  75109. var MeshoptDecoder = function () {
  75110. "use strict";
  75111. // Built with clang version 11.0.0 (https://github.com/llvm/llvm-project.git 0160ad802e899c2922bc9b29564080c22eb0908c)
  75112. // Built from meshoptimizer 0.14
  75113. var wasm_base = "B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB";
  75114. var wasm_simd = "B9h9z9tFBBBFiI9gBB9gLaaaaaFa9gEaaaB9gFaFaEMcBBFBFFGGGEILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBOn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBNI9z9iqlBVc+N9IcIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMk8lLbaE97F9+FaL978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAeDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAeDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAeDeBJAiCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPAPDQBFGENVcMILKOSQfbHeD8dBh+BsxoxoUwN0AeD8dFhxoUwkwk+gUa0sHnhTkAnsHnhNkAnsHn7CgFZHiCEWCxkUUBJDBEBAiCx+YUUBJDBBBHeAeDQBBBBBBBBBBBBBBBBAnhAk7CgFZHiCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAeDeBJAiCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBReCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBH8ZCFD9tA8ZAPD9OD9hD9RH8ZDQBTFtGmEYIPLdKeOnHpAIAQJDBIBHyCFD9tAyAPD9OD9hD9RHyAIASJDBIBH8cCFD9tA8cAPD9OD9hD9RH8cDQBTFtGmEYIPLdKeOnH8dDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAeD9uHeDyBjGBAEAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeApA8dDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNiV8ZcpMyS8cQ8df8eb8fHdAyA8cDQNiV8ZcpMyS8cQ8df8eb8fH8ZDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJHIAeAdA8ZDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHeDyBjGBAIAGJHIAeAPAPDQILKOILKOILKOILKOD9uHeDyBjGBAIAGJHIAeAPAPDQNVcMNVcMNVcMNVcMD9uHeDyBjGBAIAGJHIAeAPAPDQSQfbSQfbSQfbSQfbD9uHeDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/dLEK97FaF97GXGXAGCI9HQBAF9FQFCBRGEXABABDBBBHECiD+rFCiD+sFD/6FHIAECND+rFCiD+sFD/6FAID/gFAECTD+rFCiD+sFD/6FHLD/gFD/kFD/lFHKCBDtD+2FHOAICUUUU94DtHND9OD9RD/kFHI9DBB/+hDYAIAID/mFAKAKD/mFALAOALAND9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHLD/mF9DBBX9LDYHOD/kFCgFDtD9OAECUUU94DtD9OD9QAIALD/mFAOD/kFCND+rFCU/+EDtD9OD9QAKALD/mFAOD/kFCTD+rFCUU/8ODtD9OD9QDMBBABCTJRBAGCIJHGAF9JQBSGMMAF9FQBCBRGEXABCTJHVAVDBBBHECBDtHOCUU98D8cFCUU98D8cEHND9OABDBBBHKAEDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAKAEDQBFGENVcMTtmYi8ZpyHECTD+sFD/6FHID/gFAECTD+rFCTD+sFD/6FHLD/gFD/kFD/lFHE9DB/+g6DYALAEAOD+2FHOALCUUUU94DtHcD9OD9RD/kFHLALD/mFAEAED/mFAIAOAIAcD9OD9RD/kFHEAED/mFD/kFD/kFD/jFD/nFHID/mF9DBBX9LDYHOD/kFCTD+rFALAID/mFAOD/kFCggEDtD9OD9QHLAEAID/mFAOD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHEDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAKAND9OALAEDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM/hEIGaF97FaL978jUUUUBCTlREGXAF9FQBCBRIEXAEABDBBBHLABCTJHKDBBBHODQILKOSQfbPden8c8d8e8fHNCTD+sFHVCID+rFDMIBAB9DBBU8/DY9D/zI818/DYAVCEDtD9QD/6FD/nFHVALAODQBFGENVcMTtmYi8ZpyHLCTD+rFCTD+sFD/6FD/mFHOAOD/mFAVALCTD+sFD/6FD/mFHcAcD/mFAVANCTD+rFCTD+sFD/6FD/mFHNAND/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHVD/mF9DBBX9LDYHLD/kFCggEDtHMD9OAcAVD/mFALD/kFCTD+rFD9QHcANAVD/mFALD/kFCTD+rFAOAVD/mFALD/kFAMD9OD9QHVDQBFTtGEmYILPdKOenHLD8dBAEDBIBDyB+t+J83EBABCNJALD8dFAEDBIBDyF+t+J83EBAKAcAVDQNVi8ZcMpySQ8c8dfb8e8fHVD8dBAEDBIBDyG+t+J83EBABCiJAVD8dFAEDBIBDyE+t+J83EBABCAJRBAICIJHIAF9JQBMMM9jFF97GXAGCGrAF9sHG9FQBCBRFEXABABDBBBHECND+rFCND+sFD/6FAECiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBABCTJRBAFCIJHFAG9JQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB";
  75115. // Uses bulk-memory and simd extensions
  75116. var detector = new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 4, 1, 96, 0, 0, 3, 3, 2, 0, 0, 5, 3, 1, 0, 1, 12, 1, 0, 10, 22, 2, 12, 0, 65, 0, 65, 0, 65, 0, 252, 10, 0, 0, 11, 7, 0, 65, 0, 253, 15, 26, 11]);
  75117. // Used to unpack wasm
  75118. var wasmpack = new Uint8Array([32, 0, 65, 253, 3, 1, 2, 34, 4, 106, 6, 5, 11, 8, 7, 20, 13, 33, 12, 16, 128, 9, 116, 64, 19, 113, 127, 15, 10, 21, 22, 14, 255, 66, 24, 54, 136, 107, 18, 23, 192, 26, 114, 118, 132, 17, 77, 101, 130, 144, 27, 87, 131, 44, 45, 74, 156, 154, 70, 167]);
  75119. if (typeof WebAssembly !== 'object') {
  75120. // This module requires WebAssembly to function
  75121. return {
  75122. supported: false
  75123. };
  75124. }
  75125. var wasm = wasm_base;
  75126. if (WebAssembly.validate(detector)) {
  75127. wasm = wasm_simd;
  75128. console.log("Warning: meshopt_decoder is using experimental SIMD support");
  75129. }
  75130. var instance;
  75131. var promise = WebAssembly.instantiate(unpack(wasm), {}).then(function (result) {
  75132. instance = result.instance;
  75133. instance.exports.__wasm_call_ctors();
  75134. });
  75135. function unpack(data) {
  75136. var result = new Uint8Array(data.length);
  75137. for (var i = 0; i < data.length; ++i) {
  75138. var ch = data.charCodeAt(i);
  75139. result[i] = ch > 96 ? ch - 71 : ch > 64 ? ch - 65 : ch > 47 ? ch + 4 : ch > 46 ? 63 : 62;
  75140. }
  75141. var write = 0;
  75142. for (var i = 0; i < data.length; ++i) {
  75143. result[write++] = result[i] < 60 ? wasmpack[result[i]] : (result[i] - 60) * 64 + result[++i];
  75144. }
  75145. return result.buffer.slice(0, write);
  75146. }
  75147. function decode(fun, target, count, size, source, filter) {
  75148. var sbrk = instance.exports.sbrk;
  75149. var count4 = count + 3 & ~3; // pad for SIMD filter
  75150. var tp = sbrk(count4 * size);
  75151. var sp = sbrk(source.length);
  75152. var heap = new Uint8Array(instance.exports.memory.buffer);
  75153. heap.set(source, sp);
  75154. var res = fun(tp, count, size, sp, source.length);
  75155. if (res == 0 && filter) {
  75156. filter(tp, count4, size);
  75157. }
  75158. target.set(heap.subarray(tp, tp + count * size));
  75159. sbrk(tp - sbrk(0));
  75160. if (res != 0) {
  75161. throw new Error("Malformed buffer data: " + res);
  75162. }
  75163. }
  75164. ;
  75165. var filters = {
  75166. // legacy index-based enums for glTF
  75167. 0: "",
  75168. 1: "meshopt_decodeFilterOct",
  75169. 2: "meshopt_decodeFilterQuat",
  75170. 3: "meshopt_decodeFilterExp",
  75171. // string-based enums for glTF
  75172. NONE: "",
  75173. OCTAHEDRAL: "meshopt_decodeFilterOct",
  75174. QUATERNION: "meshopt_decodeFilterQuat",
  75175. EXPONENTIAL: "meshopt_decodeFilterExp"
  75176. };
  75177. var decoders = {
  75178. // legacy index-based enums for glTF
  75179. 0: "meshopt_decodeVertexBuffer",
  75180. 1: "meshopt_decodeIndexBuffer",
  75181. 2: "meshopt_decodeIndexSequence",
  75182. // string-based enums for glTF
  75183. ATTRIBUTES: "meshopt_decodeVertexBuffer",
  75184. TRIANGLES: "meshopt_decodeIndexBuffer",
  75185. INDICES: "meshopt_decodeIndexSequence"
  75186. };
  75187. return {
  75188. ready: promise,
  75189. supported: true,
  75190. decodeVertexBuffer: function decodeVertexBuffer(target, count, size, source, filter) {
  75191. decode(instance.exports.meshopt_decodeVertexBuffer, target, count, size, source, instance.exports[filters[filter]]);
  75192. },
  75193. decodeIndexBuffer: function decodeIndexBuffer(target, count, size, source) {
  75194. decode(instance.exports.meshopt_decodeIndexBuffer, target, count, size, source);
  75195. },
  75196. decodeIndexSequence: function decodeIndexSequence(target, count, size, source) {
  75197. decode(instance.exports.meshopt_decodeIndexSequence, target, count, size, source);
  75198. },
  75199. decodeGltfBuffer: function decodeGltfBuffer(target, count, size, source, mode, filter) {
  75200. decode(instance.exports[decoders[mode]], target, count, size, source, instance.exports[filters[filter]]);
  75201. }
  75202. };
  75203. }();
  75204. var DDSLoader = function DDSLoader(manager) {
  75205. CompressedTextureLoader.call(this, manager);
  75206. };
  75207. DDSLoader.prototype = Object.assign(Object.create(CompressedTextureLoader.prototype), {
  75208. constructor: DDSLoader,
  75209. parse: function parse(buffer, loadMipmaps) {
  75210. var dds = {
  75211. mipmaps: [],
  75212. width: 0,
  75213. height: 0,
  75214. format: null,
  75215. mipmapCount: 1
  75216. };
  75217. // Adapted from @toji's DDS utils
  75218. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  75219. // All values and structures referenced from:
  75220. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75221. var DDS_MAGIC = 0x20534444;
  75222. // var DDSD_CAPS = 0x1;
  75223. // var DDSD_HEIGHT = 0x2;
  75224. // var DDSD_WIDTH = 0x4;
  75225. // var DDSD_PITCH = 0x8;
  75226. // var DDSD_PIXELFORMAT = 0x1000;
  75227. var DDSD_MIPMAPCOUNT = 0x20000;
  75228. // var DDSD_LINEARSIZE = 0x80000;
  75229. // var DDSD_DEPTH = 0x800000;
  75230. // var DDSCAPS_COMPLEX = 0x8;
  75231. // var DDSCAPS_MIPMAP = 0x400000;
  75232. // var DDSCAPS_TEXTURE = 0x1000;
  75233. var DDSCAPS2_CUBEMAP = 0x200;
  75234. var DDSCAPS2_CUBEMAP_POSITIVEX = 0x400;
  75235. var DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800;
  75236. var DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000;
  75237. var DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000;
  75238. var DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000;
  75239. var DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000;
  75240. // var DDSCAPS2_VOLUME = 0x200000;
  75241. // var DDPF_ALPHAPIXELS = 0x1;
  75242. // var DDPF_ALPHA = 0x2;
  75243. var DDPF_FOURCC = 0x4;
  75244. // var DDPF_RGB = 0x40;
  75245. // var DDPF_YUV = 0x200;
  75246. // var DDPF_LUMINANCE = 0x20000;
  75247. function fourCCToInt32(value) {
  75248. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  75249. }
  75250. function int32ToFourCC(value) {
  75251. return String.fromCharCode(value & 0xff, value >> 8 & 0xff, value >> 16 & 0xff, value >> 24 & 0xff);
  75252. }
  75253. function loadARGBMip(buffer, dataOffset, width, height) {
  75254. var dataLength = width * height * 4;
  75255. var srcBuffer = new Uint8Array(buffer, dataOffset, dataLength);
  75256. var byteArray = new Uint8Array(dataLength);
  75257. var dst = 0;
  75258. var src = 0;
  75259. for (var y = 0; y < height; y++) {
  75260. for (var x = 0; x < width; x++) {
  75261. var b = srcBuffer[src];
  75262. src++;
  75263. var g = srcBuffer[src];
  75264. src++;
  75265. var r = srcBuffer[src];
  75266. src++;
  75267. var a = srcBuffer[src];
  75268. src++;
  75269. byteArray[dst] = r;
  75270. dst++; //r
  75271. byteArray[dst] = g;
  75272. dst++; //g
  75273. byteArray[dst] = b;
  75274. dst++; //b
  75275. byteArray[dst] = a;
  75276. dst++; //a
  75277. }
  75278. }
  75279. return byteArray;
  75280. }
  75281. var FOURCC_DXT1 = fourCCToInt32('DXT1');
  75282. var FOURCC_DXT3 = fourCCToInt32('DXT3');
  75283. var FOURCC_DXT5 = fourCCToInt32('DXT5');
  75284. var FOURCC_ETC1 = fourCCToInt32('ETC1');
  75285. var headerLengthInt = 31; // The header length in 32 bit ints
  75286. // Offsets into the header array
  75287. var off_magic = 0;
  75288. var off_size = 1;
  75289. var off_flags = 2;
  75290. var off_height = 3;
  75291. var off_width = 4;
  75292. var off_mipmapCount = 7;
  75293. var off_pfFlags = 20;
  75294. var off_pfFourCC = 21;
  75295. var off_RGBBitCount = 22;
  75296. var off_RBitMask = 23;
  75297. var off_GBitMask = 24;
  75298. var off_BBitMask = 25;
  75299. var off_ABitMask = 26;
  75300. // var off_caps = 27;
  75301. var off_caps2 = 28;
  75302. // var off_caps3 = 29;
  75303. // var off_caps4 = 30;
  75304. // Parse header
  75305. var header = new Int32Array(buffer, 0, headerLengthInt);
  75306. if (header[off_magic] !== DDS_MAGIC) {
  75307. console.error('THREE.DDSLoader.parse: Invalid magic number in DDS header.');
  75308. return dds;
  75309. }
  75310. if (!header[off_pfFlags] & DDPF_FOURCC) {
  75311. console.error('THREE.DDSLoader.parse: Unsupported format, must contain a FourCC code.');
  75312. return dds;
  75313. }
  75314. var blockBytes;
  75315. var fourCC = header[off_pfFourCC];
  75316. var isRGBAUncompressed = false;
  75317. switch (fourCC) {
  75318. case FOURCC_DXT1:
  75319. blockBytes = 8;
  75320. dds.format = RGB_S3TC_DXT1_Format;
  75321. break;
  75322. case FOURCC_DXT3:
  75323. blockBytes = 16;
  75324. dds.format = RGBA_S3TC_DXT3_Format;
  75325. break;
  75326. case FOURCC_DXT5:
  75327. blockBytes = 16;
  75328. dds.format = RGBA_S3TC_DXT5_Format$1;
  75329. break;
  75330. case FOURCC_ETC1:
  75331. blockBytes = 8;
  75332. dds.format = RGB_ETC1_Format;
  75333. break;
  75334. default:
  75335. if (header[off_RGBBitCount] === 32 && header[off_RBitMask] & 0xff0000 && header[off_GBitMask] & 0xff00 && header[off_BBitMask] & 0xff && header[off_ABitMask] & 0xff000000) {
  75336. isRGBAUncompressed = true;
  75337. blockBytes = 64;
  75338. dds.format = RGBAFormat;
  75339. } else {
  75340. console.error('THREE.DDSLoader.parse: Unsupported FourCC code ', int32ToFourCC(fourCC));
  75341. return dds;
  75342. }
  75343. }
  75344. dds.mipmapCount = 1;
  75345. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  75346. dds.mipmapCount = Math.max(1, header[off_mipmapCount]);
  75347. }
  75348. var caps2 = header[off_caps2];
  75349. dds.isCubemap = caps2 & DDSCAPS2_CUBEMAP ? true : false;
  75350. if (dds.isCubemap && (!(caps2 & DDSCAPS2_CUBEMAP_POSITIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) || !(caps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) || !(caps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ))) {
  75351. console.error('THREE.DDSLoader.parse: Incomplete cubemap faces');
  75352. return dds;
  75353. }
  75354. dds.width = header[off_width];
  75355. dds.height = header[off_height];
  75356. var dataOffset = header[off_size] + 4;
  75357. // Extract mipmaps buffers
  75358. var faces = dds.isCubemap ? 6 : 1;
  75359. for (var face = 0; face < faces; face++) {
  75360. var width = dds.width;
  75361. var height = dds.height;
  75362. for (var i = 0; i < dds.mipmapCount; i++) {
  75363. if (isRGBAUncompressed) {
  75364. var byteArray = loadARGBMip(buffer, dataOffset, width, height);
  75365. var dataLength = byteArray.length;
  75366. } else {
  75367. var dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  75368. var byteArray = new Uint8Array(buffer, dataOffset, dataLength);
  75369. }
  75370. var mipmap = {
  75371. 'data': byteArray,
  75372. 'width': width,
  75373. 'height': height
  75374. };
  75375. dds.mipmaps.push(mipmap);
  75376. dataOffset += dataLength;
  75377. width = Math.max(width >> 1, 1);
  75378. height = Math.max(height >> 1, 1);
  75379. }
  75380. }
  75381. return dds;
  75382. }
  75383. });
  75384. //2022.11.11 copyfrom : https://unpkg.com/three@0.146.0/examples/jsm/loaders/GLTFLoader.js
  75385. //xzw add:----
  75386. var unknownExtensions = {};
  75387. var oldSet = MeshBasicMaterial.prototype.setValues;
  75388. MeshBasicMaterial.prototype.setValues = function (values) {
  75389. return oldSet.call(this, values);
  75390. };
  75391. class GLTFLoader extends Loader {
  75392. constructor(manager, renderer, urlPrefix) {
  75393. super(manager);
  75394. //xzw add:
  75395. this.dracoLoader = new DRACOLoader();
  75396. this.ktx2Loader = new KTX2Loader();
  75397. this.meshoptDecoder = MeshoptDecoder;
  75398. this.ddsLoader = new DDSLoader(); //这个没测过
  75399. //路径相对于index.html
  75400. this.dracoLoader.setDecoderPath(urlPrefix + 'three.js/loaders/draco/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/draco/gltf/' 版本可升级 */); //这两个路径可以自己改。在laser的环境也要放一份这个路径
  75401. this.ktx2Loader.setTranscoderPath(urlPrefix + 'three.js/loaders/basis/' /*or 'https://unpkg.com/three@0.144.0/examples/js/libs/basis/' 版本可升级 */).detectSupport(renderer);
  75402. this.pluginCallbacks = [];
  75403. this.register(function (parser) {
  75404. return new GLTFMaterialsClearcoatExtension(parser);
  75405. });
  75406. this.register(function (parser) {
  75407. return new GLTFTextureBasisUExtension(parser);
  75408. });
  75409. this.register(function (parser) {
  75410. return new GLTFTextureWebPExtension(parser);
  75411. });
  75412. this.register(function (parser) {
  75413. return new GLTFMaterialsSheenExtension(parser);
  75414. });
  75415. this.register(function (parser) {
  75416. return new GLTFMaterialsTransmissionExtension(parser);
  75417. });
  75418. this.register(function (parser) {
  75419. return new GLTFMaterialsVolumeExtension(parser);
  75420. });
  75421. this.register(function (parser) {
  75422. return new GLTFMaterialsIorExtension(parser);
  75423. });
  75424. this.register(function (parser) {
  75425. return new GLTFMaterialsEmissiveStrengthExtension(parser);
  75426. });
  75427. this.register(function (parser) {
  75428. return new GLTFMaterialsSpecularExtension(parser);
  75429. });
  75430. this.register(function (parser) {
  75431. return new GLTFMaterialsIridescenceExtension(parser);
  75432. });
  75433. this.register(function (parser) {
  75434. return new GLTFLightsExtension(parser);
  75435. });
  75436. this.register(function (parser) {
  75437. return new GLTFMeshoptCompression(parser);
  75438. });
  75439. this.register(function (parser) {
  75440. return new GLTFMeshGpuInstancing(parser);
  75441. });
  75442. }
  75443. load(url, onLoad, onProgress, onError) {
  75444. var scope = this;
  75445. var resourcePath;
  75446. if (this.resourcePath !== '') {
  75447. resourcePath = this.resourcePath;
  75448. } else if (this.path !== '') {
  75449. resourcePath = this.path;
  75450. } else {
  75451. resourcePath = LoaderUtils.extractUrlBase(url);
  75452. }
  75453. // Tells the LoadingManager to track an extra item, which resolves after
  75454. // the model is fully loaded. This means the count of items loaded will
  75455. // be incorrect, but ensures manager.onLoad() does not fire early.
  75456. this.manager.itemStart(url);
  75457. var _onError = function _onError(e) {
  75458. if (onError) {
  75459. onError(e);
  75460. } else {
  75461. console.error(e);
  75462. }
  75463. scope.manager.itemError(url);
  75464. scope.manager.itemEnd(url);
  75465. };
  75466. var loader = new FileLoader(this.manager);
  75467. loader.setPath(this.path);
  75468. loader.setResponseType('arraybuffer');
  75469. loader.setRequestHeader(this.requestHeader);
  75470. loader.setWithCredentials(this.withCredentials);
  75471. loader.load(url, function (data) {
  75472. try {
  75473. scope.parse(data, resourcePath, function (gltf) {
  75474. onLoad(gltf);
  75475. scope.manager.itemEnd(url);
  75476. }, _onError);
  75477. } catch (e) {
  75478. _onError(e);
  75479. }
  75480. }, onProgress, _onError);
  75481. }
  75482. setDRACOLoader(dracoLoader) {
  75483. this.dracoLoader = dracoLoader;
  75484. return this;
  75485. }
  75486. setDDSLoader() {
  75487. throw new Error('THREE.GLTFLoader: "MSFT_texture_dds" no longer supported. Please update to "KHR_texture_basisu".');
  75488. }
  75489. setKTX2Loader(ktx2Loader) {
  75490. this.ktx2Loader = ktx2Loader;
  75491. return this;
  75492. }
  75493. setMeshoptDecoder(meshoptDecoder) {
  75494. this.meshoptDecoder = meshoptDecoder;
  75495. return this;
  75496. }
  75497. register(callback) {
  75498. if (this.pluginCallbacks.indexOf(callback) === -1) {
  75499. this.pluginCallbacks.push(callback);
  75500. }
  75501. return this;
  75502. }
  75503. unregister(callback) {
  75504. if (this.pluginCallbacks.indexOf(callback) !== -1) {
  75505. this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(callback), 1);
  75506. }
  75507. return this;
  75508. }
  75509. parse(data, path, onLoad, onError) {
  75510. var json;
  75511. var extensions = {};
  75512. var plugins = {};
  75513. if (typeof data === 'string') {
  75514. json = JSON.parse(data);
  75515. } else if (data instanceof ArrayBuffer) {
  75516. var magic = LoaderUtils.decodeText(new Uint8Array(data, 0, 4));
  75517. if (magic === BINARY_EXTENSION_HEADER_MAGIC) {
  75518. try {
  75519. extensions[EXTENSIONS.KHR_BINARY_GLTF] = new GLTFBinaryExtension(data);
  75520. } catch (error) {
  75521. if (onError) onError(error);
  75522. return;
  75523. }
  75524. json = JSON.parse(extensions[EXTENSIONS.KHR_BINARY_GLTF].content);
  75525. } else {
  75526. json = JSON.parse(LoaderUtils.decodeText(new Uint8Array(data)));
  75527. }
  75528. } else {
  75529. json = data;
  75530. }
  75531. if (json.asset === undefined || json.asset.version[0] < 2) {
  75532. if (onError) onError(new Error('THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported.'));
  75533. return;
  75534. }
  75535. var parser = new GLTFParser(json, {
  75536. path: path || this.resourcePath || '',
  75537. crossOrigin: this.crossOrigin,
  75538. requestHeader: this.requestHeader,
  75539. manager: this.manager,
  75540. ktx2Loader: this.ktx2Loader,
  75541. meshoptDecoder: this.meshoptDecoder
  75542. });
  75543. parser.fileLoader.setRequestHeader(this.requestHeader);
  75544. for (var i = 0; i < this.pluginCallbacks.length; i++) {
  75545. var plugin = this.pluginCallbacks[i](parser);
  75546. plugins[plugin.name] = plugin;
  75547. // Workaround to avoid determining as unknown extension
  75548. // in addUnknownExtensionsToUserData().
  75549. // Remove this workaround if we move all the existing
  75550. // extension handlers to plugin system
  75551. extensions[plugin.name] = true;
  75552. }
  75553. if (json.extensionsUsed) {
  75554. for (var _i = 0; _i < json.extensionsUsed.length; ++_i) {
  75555. var extensionName = json.extensionsUsed[_i];
  75556. var extensionsRequired = json.extensionsRequired || [];
  75557. switch (extensionName) {
  75558. case EXTENSIONS.KHR_MATERIALS_UNLIT:
  75559. extensions[extensionName] = new GLTFMaterialsUnlitExtension();
  75560. break;
  75561. case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS:
  75562. extensions[extensionName] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  75563. break;
  75564. case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION:
  75565. extensions[extensionName] = new GLTFDracoMeshCompressionExtension(json, this.dracoLoader);
  75566. break;
  75567. case EXTENSIONS.KHR_TEXTURE_TRANSFORM:
  75568. extensions[extensionName] = new GLTFTextureTransformExtension();
  75569. break;
  75570. case EXTENSIONS.KHR_MESH_QUANTIZATION:
  75571. extensions[extensionName] = new GLTFMeshQuantizationExtension();
  75572. break;
  75573. default:
  75574. if (extensionsRequired.indexOf(extensionName) >= 0 && plugins[extensionName] === undefined) {
  75575. if (!unknownExtensions[extensionName]) {
  75576. console.warn('GLTFLoader: Unknown extension "' + extensionName + '".', '使用默认的KHR_materials_unlit材质');
  75577. unknownExtensions[extensionName] = 1;
  75578. }
  75579. //xzw add: 默认
  75580. json.extensionsRequired = 'KHR_materials_unlit';
  75581. json.materials = [{
  75582. extensions: {
  75583. KHR_materials_unlit: {}
  75584. },
  75585. pbrMetallicRoughness: {
  75586. baseColorFactor: [1, 1, 1, 1],
  75587. baseColorTexture: {
  75588. index: 0,
  75589. texCoord: 0
  75590. },
  75591. metallicFactor: 0,
  75592. roughnessFactor: 0.5
  75593. }
  75594. }];
  75595. extensions[json.extensionsRequired] = new GLTFMaterialsUnlitExtension();
  75596. }
  75597. /*
  75598. 如原先:
  75599. json.materials = KHR_techniques_webgl:{
  75600. technique: 0,
  75601. values:{u_diffuse:{index: 0,texCoord: 0}}
  75602. }
  75603. */
  75604. }
  75605. }
  75606. }
  75607. parser.setExtensions(extensions);
  75608. parser.setPlugins(plugins);
  75609. parser.parse(onLoad, onError);
  75610. }
  75611. parseAsync(data, path) {
  75612. var scope = this;
  75613. return new Promise(function (resolve, reject) {
  75614. scope.parse(data, path, resolve, reject);
  75615. });
  75616. }
  75617. }
  75618. /* GLTFREGISTRY */
  75619. function GLTFRegistry() {
  75620. var objects = {};
  75621. return {
  75622. get: function get(key) {
  75623. return objects[key];
  75624. },
  75625. add: function add(key, object) {
  75626. objects[key] = object;
  75627. },
  75628. remove: function remove(key) {
  75629. delete objects[key];
  75630. },
  75631. removeAll: function removeAll() {
  75632. objects = {};
  75633. }
  75634. };
  75635. }
  75636. /*********************************/
  75637. /********** EXTENSIONS ***********/
  75638. /*********************************/
  75639. var EXTENSIONS = {
  75640. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  75641. KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression',
  75642. KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual',
  75643. KHR_MATERIALS_CLEARCOAT: 'KHR_materials_clearcoat',
  75644. KHR_MATERIALS_IOR: 'KHR_materials_ior',
  75645. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness',
  75646. KHR_MATERIALS_SHEEN: 'KHR_materials_sheen',
  75647. KHR_MATERIALS_SPECULAR: 'KHR_materials_specular',
  75648. KHR_MATERIALS_TRANSMISSION: 'KHR_materials_transmission',
  75649. KHR_MATERIALS_IRIDESCENCE: 'KHR_materials_iridescence',
  75650. KHR_MATERIALS_UNLIT: 'KHR_materials_unlit',
  75651. KHR_MATERIALS_VOLUME: 'KHR_materials_volume',
  75652. KHR_TEXTURE_BASISU: 'KHR_texture_basisu',
  75653. KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform',
  75654. KHR_MESH_QUANTIZATION: 'KHR_mesh_quantization',
  75655. KHR_MATERIALS_EMISSIVE_STRENGTH: 'KHR_materials_emissive_strength',
  75656. EXT_TEXTURE_WEBP: 'EXT_texture_webp',
  75657. EXT_MESHOPT_COMPRESSION: 'EXT_meshopt_compression',
  75658. EXT_MESH_GPU_INSTANCING: 'EXT_mesh_gpu_instancing'
  75659. };
  75660. /**
  75661. * Punctual Lights Extension
  75662. *
  75663. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual
  75664. */
  75665. class GLTFLightsExtension {
  75666. constructor(parser) {
  75667. this.parser = parser;
  75668. this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL;
  75669. // Object3D instance caches
  75670. this.cache = {
  75671. refs: {},
  75672. uses: {}
  75673. };
  75674. }
  75675. _markDefs() {
  75676. var parser = this.parser;
  75677. var nodeDefs = this.parser.json.nodes || [];
  75678. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  75679. var nodeDef = nodeDefs[nodeIndex];
  75680. if (nodeDef.extensions && nodeDef.extensions[this.name] && nodeDef.extensions[this.name].light !== undefined) {
  75681. parser._addNodeRef(this.cache, nodeDef.extensions[this.name].light);
  75682. }
  75683. }
  75684. }
  75685. _loadLight(lightIndex) {
  75686. var parser = this.parser;
  75687. var cacheKey = 'light:' + lightIndex;
  75688. var dependency = parser.cache.get(cacheKey);
  75689. if (dependency) return dependency;
  75690. var json = parser.json;
  75691. var extensions = json.extensions && json.extensions[this.name] || {};
  75692. var lightDefs = extensions.lights || [];
  75693. var lightDef = lightDefs[lightIndex];
  75694. var lightNode;
  75695. var color = new Color(0xffffff);
  75696. if (lightDef.color !== undefined) color.fromArray(lightDef.color);
  75697. var range = lightDef.range !== undefined ? lightDef.range : 0;
  75698. switch (lightDef.type) {
  75699. case 'directional':
  75700. lightNode = new DirectionalLight(color);
  75701. lightNode.target.position.set(0, 0, -1);
  75702. lightNode.add(lightNode.target);
  75703. break;
  75704. case 'point':
  75705. lightNode = new PointLight(color);
  75706. lightNode.distance = range;
  75707. break;
  75708. case 'spot':
  75709. lightNode = new SpotLight(color);
  75710. lightNode.distance = range;
  75711. // Handle spotlight properties.
  75712. lightDef.spot = lightDef.spot || {};
  75713. lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0;
  75714. lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0;
  75715. lightNode.angle = lightDef.spot.outerConeAngle;
  75716. lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle;
  75717. lightNode.target.position.set(0, 0, -1);
  75718. lightNode.add(lightNode.target);
  75719. break;
  75720. default:
  75721. throw new Error('THREE.GLTFLoader: Unexpected light type: ' + lightDef.type);
  75722. }
  75723. // Some lights (e.g. spot) default to a position other than the origin. Reset the position
  75724. // here, because node-level parsing will only override position if explicitly specified.
  75725. lightNode.position.set(0, 0, 0);
  75726. lightNode.decay = 2;
  75727. if (lightDef.intensity !== undefined) lightNode.intensity = lightDef.intensity;
  75728. lightNode.name = parser.createUniqueName(lightDef.name || 'light_' + lightIndex);
  75729. dependency = Promise.resolve(lightNode);
  75730. parser.cache.add(cacheKey, dependency);
  75731. return dependency;
  75732. }
  75733. createNodeAttachment(nodeIndex) {
  75734. var self = this;
  75735. var parser = this.parser;
  75736. var json = parser.json;
  75737. var nodeDef = json.nodes[nodeIndex];
  75738. var lightDef = nodeDef.extensions && nodeDef.extensions[this.name] || {};
  75739. var lightIndex = lightDef.light;
  75740. if (lightIndex === undefined) return null;
  75741. return this._loadLight(lightIndex).then(function (light) {
  75742. return parser._getNodeRef(self.cache, lightIndex, light);
  75743. });
  75744. }
  75745. }
  75746. /**
  75747. * Unlit Materials Extension
  75748. *
  75749. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit
  75750. */
  75751. class GLTFMaterialsUnlitExtension {
  75752. constructor() {
  75753. this.name = EXTENSIONS.KHR_MATERIALS_UNLIT;
  75754. }
  75755. getMaterialType() {
  75756. return MeshBasicMaterial;
  75757. }
  75758. extendParams(materialParams, materialDef, parser) {
  75759. var pending = [];
  75760. materialParams.color = new Color(1.0, 1.0, 1.0);
  75761. materialParams.opacity = 1.0;
  75762. var metallicRoughness = materialDef.pbrMetallicRoughness;
  75763. if (metallicRoughness) {
  75764. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  75765. var array = metallicRoughness.baseColorFactor;
  75766. materialParams.color.fromArray(array);
  75767. materialParams.opacity = array[3];
  75768. }
  75769. if (metallicRoughness.baseColorTexture !== undefined) {
  75770. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding));
  75771. }
  75772. }
  75773. return Promise.all(pending);
  75774. }
  75775. }
  75776. /**
  75777. * Materials Emissive Strength Extension
  75778. *
  75779. * Specification: https://github.com/KhronosGroup/glTF/blob/5768b3ce0ef32bc39cdf1bef10b948586635ead3/extensions/2.0/Khronos/KHR_materials_emissive_strength/README.md
  75780. */
  75781. class GLTFMaterialsEmissiveStrengthExtension {
  75782. constructor(parser) {
  75783. this.parser = parser;
  75784. this.name = EXTENSIONS.KHR_MATERIALS_EMISSIVE_STRENGTH;
  75785. }
  75786. extendMaterialParams(materialIndex, materialParams) {
  75787. var parser = this.parser;
  75788. var materialDef = parser.json.materials[materialIndex] || parser.json.materials; //xzw change
  75789. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75790. return Promise.resolve();
  75791. }
  75792. var emissiveStrength = materialDef.extensions[this.name].emissiveStrength;
  75793. if (emissiveStrength !== undefined) {
  75794. materialParams.emissiveIntensity = emissiveStrength;
  75795. }
  75796. return Promise.resolve();
  75797. }
  75798. }
  75799. /**
  75800. * Clearcoat Materials Extension
  75801. *
  75802. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_clearcoat
  75803. */
  75804. class GLTFMaterialsClearcoatExtension {
  75805. constructor(parser) {
  75806. this.parser = parser;
  75807. this.name = EXTENSIONS.KHR_MATERIALS_CLEARCOAT;
  75808. }
  75809. getMaterialType(materialIndex) {
  75810. var parser = this.parser;
  75811. var materialDef = parser.json.materials[materialIndex] || parser.json.materials;
  75812. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  75813. return MeshPhysicalMaterial;
  75814. }
  75815. extendMaterialParams(materialIndex, materialParams) {
  75816. var parser = this.parser;
  75817. var materialDef = parser.json.materials[materialIndex]; //曾因这里报错加了一句 || parser.json.materials; 但是加载的图会先变白
  75818. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75819. return Promise.resolve();
  75820. }
  75821. var pending = [];
  75822. var extension = materialDef.extensions[this.name];
  75823. if (extension.clearcoatFactor !== undefined) {
  75824. materialParams.clearcoat = extension.clearcoatFactor;
  75825. }
  75826. if (extension.clearcoatTexture !== undefined) {
  75827. pending.push(parser.assignTexture(materialParams, 'clearcoatMap', extension.clearcoatTexture));
  75828. }
  75829. if (extension.clearcoatRoughnessFactor !== undefined) {
  75830. materialParams.clearcoatRoughness = extension.clearcoatRoughnessFactor;
  75831. }
  75832. if (extension.clearcoatRoughnessTexture !== undefined) {
  75833. pending.push(parser.assignTexture(materialParams, 'clearcoatRoughnessMap', extension.clearcoatRoughnessTexture));
  75834. }
  75835. if (extension.clearcoatNormalTexture !== undefined) {
  75836. pending.push(parser.assignTexture(materialParams, 'clearcoatNormalMap', extension.clearcoatNormalTexture));
  75837. if (extension.clearcoatNormalTexture.scale !== undefined) {
  75838. var scale = extension.clearcoatNormalTexture.scale;
  75839. materialParams.clearcoatNormalScale = new Vector2(scale, scale);
  75840. }
  75841. }
  75842. return Promise.all(pending);
  75843. }
  75844. }
  75845. /**
  75846. * Iridescence Materials Extension
  75847. *
  75848. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_iridescence
  75849. */
  75850. class GLTFMaterialsIridescenceExtension {
  75851. constructor(parser) {
  75852. this.parser = parser;
  75853. this.name = EXTENSIONS.KHR_MATERIALS_IRIDESCENCE;
  75854. }
  75855. getMaterialType(materialIndex) {
  75856. var parser = this.parser;
  75857. var materialDef = parser.json.materials[materialIndex];
  75858. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  75859. return MeshPhysicalMaterial;
  75860. }
  75861. extendMaterialParams(materialIndex, materialParams) {
  75862. var parser = this.parser;
  75863. var materialDef = parser.json.materials[materialIndex];
  75864. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75865. return Promise.resolve();
  75866. }
  75867. var pending = [];
  75868. var extension = materialDef.extensions[this.name];
  75869. if (extension.iridescenceFactor !== undefined) {
  75870. materialParams.iridescence = extension.iridescenceFactor;
  75871. }
  75872. if (extension.iridescenceTexture !== undefined) {
  75873. pending.push(parser.assignTexture(materialParams, 'iridescenceMap', extension.iridescenceTexture));
  75874. }
  75875. if (extension.iridescenceIor !== undefined) {
  75876. materialParams.iridescenceIOR = extension.iridescenceIor;
  75877. }
  75878. if (materialParams.iridescenceThicknessRange === undefined) {
  75879. materialParams.iridescenceThicknessRange = [100, 400];
  75880. }
  75881. if (extension.iridescenceThicknessMinimum !== undefined) {
  75882. materialParams.iridescenceThicknessRange[0] = extension.iridescenceThicknessMinimum;
  75883. }
  75884. if (extension.iridescenceThicknessMaximum !== undefined) {
  75885. materialParams.iridescenceThicknessRange[1] = extension.iridescenceThicknessMaximum;
  75886. }
  75887. if (extension.iridescenceThicknessTexture !== undefined) {
  75888. pending.push(parser.assignTexture(materialParams, 'iridescenceThicknessMap', extension.iridescenceThicknessTexture));
  75889. }
  75890. return Promise.all(pending);
  75891. }
  75892. }
  75893. /**
  75894. * Sheen Materials Extension
  75895. *
  75896. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Khronos/KHR_materials_sheen
  75897. */
  75898. class GLTFMaterialsSheenExtension {
  75899. constructor(parser) {
  75900. this.parser = parser;
  75901. this.name = EXTENSIONS.KHR_MATERIALS_SHEEN;
  75902. }
  75903. getMaterialType(materialIndex) {
  75904. var parser = this.parser;
  75905. var materialDef = parser.json.materials[materialIndex];
  75906. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  75907. return MeshPhysicalMaterial;
  75908. }
  75909. extendMaterialParams(materialIndex, materialParams) {
  75910. var parser = this.parser;
  75911. var materialDef = parser.json.materials[materialIndex];
  75912. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75913. return Promise.resolve();
  75914. }
  75915. var pending = [];
  75916. materialParams.sheenColor = new Color(0, 0, 0);
  75917. materialParams.sheenRoughness = 0;
  75918. materialParams.sheen = 1;
  75919. var extension = materialDef.extensions[this.name];
  75920. if (extension.sheenColorFactor !== undefined) {
  75921. materialParams.sheenColor.fromArray(extension.sheenColorFactor);
  75922. }
  75923. if (extension.sheenRoughnessFactor !== undefined) {
  75924. materialParams.sheenRoughness = extension.sheenRoughnessFactor;
  75925. }
  75926. if (extension.sheenColorTexture !== undefined) {
  75927. pending.push(parser.assignTexture(materialParams, 'sheenColorMap', extension.sheenColorTexture, sRGBEncoding));
  75928. }
  75929. if (extension.sheenRoughnessTexture !== undefined) {
  75930. pending.push(parser.assignTexture(materialParams, 'sheenRoughnessMap', extension.sheenRoughnessTexture));
  75931. }
  75932. return Promise.all(pending);
  75933. }
  75934. }
  75935. /**
  75936. * Transmission Materials Extension
  75937. *
  75938. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_transmission
  75939. * Draft: https://github.com/KhronosGroup/glTF/pull/1698
  75940. */
  75941. class GLTFMaterialsTransmissionExtension {
  75942. constructor(parser) {
  75943. this.parser = parser;
  75944. this.name = EXTENSIONS.KHR_MATERIALS_TRANSMISSION;
  75945. }
  75946. getMaterialType(materialIndex) {
  75947. var parser = this.parser;
  75948. var materialDef = parser.json.materials[materialIndex];
  75949. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  75950. return MeshPhysicalMaterial;
  75951. }
  75952. extendMaterialParams(materialIndex, materialParams) {
  75953. var parser = this.parser;
  75954. var materialDef = parser.json.materials[materialIndex];
  75955. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75956. return Promise.resolve();
  75957. }
  75958. var pending = [];
  75959. var extension = materialDef.extensions[this.name];
  75960. if (extension.transmissionFactor !== undefined) {
  75961. materialParams.transmission = extension.transmissionFactor;
  75962. }
  75963. if (extension.transmissionTexture !== undefined) {
  75964. pending.push(parser.assignTexture(materialParams, 'transmissionMap', extension.transmissionTexture));
  75965. }
  75966. return Promise.all(pending);
  75967. }
  75968. }
  75969. /**
  75970. * Materials Volume Extension
  75971. *
  75972. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_volume
  75973. */
  75974. class GLTFMaterialsVolumeExtension {
  75975. constructor(parser) {
  75976. this.parser = parser;
  75977. this.name = EXTENSIONS.KHR_MATERIALS_VOLUME;
  75978. }
  75979. getMaterialType(materialIndex) {
  75980. var parser = this.parser;
  75981. var materialDef = parser.json.materials[materialIndex];
  75982. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  75983. return MeshPhysicalMaterial;
  75984. }
  75985. extendMaterialParams(materialIndex, materialParams) {
  75986. var parser = this.parser;
  75987. var materialDef = parser.json.materials[materialIndex];
  75988. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  75989. return Promise.resolve();
  75990. }
  75991. var pending = [];
  75992. var extension = materialDef.extensions[this.name];
  75993. materialParams.thickness = extension.thicknessFactor !== undefined ? extension.thicknessFactor : 0;
  75994. if (extension.thicknessTexture !== undefined) {
  75995. pending.push(parser.assignTexture(materialParams, 'thicknessMap', extension.thicknessTexture));
  75996. }
  75997. materialParams.attenuationDistance = extension.attenuationDistance || Infinity;
  75998. var colorArray = extension.attenuationColor || [1, 1, 1];
  75999. materialParams.attenuationColor = new Color(colorArray[0], colorArray[1], colorArray[2]);
  76000. return Promise.all(pending);
  76001. }
  76002. }
  76003. /**
  76004. * Materials ior Extension
  76005. *
  76006. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_ior
  76007. */
  76008. class GLTFMaterialsIorExtension {
  76009. constructor(parser) {
  76010. this.parser = parser;
  76011. this.name = EXTENSIONS.KHR_MATERIALS_IOR;
  76012. }
  76013. getMaterialType(materialIndex) {
  76014. var parser = this.parser;
  76015. var materialDef = parser.json.materials[materialIndex];
  76016. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  76017. return MeshPhysicalMaterial;
  76018. }
  76019. extendMaterialParams(materialIndex, materialParams) {
  76020. var parser = this.parser;
  76021. var materialDef = parser.json.materials[materialIndex];
  76022. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  76023. return Promise.resolve();
  76024. }
  76025. var extension = materialDef.extensions[this.name];
  76026. materialParams.ior = extension.ior !== undefined ? extension.ior : 1.5;
  76027. return Promise.resolve();
  76028. }
  76029. }
  76030. /**
  76031. * Materials specular Extension
  76032. *
  76033. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_specular
  76034. */
  76035. class GLTFMaterialsSpecularExtension {
  76036. constructor(parser) {
  76037. this.parser = parser;
  76038. this.name = EXTENSIONS.KHR_MATERIALS_SPECULAR;
  76039. }
  76040. getMaterialType(materialIndex) {
  76041. var parser = this.parser;
  76042. var materialDef = parser.json.materials[materialIndex];
  76043. if (!materialDef.extensions || !materialDef.extensions[this.name]) return null;
  76044. return MeshPhysicalMaterial;
  76045. }
  76046. extendMaterialParams(materialIndex, materialParams) {
  76047. var parser = this.parser;
  76048. var materialDef = parser.json.materials[materialIndex];
  76049. if (!materialDef.extensions || !materialDef.extensions[this.name]) {
  76050. return Promise.resolve();
  76051. }
  76052. var pending = [];
  76053. var extension = materialDef.extensions[this.name];
  76054. materialParams.specularIntensity = extension.specularFactor !== undefined ? extension.specularFactor : 1.0;
  76055. if (extension.specularTexture !== undefined) {
  76056. pending.push(parser.assignTexture(materialParams, 'specularIntensityMap', extension.specularTexture));
  76057. }
  76058. var colorArray = extension.specularColorFactor || [1, 1, 1];
  76059. materialParams.specularColor = new Color(colorArray[0], colorArray[1], colorArray[2]);
  76060. if (extension.specularColorTexture !== undefined) {
  76061. pending.push(parser.assignTexture(materialParams, 'specularColorMap', extension.specularColorTexture, sRGBEncoding));
  76062. }
  76063. return Promise.all(pending);
  76064. }
  76065. }
  76066. /**
  76067. * BasisU Texture Extension
  76068. *
  76069. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_basisu
  76070. */
  76071. class GLTFTextureBasisUExtension {
  76072. constructor(parser) {
  76073. this.parser = parser;
  76074. this.name = EXTENSIONS.KHR_TEXTURE_BASISU;
  76075. }
  76076. loadTexture(textureIndex) {
  76077. var parser = this.parser;
  76078. var json = parser.json;
  76079. var textureDef = json.textures[textureIndex];
  76080. if (!textureDef.extensions || !textureDef.extensions[this.name]) {
  76081. return null;
  76082. }
  76083. var extension = textureDef.extensions[this.name];
  76084. var loader = parser.options.ktx2Loader;
  76085. if (!loader) {
  76086. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  76087. throw new Error('THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures');
  76088. } else {
  76089. // Assumes that the extension is optional and that a fallback texture is present
  76090. return null;
  76091. }
  76092. }
  76093. return parser.loadTextureImage(textureIndex, extension.source, loader);
  76094. }
  76095. }
  76096. /**
  76097. * WebP Texture Extension
  76098. *
  76099. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_texture_webp
  76100. */
  76101. class GLTFTextureWebPExtension {
  76102. constructor(parser) {
  76103. this.parser = parser;
  76104. this.name = EXTENSIONS.EXT_TEXTURE_WEBP;
  76105. this.isSupported = null;
  76106. }
  76107. loadTexture(textureIndex) {
  76108. var name = this.name;
  76109. var parser = this.parser;
  76110. var json = parser.json;
  76111. var textureDef = json.textures[textureIndex];
  76112. if (!textureDef.extensions || !textureDef.extensions[name]) {
  76113. return null;
  76114. }
  76115. var extension = textureDef.extensions[name];
  76116. var source = json.images[extension.source];
  76117. var loader = parser.textureLoader;
  76118. if (source.uri) {
  76119. var handler = parser.options.manager.getHandler(source.uri);
  76120. if (handler !== null) loader = handler;
  76121. }
  76122. return this.detectSupport().then(function (isSupported) {
  76123. if (isSupported) return parser.loadTextureImage(textureIndex, extension.source, loader);
  76124. if (json.extensionsRequired && json.extensionsRequired.indexOf(name) >= 0) {
  76125. throw new Error('THREE.GLTFLoader: WebP required by asset but unsupported.');
  76126. }
  76127. // Fall back to PNG or JPEG.
  76128. return parser.loadTexture(textureIndex);
  76129. });
  76130. }
  76131. detectSupport() {
  76132. if (!this.isSupported) {
  76133. this.isSupported = new Promise(function (resolve) {
  76134. var image = new Image();
  76135. // Lossy test image. Support for lossy images doesn't guarantee support for all
  76136. // WebP images, unfortunately.
  76137. image.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
  76138. image.onload = image.onerror = function () {
  76139. resolve(image.height === 1);
  76140. };
  76141. });
  76142. }
  76143. return this.isSupported;
  76144. }
  76145. }
  76146. /**
  76147. * meshopt BufferView Compression Extension
  76148. *
  76149. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_meshopt_compression
  76150. */
  76151. class GLTFMeshoptCompression {
  76152. constructor(parser) {
  76153. this.name = EXTENSIONS.EXT_MESHOPT_COMPRESSION;
  76154. this.parser = parser;
  76155. }
  76156. loadBufferView(index) {
  76157. var json = this.parser.json;
  76158. var bufferView = json.bufferViews[index];
  76159. if (bufferView.extensions && bufferView.extensions[this.name]) {
  76160. var extensionDef = bufferView.extensions[this.name];
  76161. var buffer = this.parser.getDependency('buffer', extensionDef.buffer);
  76162. var decoder = this.parser.options.meshoptDecoder;
  76163. if (!decoder || !decoder.supported) {
  76164. if (json.extensionsRequired && json.extensionsRequired.indexOf(this.name) >= 0) {
  76165. throw new Error('THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files');
  76166. } else {
  76167. // Assumes that the extension is optional and that fallback buffer data is present
  76168. return null;
  76169. }
  76170. }
  76171. return buffer.then(function (res) {
  76172. var byteOffset = extensionDef.byteOffset || 0;
  76173. var byteLength = extensionDef.byteLength || 0;
  76174. var count = extensionDef.count;
  76175. var stride = extensionDef.byteStride;
  76176. var source = new Uint8Array(res, byteOffset, byteLength);
  76177. if (decoder.decodeGltfBufferAsync) {
  76178. return decoder.decodeGltfBufferAsync(count, stride, source, extensionDef.mode, extensionDef.filter).then(function (res) {
  76179. return res.buffer;
  76180. });
  76181. } else {
  76182. // Support for MeshoptDecoder 0.18 or earlier, without decodeGltfBufferAsync
  76183. return decoder.ready.then(function () {
  76184. var result = new ArrayBuffer(count * stride);
  76185. decoder.decodeGltfBuffer(new Uint8Array(result), count, stride, source, extensionDef.mode, extensionDef.filter);
  76186. return result;
  76187. });
  76188. }
  76189. });
  76190. } else {
  76191. return null;
  76192. }
  76193. }
  76194. }
  76195. /**
  76196. * GPU Instancing Extension
  76197. *
  76198. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/EXT_mesh_gpu_instancing
  76199. *
  76200. */
  76201. class GLTFMeshGpuInstancing {
  76202. constructor(parser) {
  76203. this.name = EXTENSIONS.EXT_MESH_GPU_INSTANCING;
  76204. this.parser = parser;
  76205. }
  76206. createNodeMesh(nodeIndex) {
  76207. var _this = this;
  76208. var json = this.parser.json;
  76209. var nodeDef = json.nodes[nodeIndex];
  76210. if (!nodeDef.extensions || !nodeDef.extensions[this.name] || nodeDef.mesh === undefined) {
  76211. return null;
  76212. }
  76213. var meshDef = json.meshes[nodeDef.mesh];
  76214. // No Points or Lines + Instancing support yet
  76215. for (var primitive of meshDef.primitives) {
  76216. if (primitive.mode !== WEBGL_CONSTANTS.TRIANGLES && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_STRIP && primitive.mode !== WEBGL_CONSTANTS.TRIANGLE_FAN && primitive.mode !== undefined) {
  76217. return null;
  76218. }
  76219. }
  76220. var extensionDef = nodeDef.extensions[this.name];
  76221. var attributesDef = extensionDef.attributes;
  76222. // @TODO: Can we support InstancedMesh + SkinnedMesh?
  76223. var pending = [];
  76224. var attributes = {};
  76225. var _loop = function _loop(key) {
  76226. pending.push(_this.parser.getDependency('accessor', attributesDef[key]).then(accessor => {
  76227. attributes[key] = accessor;
  76228. return attributes[key];
  76229. }));
  76230. };
  76231. for (var key in attributesDef) {
  76232. _loop(key);
  76233. }
  76234. if (pending.length < 1) {
  76235. return null;
  76236. }
  76237. pending.push(this.parser.createNodeMesh(nodeIndex));
  76238. return Promise.all(pending).then(results => {
  76239. var nodeObject = results.pop();
  76240. var meshes = nodeObject.isGroup ? nodeObject.children : [nodeObject];
  76241. var count = results[0].count; // All attribute counts should be same
  76242. var instancedMeshes = [];
  76243. for (var mesh of meshes) {
  76244. // Temporal variables
  76245. var m = new Matrix4();
  76246. var p = new Vector3();
  76247. var q = new Quaternion();
  76248. var s = new Vector3(1, 1, 1);
  76249. var instancedMesh = new InstancedMesh(mesh.geometry, mesh.material, count);
  76250. for (var i = 0; i < count; i++) {
  76251. if (attributes.TRANSLATION) {
  76252. p.fromBufferAttribute(attributes.TRANSLATION, i);
  76253. }
  76254. if (attributes.ROTATION) {
  76255. q.fromBufferAttribute(attributes.ROTATION, i);
  76256. }
  76257. if (attributes.SCALE) {
  76258. s.fromBufferAttribute(attributes.SCALE, i);
  76259. }
  76260. instancedMesh.setMatrixAt(i, m.compose(p, q, s));
  76261. }
  76262. // Add instance attributes to the geometry, excluding TRS.
  76263. for (var attributeName in attributes) {
  76264. if (attributeName !== 'TRANSLATION' && attributeName !== 'ROTATION' && attributeName !== 'SCALE') {
  76265. mesh.geometry.setAttribute(attributeName, attributes[attributeName]);
  76266. }
  76267. }
  76268. // Just in case
  76269. Object3D.prototype.copy.call(instancedMesh, mesh);
  76270. // https://github.com/mrdoob/three.js/issues/18334
  76271. instancedMesh.frustumCulled = false;
  76272. this.parser.assignFinalMaterial(instancedMesh);
  76273. instancedMeshes.push(instancedMesh);
  76274. }
  76275. if (nodeObject.isGroup) {
  76276. nodeObject.clear();
  76277. nodeObject.add(...instancedMeshes);
  76278. return nodeObject;
  76279. }
  76280. return instancedMeshes[0];
  76281. });
  76282. }
  76283. }
  76284. /* BINARY EXTENSION */
  76285. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  76286. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  76287. var BINARY_EXTENSION_CHUNK_TYPES = {
  76288. JSON: 0x4E4F534A,
  76289. BIN: 0x004E4942
  76290. };
  76291. class GLTFBinaryExtension {
  76292. constructor(data) {
  76293. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  76294. this.content = null;
  76295. this.body = null;
  76296. var headerView = new DataView(data, 0, BINARY_EXTENSION_HEADER_LENGTH);
  76297. this.header = {
  76298. magic: LoaderUtils.decodeText(new Uint8Array(data.slice(0, 4))),
  76299. version: headerView.getUint32(4, true),
  76300. length: headerView.getUint32(8, true)
  76301. };
  76302. if (this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC) {
  76303. throw new Error('THREE.GLTFLoader: Unsupported glTF-Binary header.');
  76304. } else if (this.header.version < 2.0) {
  76305. throw new Error('THREE.GLTFLoader: Legacy binary file detected.');
  76306. }
  76307. var chunkContentsLength = this.header.length - BINARY_EXTENSION_HEADER_LENGTH;
  76308. var chunkView = new DataView(data, BINARY_EXTENSION_HEADER_LENGTH);
  76309. var chunkIndex = 0;
  76310. while (chunkIndex < chunkContentsLength) {
  76311. var chunkLength = chunkView.getUint32(chunkIndex, true);
  76312. chunkIndex += 4;
  76313. var chunkType = chunkView.getUint32(chunkIndex, true);
  76314. chunkIndex += 4;
  76315. if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON) {
  76316. var contentArray = new Uint8Array(data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength);
  76317. this.content = LoaderUtils.decodeText(contentArray);
  76318. } else if (chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN) {
  76319. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  76320. this.body = data.slice(byteOffset, byteOffset + chunkLength);
  76321. }
  76322. // Clients must ignore chunks with unknown types.
  76323. chunkIndex += chunkLength;
  76324. }
  76325. if (this.content === null) {
  76326. throw new Error('THREE.GLTFLoader: JSON content not found.');
  76327. }
  76328. }
  76329. }
  76330. /**
  76331. * DRACO Mesh Compression Extension
  76332. *
  76333. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  76334. */
  76335. class GLTFDracoMeshCompressionExtension {
  76336. constructor(json, dracoLoader) {
  76337. if (!dracoLoader) {
  76338. throw new Error('THREE.GLTFLoader: No DRACOLoader instance provided.');
  76339. }
  76340. this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION;
  76341. this.json = json;
  76342. this.dracoLoader = dracoLoader;
  76343. this.dracoLoader.preload();
  76344. }
  76345. decodePrimitive(primitive, parser) {
  76346. var json = this.json;
  76347. var dracoLoader = this.dracoLoader;
  76348. var bufferViewIndex = primitive.extensions[this.name].bufferView;
  76349. var gltfAttributeMap = primitive.extensions[this.name].attributes;
  76350. var threeAttributeMap = {};
  76351. var attributeNormalizedMap = {};
  76352. var attributeTypeMap = {};
  76353. for (var attributeName in gltfAttributeMap) {
  76354. var threeAttributeName = ATTRIBUTES[attributeName] || attributeName.toLowerCase();
  76355. threeAttributeMap[threeAttributeName] = gltfAttributeMap[attributeName];
  76356. }
  76357. for (var _attributeName in primitive.attributes) {
  76358. var _threeAttributeName = ATTRIBUTES[_attributeName] || _attributeName.toLowerCase();
  76359. if (gltfAttributeMap[_attributeName] !== undefined) {
  76360. var accessorDef = json.accessors[primitive.attributes[_attributeName]];
  76361. var componentType = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  76362. attributeTypeMap[_threeAttributeName] = componentType.name;
  76363. attributeNormalizedMap[_threeAttributeName] = accessorDef.normalized === true;
  76364. }
  76365. }
  76366. return parser.getDependency('bufferView', bufferViewIndex).then(function (bufferView) {
  76367. return new Promise(function (resolve) {
  76368. dracoLoader.decodeDracoFile(bufferView, function (geometry) {
  76369. for (var _attributeName2 in geometry.attributes) {
  76370. var attribute = geometry.attributes[_attributeName2];
  76371. var normalized = attributeNormalizedMap[_attributeName2];
  76372. if (normalized !== undefined) attribute.normalized = normalized;
  76373. }
  76374. resolve(geometry);
  76375. }, threeAttributeMap, attributeTypeMap);
  76376. });
  76377. });
  76378. }
  76379. }
  76380. /**
  76381. * Texture Transform Extension
  76382. *
  76383. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform
  76384. */
  76385. class GLTFTextureTransformExtension {
  76386. constructor() {
  76387. this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM;
  76388. }
  76389. extendTexture(texture, transform) {
  76390. if (transform.texCoord !== undefined) {
  76391. console.warn('THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.');
  76392. }
  76393. if (transform.offset === undefined && transform.rotation === undefined && transform.scale === undefined) {
  76394. // See https://github.com/mrdoob/three.js/issues/21819.
  76395. return texture;
  76396. }
  76397. texture = texture.clone();
  76398. if (transform.offset !== undefined) {
  76399. texture.offset.fromArray(transform.offset);
  76400. }
  76401. if (transform.rotation !== undefined) {
  76402. texture.rotation = transform.rotation;
  76403. }
  76404. if (transform.scale !== undefined) {
  76405. texture.repeat.fromArray(transform.scale);
  76406. }
  76407. texture.needsUpdate = true;
  76408. return texture;
  76409. }
  76410. }
  76411. /**
  76412. * Specular-Glossiness Extension
  76413. *
  76414. * Specification: https://github.com/KhronosGroup/glTF/tree/main/extensions/2.0/Archived/KHR_materials_pbrSpecularGlossiness
  76415. */
  76416. /**
  76417. * A sub class of StandardMaterial with some of the functionality
  76418. * changed via the `onBeforeCompile` callback
  76419. * @pailhead
  76420. */
  76421. class GLTFMeshStandardSGMaterial extends MeshStandardMaterial {
  76422. constructor(params) {
  76423. super();
  76424. this.isGLTFSpecularGlossinessMaterial = true;
  76425. //various chunks that need replacing
  76426. var specularMapParsFragmentChunk = ['#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif'].join('\n');
  76427. var glossinessMapParsFragmentChunk = ['#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif'].join('\n');
  76428. var specularMapFragmentChunk = ['vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif'].join('\n');
  76429. var glossinessMapFragmentChunk = ['float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif'].join('\n');
  76430. var lightPhysicalFragmentChunk = ['PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb * ( 1. - max( specularFactor.r, max( specularFactor.g, specularFactor.b ) ) );', 'vec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );', 'float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );', 'material.roughness = max( 1.0 - glossinessFactor, 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.', 'material.roughness += geometryRoughness;', 'material.roughness = min( material.roughness, 1.0 );', 'material.specularColor = specularFactor;'].join('\n');
  76431. var uniforms = {
  76432. specular: {
  76433. value: new Color().setHex(0xffffff)
  76434. },
  76435. glossiness: {
  76436. value: 1
  76437. },
  76438. specularMap: {
  76439. value: null
  76440. },
  76441. glossinessMap: {
  76442. value: null
  76443. }
  76444. };
  76445. this._extraUniforms = uniforms;
  76446. this.onBeforeCompile = function (shader) {
  76447. for (var uniformName in uniforms) {
  76448. shader.uniforms[uniformName] = uniforms[uniformName];
  76449. }
  76450. shader.fragmentShader = shader.fragmentShader.replace('uniform float roughness;', 'uniform vec3 specular;').replace('uniform float metalness;', 'uniform float glossiness;').replace('#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk).replace('#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk).replace('#include <roughnessmap_fragment>', specularMapFragmentChunk).replace('#include <metalnessmap_fragment>', glossinessMapFragmentChunk).replace('#include <lights_physical_fragment>', lightPhysicalFragmentChunk);
  76451. };
  76452. Object.defineProperties(this, {
  76453. specular: {
  76454. get: function get() {
  76455. return uniforms.specular.value;
  76456. },
  76457. set: function set(v) {
  76458. uniforms.specular.value = v;
  76459. }
  76460. },
  76461. specularMap: {
  76462. get: function get() {
  76463. return uniforms.specularMap.value;
  76464. },
  76465. set: function set(v) {
  76466. uniforms.specularMap.value = v;
  76467. if (v) {
  76468. this.defines.USE_SPECULARMAP = ''; // USE_UV is set by the renderer for specular maps
  76469. } else {
  76470. delete this.defines.USE_SPECULARMAP;
  76471. }
  76472. }
  76473. },
  76474. glossiness: {
  76475. get: function get() {
  76476. return uniforms.glossiness.value;
  76477. },
  76478. set: function set(v) {
  76479. uniforms.glossiness.value = v;
  76480. }
  76481. },
  76482. glossinessMap: {
  76483. get: function get() {
  76484. return uniforms.glossinessMap.value;
  76485. },
  76486. set: function set(v) {
  76487. uniforms.glossinessMap.value = v;
  76488. if (v) {
  76489. this.defines.USE_GLOSSINESSMAP = '';
  76490. this.defines.USE_UV = '';
  76491. } else {
  76492. delete this.defines.USE_GLOSSINESSMAP;
  76493. delete this.defines.USE_UV;
  76494. }
  76495. }
  76496. }
  76497. });
  76498. delete this.metalness;
  76499. delete this.roughness;
  76500. delete this.metalnessMap;
  76501. delete this.roughnessMap;
  76502. this.setValues(params);
  76503. }
  76504. copy(source) {
  76505. super.copy(source);
  76506. this.specularMap = source.specularMap;
  76507. this.specular.copy(source.specular);
  76508. this.glossinessMap = source.glossinessMap;
  76509. this.glossiness = source.glossiness;
  76510. delete this.metalness;
  76511. delete this.roughness;
  76512. delete this.metalnessMap;
  76513. delete this.roughnessMap;
  76514. return this;
  76515. }
  76516. }
  76517. class GLTFMaterialsPbrSpecularGlossinessExtension {
  76518. constructor() {
  76519. this.name = EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS;
  76520. this.specularGlossinessParams = ['color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'normalMapType', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity'];
  76521. }
  76522. getMaterialType() {
  76523. return GLTFMeshStandardSGMaterial;
  76524. }
  76525. extendParams(materialParams, materialDef, parser) {
  76526. var pbrSpecularGlossiness = materialDef.extensions[this.name];
  76527. materialParams.color = new Color(1.0, 1.0, 1.0);
  76528. materialParams.opacity = 1.0;
  76529. var pending = [];
  76530. if (Array.isArray(pbrSpecularGlossiness.diffuseFactor)) {
  76531. var array = pbrSpecularGlossiness.diffuseFactor;
  76532. materialParams.color.fromArray(array);
  76533. materialParams.opacity = array[3];
  76534. }
  76535. if (pbrSpecularGlossiness.diffuseTexture !== undefined) {
  76536. pending.push(parser.assignTexture(materialParams, 'map', pbrSpecularGlossiness.diffuseTexture, sRGBEncoding));
  76537. }
  76538. materialParams.emissive = new Color(0.0, 0.0, 0.0);
  76539. materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  76540. materialParams.specular = new Color(1.0, 1.0, 1.0);
  76541. if (Array.isArray(pbrSpecularGlossiness.specularFactor)) {
  76542. materialParams.specular.fromArray(pbrSpecularGlossiness.specularFactor);
  76543. }
  76544. if (pbrSpecularGlossiness.specularGlossinessTexture !== undefined) {
  76545. var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture;
  76546. pending.push(parser.assignTexture(materialParams, 'glossinessMap', specGlossMapDef));
  76547. pending.push(parser.assignTexture(materialParams, 'specularMap', specGlossMapDef, sRGBEncoding));
  76548. }
  76549. return Promise.all(pending);
  76550. }
  76551. createMaterial(materialParams) {
  76552. var material = new GLTFMeshStandardSGMaterial(materialParams);
  76553. material.fog = true;
  76554. material.color = materialParams.color;
  76555. material.map = materialParams.map === undefined ? null : materialParams.map;
  76556. material.lightMap = null;
  76557. material.lightMapIntensity = 1.0;
  76558. material.aoMap = materialParams.aoMap === undefined ? null : materialParams.aoMap;
  76559. material.aoMapIntensity = 1.0;
  76560. material.emissive = materialParams.emissive;
  76561. material.emissiveIntensity = materialParams.emissiveIntensity === undefined ? 1.0 : materialParams.emissiveIntensity;
  76562. material.emissiveMap = materialParams.emissiveMap === undefined ? null : materialParams.emissiveMap;
  76563. material.bumpMap = materialParams.bumpMap === undefined ? null : materialParams.bumpMap;
  76564. material.bumpScale = 1;
  76565. material.normalMap = materialParams.normalMap === undefined ? null : materialParams.normalMap;
  76566. material.normalMapType = TangentSpaceNormalMap;
  76567. if (materialParams.normalScale) material.normalScale = materialParams.normalScale;
  76568. material.displacementMap = null;
  76569. material.displacementScale = 1;
  76570. material.displacementBias = 0;
  76571. material.specularMap = materialParams.specularMap === undefined ? null : materialParams.specularMap;
  76572. material.specular = materialParams.specular;
  76573. material.glossinessMap = materialParams.glossinessMap === undefined ? null : materialParams.glossinessMap;
  76574. material.glossiness = materialParams.glossiness;
  76575. material.alphaMap = null;
  76576. material.envMap = materialParams.envMap === undefined ? null : materialParams.envMap;
  76577. material.envMapIntensity = 1.0;
  76578. return material;
  76579. }
  76580. }
  76581. /**
  76582. * Mesh Quantization Extension
  76583. *
  76584. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization
  76585. */
  76586. class GLTFMeshQuantizationExtension {
  76587. constructor() {
  76588. this.name = EXTENSIONS.KHR_MESH_QUANTIZATION;
  76589. }
  76590. }
  76591. /*********************************/
  76592. /********** INTERPOLATION ********/
  76593. /*********************************/
  76594. // Spline Interpolation
  76595. // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  76596. class GLTFCubicSplineInterpolant extends Interpolant {
  76597. constructor(parameterPositions, sampleValues, sampleSize, resultBuffer) {
  76598. super(parameterPositions, sampleValues, sampleSize, resultBuffer);
  76599. }
  76600. copySampleValue_(index) {
  76601. // Copies a sample value to the result buffer. See description of glTF
  76602. // CUBICSPLINE values layout in interpolate_() function below.
  76603. var result = this.resultBuffer,
  76604. values = this.sampleValues,
  76605. valueSize = this.valueSize,
  76606. offset = index * valueSize * 3 + valueSize;
  76607. for (var i = 0; i !== valueSize; i++) {
  76608. result[i] = values[offset + i];
  76609. }
  76610. return result;
  76611. }
  76612. interpolate_(i1, t0, t, t1) {
  76613. var result = this.resultBuffer;
  76614. var values = this.sampleValues;
  76615. var stride = this.valueSize;
  76616. var stride2 = stride * 2;
  76617. var stride3 = stride * 3;
  76618. var td = t1 - t0;
  76619. var p = (t - t0) / td;
  76620. var pp = p * p;
  76621. var ppp = pp * p;
  76622. var offset1 = i1 * stride3;
  76623. var offset0 = offset1 - stride3;
  76624. var s2 = -2 * ppp + 3 * pp;
  76625. var s3 = ppp - pp;
  76626. var s0 = 1 - s2;
  76627. var s1 = s3 - pp + p;
  76628. // Layout of keyframe output values for CUBICSPLINE animations:
  76629. // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ]
  76630. for (var i = 0; i !== stride; i++) {
  76631. var p0 = values[offset0 + i + stride]; // splineVertex_k
  76632. var m0 = values[offset0 + i + stride2] * td; // outTangent_k * (t_k+1 - t_k)
  76633. var p1 = values[offset1 + i + stride]; // splineVertex_k+1
  76634. var m1 = values[offset1 + i] * td; // inTangent_k+1 * (t_k+1 - t_k)
  76635. result[i] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1;
  76636. }
  76637. return result;
  76638. }
  76639. }
  76640. var _q = new Quaternion();
  76641. class GLTFCubicSplineQuaternionInterpolant extends GLTFCubicSplineInterpolant {
  76642. interpolate_(i1, t0, t, t1) {
  76643. var result = super.interpolate_(i1, t0, t, t1);
  76644. _q.fromArray(result).normalize().toArray(result);
  76645. return result;
  76646. }
  76647. }
  76648. /*********************************/
  76649. /********** INTERNALS ************/
  76650. /*********************************/
  76651. /* CONSTANTS */
  76652. var WEBGL_CONSTANTS = {
  76653. FLOAT: 5126,
  76654. //FLOAT_MAT2: 35674,
  76655. FLOAT_MAT3: 35675,
  76656. FLOAT_MAT4: 35676,
  76657. FLOAT_VEC2: 35664,
  76658. FLOAT_VEC3: 35665,
  76659. FLOAT_VEC4: 35666,
  76660. LINEAR: 9729,
  76661. REPEAT: 10497,
  76662. SAMPLER_2D: 35678,
  76663. POINTS: 0,
  76664. LINES: 1,
  76665. LINE_LOOP: 2,
  76666. LINE_STRIP: 3,
  76667. TRIANGLES: 4,
  76668. TRIANGLE_STRIP: 5,
  76669. TRIANGLE_FAN: 6,
  76670. UNSIGNED_BYTE: 5121,
  76671. UNSIGNED_SHORT: 5123
  76672. };
  76673. var WEBGL_COMPONENT_TYPES = {
  76674. 5120: Int8Array,
  76675. 5121: Uint8Array,
  76676. 5122: Int16Array,
  76677. 5123: Uint16Array,
  76678. 5125: Uint32Array,
  76679. 5126: Float32Array
  76680. };
  76681. var WEBGL_FILTERS = {
  76682. 9728: NearestFilter,
  76683. 9729: LinearFilter,
  76684. 9984: NearestMipmapNearestFilter,
  76685. 9985: LinearMipmapNearestFilter,
  76686. 9986: NearestMipmapLinearFilter,
  76687. 9987: LinearMipmapLinearFilter
  76688. };
  76689. var WEBGL_WRAPPINGS = {
  76690. 33071: ClampToEdgeWrapping,
  76691. 33648: MirroredRepeatWrapping,
  76692. 10497: RepeatWrapping
  76693. };
  76694. var WEBGL_TYPE_SIZES = {
  76695. 'SCALAR': 1,
  76696. 'VEC2': 2,
  76697. 'VEC3': 3,
  76698. 'VEC4': 4,
  76699. 'MAT2': 4,
  76700. 'MAT3': 9,
  76701. 'MAT4': 16
  76702. };
  76703. var ATTRIBUTES = {
  76704. POSITION: 'position',
  76705. NORMAL: 'normal',
  76706. TANGENT: 'tangent',
  76707. TEXCOORD_0: 'uv',
  76708. TEXCOORD_1: 'uv2',
  76709. COLOR_0: 'color',
  76710. WEIGHTS_0: 'skinWeight',
  76711. JOINTS_0: 'skinIndex'
  76712. };
  76713. var PATH_PROPERTIES = {
  76714. scale: 'scale',
  76715. translation: 'position',
  76716. rotation: 'quaternion',
  76717. weights: 'morphTargetInfluences'
  76718. };
  76719. var INTERPOLATION = {
  76720. CUBICSPLINE: undefined,
  76721. // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each
  76722. // keyframe track will be initialized with a default interpolation type, then modified.
  76723. LINEAR: InterpolateLinear,
  76724. STEP: InterpolateDiscrete
  76725. };
  76726. var ALPHA_MODES = {
  76727. OPAQUE: 'OPAQUE',
  76728. MASK: 'MASK',
  76729. BLEND: 'BLEND'
  76730. };
  76731. /**
  76732. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  76733. */
  76734. function createDefaultMaterial(cache) {
  76735. if (cache['DefaultMaterial'] === undefined) {
  76736. cache['DefaultMaterial'] = new MeshStandardMaterial({
  76737. color: 0xFFFFFF,
  76738. emissive: 0x000000,
  76739. metalness: 1,
  76740. roughness: 1,
  76741. transparent: false,
  76742. depthTest: true,
  76743. side: FrontSide
  76744. });
  76745. }
  76746. return cache['DefaultMaterial'];
  76747. }
  76748. function addUnknownExtensionsToUserData(knownExtensions, object, objectDef) {
  76749. // Add unknown glTF extensions to an object's userData.
  76750. for (var name in objectDef.extensions) {
  76751. if (knownExtensions[name] === undefined) {
  76752. object.userData.gltfExtensions = object.userData.gltfExtensions || {};
  76753. object.userData.gltfExtensions[name] = objectDef.extensions[name];
  76754. }
  76755. }
  76756. }
  76757. /**
  76758. * @param {Object3D|Material|BufferGeometry} object
  76759. * @param {GLTF.definition} gltfDef
  76760. */
  76761. function assignExtrasToUserData(object, gltfDef) {
  76762. if (gltfDef.extras !== undefined) {
  76763. if (typeof gltfDef.extras === 'object') {
  76764. Object.assign(object.userData, gltfDef.extras);
  76765. } else {
  76766. console.warn('THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras);
  76767. }
  76768. }
  76769. }
  76770. /**
  76771. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  76772. *
  76773. * @param {BufferGeometry} geometry
  76774. * @param {Array<GLTF.Target>} targets
  76775. * @param {GLTFParser} parser
  76776. * @return {Promise<BufferGeometry>}
  76777. */
  76778. function addMorphTargets(geometry, targets, parser) {
  76779. var hasMorphPosition = false;
  76780. var hasMorphNormal = false;
  76781. var hasMorphColor = false;
  76782. for (var i = 0, il = targets.length; i < il; i++) {
  76783. var target = targets[i];
  76784. if (target.POSITION !== undefined) hasMorphPosition = true;
  76785. if (target.NORMAL !== undefined) hasMorphNormal = true;
  76786. if (target.COLOR_0 !== undefined) hasMorphColor = true;
  76787. if (hasMorphPosition && hasMorphNormal && hasMorphColor) break;
  76788. }
  76789. if (!hasMorphPosition && !hasMorphNormal && !hasMorphColor) return Promise.resolve(geometry);
  76790. var pendingPositionAccessors = [];
  76791. var pendingNormalAccessors = [];
  76792. var pendingColorAccessors = [];
  76793. for (var _i2 = 0, _il = targets.length; _i2 < _il; _i2++) {
  76794. var _target = targets[_i2];
  76795. if (hasMorphPosition) {
  76796. var pendingAccessor = _target.POSITION !== undefined ? parser.getDependency('accessor', _target.POSITION) : geometry.attributes.position;
  76797. pendingPositionAccessors.push(pendingAccessor);
  76798. }
  76799. if (hasMorphNormal) {
  76800. var _pendingAccessor = _target.NORMAL !== undefined ? parser.getDependency('accessor', _target.NORMAL) : geometry.attributes.normal;
  76801. pendingNormalAccessors.push(_pendingAccessor);
  76802. }
  76803. if (hasMorphColor) {
  76804. var _pendingAccessor2 = _target.COLOR_0 !== undefined ? parser.getDependency('accessor', _target.COLOR_0) : geometry.attributes.color;
  76805. pendingColorAccessors.push(_pendingAccessor2);
  76806. }
  76807. }
  76808. return Promise.all([Promise.all(pendingPositionAccessors), Promise.all(pendingNormalAccessors), Promise.all(pendingColorAccessors)]).then(function (accessors) {
  76809. var morphPositions = accessors[0];
  76810. var morphNormals = accessors[1];
  76811. var morphColors = accessors[2];
  76812. if (hasMorphPosition) geometry.morphAttributes.position = morphPositions;
  76813. if (hasMorphNormal) geometry.morphAttributes.normal = morphNormals;
  76814. if (hasMorphColor) geometry.morphAttributes.color = morphColors;
  76815. geometry.morphTargetsRelative = true;
  76816. return geometry;
  76817. });
  76818. }
  76819. /**
  76820. * @param {Mesh} mesh
  76821. * @param {GLTF.Mesh} meshDef
  76822. */
  76823. function updateMorphTargets(mesh, meshDef) {
  76824. mesh.updateMorphTargets();
  76825. if (meshDef.weights !== undefined) {
  76826. for (var i = 0, il = meshDef.weights.length; i < il; i++) {
  76827. mesh.morphTargetInfluences[i] = meshDef.weights[i];
  76828. }
  76829. }
  76830. // .extras has user-defined data, so check that .extras.targetNames is an array.
  76831. if (meshDef.extras && Array.isArray(meshDef.extras.targetNames)) {
  76832. var targetNames = meshDef.extras.targetNames;
  76833. if (mesh.morphTargetInfluences.length === targetNames.length) {
  76834. mesh.morphTargetDictionary = {};
  76835. for (var _i3 = 0, _il2 = targetNames.length; _i3 < _il2; _i3++) {
  76836. mesh.morphTargetDictionary[targetNames[_i3]] = _i3;
  76837. }
  76838. } else {
  76839. console.warn('THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.');
  76840. }
  76841. }
  76842. }
  76843. function createPrimitiveKey(primitiveDef) {
  76844. var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION];
  76845. var geometryKey;
  76846. if (dracoExtension) {
  76847. geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey(dracoExtension.attributes);
  76848. } else {
  76849. geometryKey = primitiveDef.indices + ':' + createAttributesKey(primitiveDef.attributes) + ':' + primitiveDef.mode;
  76850. }
  76851. return geometryKey;
  76852. }
  76853. function createAttributesKey(attributes) {
  76854. var attributesKey = '';
  76855. var keys = Object.keys(attributes).sort();
  76856. for (var i = 0, il = keys.length; i < il; i++) {
  76857. attributesKey += keys[i] + ':' + attributes[keys[i]] + ';';
  76858. }
  76859. return attributesKey;
  76860. }
  76861. function getNormalizedComponentScale(constructor) {
  76862. // Reference:
  76863. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_mesh_quantization#encoding-quantized-data
  76864. switch (constructor) {
  76865. case Int8Array:
  76866. return 1 / 127;
  76867. case Uint8Array:
  76868. return 1 / 255;
  76869. case Int16Array:
  76870. return 1 / 32767;
  76871. case Uint16Array:
  76872. return 1 / 65535;
  76873. default:
  76874. throw new Error('THREE.GLTFLoader: Unsupported normalized accessor component type.');
  76875. }
  76876. }
  76877. function getImageURIMimeType(uri) {
  76878. if (uri.search(/\.jpe?g($|\?)/i) > 0 || uri.search(/^data\:image\/jpeg/) === 0) return 'image/jpeg';
  76879. if (uri.search(/\.webp($|\?)/i) > 0 || uri.search(/^data\:image\/webp/) === 0) return 'image/webp';
  76880. return 'image/png';
  76881. }
  76882. /* GLTF PARSER */
  76883. class GLTFParser {
  76884. constructor() {
  76885. var json = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  76886. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  76887. this.json = json;
  76888. this.extensions = {};
  76889. this.plugins = {};
  76890. this.options = options;
  76891. // loader object cache
  76892. this.cache = new GLTFRegistry();
  76893. // associations between Three.js objects and glTF elements
  76894. this.associations = new Map();
  76895. // BufferGeometry caching
  76896. this.primitiveCache = {};
  76897. // Object3D instance caches
  76898. this.meshCache = {
  76899. refs: {},
  76900. uses: {}
  76901. };
  76902. this.cameraCache = {
  76903. refs: {},
  76904. uses: {}
  76905. };
  76906. this.lightCache = {
  76907. refs: {},
  76908. uses: {}
  76909. };
  76910. this.sourceCache = {};
  76911. this.textureCache = {};
  76912. // Track node names, to ensure no duplicates
  76913. this.nodeNamesUsed = {};
  76914. // Use an ImageBitmapLoader if imageBitmaps are supported. Moves much of the
  76915. // expensive work of uploading a texture to the GPU off the main thread.
  76916. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent) === true;
  76917. var isFirefox = navigator.userAgent.indexOf('Firefox') > -1;
  76918. var firefoxVersion = isFirefox ? navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1] : -1;
  76919. // if ( typeof createImageBitmap === 'undefined' || isSafari || ( isFirefox && firefoxVersion < 98 ) ) {
  76920. this.textureLoader = new TextureLoader(this.options.manager);
  76921. /*} else {
  76922. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,改用TextureLoader by xzw
  76923. this.textureLoader = new ImageBitmapLoader( this.options.manager );
  76924. }
  76925. */
  76926. this.textureLoader.setCrossOrigin(this.options.crossOrigin);
  76927. this.textureLoader.setRequestHeader(this.options.requestHeader);
  76928. this.fileLoader = new FileLoader(this.options.manager);
  76929. this.fileLoader.setResponseType('arraybuffer');
  76930. if (this.options.crossOrigin === 'use-credentials') {
  76931. this.fileLoader.setWithCredentials(true);
  76932. }
  76933. }
  76934. setExtensions(extensions) {
  76935. this.extensions = extensions;
  76936. }
  76937. setPlugins(plugins) {
  76938. this.plugins = plugins;
  76939. }
  76940. parse(onLoad, onError) {
  76941. var parser = this;
  76942. var json = this.json;
  76943. var extensions = this.extensions;
  76944. // Clear the loader cache
  76945. this.cache.removeAll();
  76946. // Mark the special nodes/meshes in json for efficient parse
  76947. this._invokeAll(function (ext) {
  76948. return ext._markDefs && ext._markDefs();
  76949. });
  76950. Promise.all(this._invokeAll(function (ext) {
  76951. return ext.beforeRoot && ext.beforeRoot();
  76952. })).then(function () {
  76953. return Promise.all([parser.getDependencies('scene'), parser.getDependencies('animation'), parser.getDependencies('camera')]);
  76954. }).then(function (dependencies) {
  76955. var result = {
  76956. scene: dependencies[0][json.scene || 0],
  76957. scenes: dependencies[0],
  76958. animations: dependencies[1],
  76959. cameras: dependencies[2],
  76960. asset: json.asset,
  76961. parser: parser,
  76962. userData: {}
  76963. };
  76964. addUnknownExtensionsToUserData(extensions, result, json);
  76965. assignExtrasToUserData(result, json);
  76966. Promise.all(parser._invokeAll(function (ext) {
  76967. return ext.afterRoot && ext.afterRoot(result);
  76968. })).then(function () {
  76969. onLoad(result);
  76970. });
  76971. }).catch(onError);
  76972. }
  76973. /**
  76974. * Marks the special nodes/meshes in json for efficient parse.
  76975. */
  76976. _markDefs() {
  76977. var nodeDefs = this.json.nodes || [];
  76978. var skinDefs = this.json.skins || [];
  76979. var meshDefs = this.json.meshes || [];
  76980. // Nothing in the node definition indicates whether it is a Bone or an
  76981. // Object3D. Use the skins' joint references to mark bones.
  76982. for (var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex++) {
  76983. var joints = skinDefs[skinIndex].joints;
  76984. for (var i = 0, il = joints.length; i < il; i++) {
  76985. nodeDefs[joints[i]].isBone = true;
  76986. }
  76987. }
  76988. // Iterate over all nodes, marking references to shared resources,
  76989. // as well as skeleton joints.
  76990. for (var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex++) {
  76991. var nodeDef = nodeDefs[nodeIndex];
  76992. if (nodeDef.mesh !== undefined) {
  76993. this._addNodeRef(this.meshCache, nodeDef.mesh);
  76994. // Nothing in the mesh definition indicates whether it is
  76995. // a SkinnedMesh or Mesh. Use the node's mesh reference
  76996. // to mark SkinnedMesh if node has skin.
  76997. if (nodeDef.skin !== undefined) {
  76998. meshDefs[nodeDef.mesh].isSkinnedMesh = true;
  76999. }
  77000. }
  77001. if (nodeDef.camera !== undefined) {
  77002. this._addNodeRef(this.cameraCache, nodeDef.camera);
  77003. }
  77004. }
  77005. }
  77006. /**
  77007. * Counts references to shared node / Object3D resources. These resources
  77008. * can be reused, or "instantiated", at multiple nodes in the scene
  77009. * hierarchy. Mesh, Camera, and Light instances are instantiated and must
  77010. * be marked. Non-scenegraph resources (like Materials, Geometries, and
  77011. * Textures) can be reused directly and are not marked here.
  77012. *
  77013. * Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  77014. */
  77015. _addNodeRef(cache, index) {
  77016. if (index === undefined) return;
  77017. if (cache.refs[index] === undefined) {
  77018. cache.refs[index] = cache.uses[index] = 0;
  77019. }
  77020. cache.refs[index]++;
  77021. }
  77022. /** Returns a reference to a shared resource, cloning it if necessary. */
  77023. _getNodeRef(cache, index, object) {
  77024. if (cache.refs[index] <= 1) return object;
  77025. var ref = object.clone();
  77026. // Propagates mappings to the cloned object, prevents mappings on the
  77027. // original object from being lost.
  77028. var updateMappings = (original, clone) => {
  77029. var mappings = this.associations.get(original);
  77030. if (mappings != null) {
  77031. this.associations.set(clone, mappings);
  77032. }
  77033. for (var [i, child] of original.children.entries()) {
  77034. updateMappings(child, clone.children[i]);
  77035. }
  77036. };
  77037. updateMappings(object, ref);
  77038. ref.name += '_instance_' + cache.uses[index]++;
  77039. return ref;
  77040. }
  77041. _invokeOne(func) {
  77042. var extensions = Object.values(this.plugins);
  77043. extensions.push(this);
  77044. for (var i = 0; i < extensions.length; i++) {
  77045. var result = func(extensions[i]);
  77046. if (result) return result;
  77047. }
  77048. return null;
  77049. }
  77050. _invokeAll(func) {
  77051. var extensions = Object.values(this.plugins);
  77052. extensions.unshift(this);
  77053. var pending = [];
  77054. for (var i = 0; i < extensions.length; i++) {
  77055. var result = func(extensions[i]);
  77056. if (result) pending.push(result);
  77057. }
  77058. return pending;
  77059. }
  77060. /**
  77061. * Requests the specified dependency asynchronously, with caching.
  77062. * @param {string} type
  77063. * @param {number} index
  77064. * @return {Promise<Object3D|Material|THREE.Texture|AnimationClip|ArrayBuffer|Object>}
  77065. */
  77066. getDependency(type, index) {
  77067. var cacheKey = type + ':' + index;
  77068. var dependency = this.cache.get(cacheKey);
  77069. if (!dependency) {
  77070. switch (type) {
  77071. case 'scene':
  77072. dependency = this.loadScene(index);
  77073. break;
  77074. case 'node':
  77075. dependency = this.loadNode(index);
  77076. break;
  77077. case 'mesh':
  77078. dependency = this._invokeOne(function (ext) {
  77079. return ext.loadMesh && ext.loadMesh(index);
  77080. });
  77081. break;
  77082. case 'accessor':
  77083. dependency = this.loadAccessor(index);
  77084. break;
  77085. case 'bufferView':
  77086. dependency = this._invokeOne(function (ext) {
  77087. return ext.loadBufferView && ext.loadBufferView(index);
  77088. });
  77089. break;
  77090. case 'buffer':
  77091. dependency = this.loadBuffer(index);
  77092. break;
  77093. case 'material':
  77094. dependency = this._invokeOne(function (ext) {
  77095. return ext.loadMaterial && ext.loadMaterial(index);
  77096. });
  77097. break;
  77098. case 'texture':
  77099. dependency = this._invokeOne(function (ext) {
  77100. return ext.loadTexture && ext.loadTexture(index);
  77101. });
  77102. break;
  77103. case 'skin':
  77104. dependency = this.loadSkin(index);
  77105. break;
  77106. case 'animation':
  77107. dependency = this._invokeOne(function (ext) {
  77108. return ext.loadAnimation && ext.loadAnimation(index);
  77109. });
  77110. break;
  77111. case 'camera':
  77112. dependency = this.loadCamera(index);
  77113. break;
  77114. default:
  77115. throw new Error('Unknown type: ' + type);
  77116. }
  77117. this.cache.add(cacheKey, dependency);
  77118. }
  77119. return dependency;
  77120. }
  77121. /**
  77122. * Requests all dependencies of the specified type asynchronously, with caching.
  77123. * @param {string} type
  77124. * @return {Promise<Array<Object>>}
  77125. */
  77126. getDependencies(type) {
  77127. var dependencies = this.cache.get(type);
  77128. if (!dependencies) {
  77129. var parser = this;
  77130. var defs = this.json[type + (type === 'mesh' ? 'es' : 's')] || [];
  77131. dependencies = Promise.all(defs.map(function (def, index) {
  77132. return parser.getDependency(type, index);
  77133. }));
  77134. this.cache.add(type, dependencies);
  77135. }
  77136. return dependencies;
  77137. }
  77138. /**
  77139. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  77140. * @param {number} bufferIndex
  77141. * @return {Promise<ArrayBuffer>}
  77142. */
  77143. loadBuffer(bufferIndex) {
  77144. var bufferDef = this.json.buffers[bufferIndex];
  77145. var loader = this.fileLoader;
  77146. if (bufferDef.type && bufferDef.type !== 'arraybuffer') {
  77147. throw new Error('THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.');
  77148. }
  77149. // If present, GLB container is required to be the first buffer.
  77150. if (bufferDef.uri === undefined && bufferIndex === 0) {
  77151. return Promise.resolve(this.extensions[EXTENSIONS.KHR_BINARY_GLTF].body);
  77152. }
  77153. var options = this.options;
  77154. return new Promise(function (resolve, reject) {
  77155. loader.load(LoaderUtils.resolveURL(bufferDef.uri, options.path), resolve, undefined, function () {
  77156. reject(new Error('THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".'));
  77157. });
  77158. });
  77159. }
  77160. /**
  77161. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  77162. * @param {number} bufferViewIndex
  77163. * @return {Promise<ArrayBuffer>}
  77164. */
  77165. loadBufferView(bufferViewIndex) {
  77166. var bufferViewDef = this.json.bufferViews[bufferViewIndex];
  77167. return this.getDependency('buffer', bufferViewDef.buffer).then(function (buffer) {
  77168. var byteLength = bufferViewDef.byteLength || 0;
  77169. var byteOffset = bufferViewDef.byteOffset || 0;
  77170. return buffer.slice(byteOffset, byteOffset + byteLength);
  77171. });
  77172. }
  77173. /**
  77174. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  77175. * @param {number} accessorIndex
  77176. * @return {Promise<BufferAttribute|InterleavedBufferAttribute>}
  77177. */
  77178. loadAccessor(accessorIndex) {
  77179. var parser = this;
  77180. var json = this.json;
  77181. var accessorDef = this.json.accessors[accessorIndex];
  77182. if (accessorDef.bufferView === undefined && accessorDef.sparse === undefined) {
  77183. // Ignore empty accessors, which may be used to declare runtime
  77184. // information about attributes coming from another source (e.g. Draco
  77185. // compression extension).
  77186. return Promise.resolve(null);
  77187. }
  77188. var pendingBufferViews = [];
  77189. if (accessorDef.bufferView !== undefined) {
  77190. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.bufferView));
  77191. } else {
  77192. pendingBufferViews.push(null);
  77193. }
  77194. if (accessorDef.sparse !== undefined) {
  77195. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.indices.bufferView));
  77196. pendingBufferViews.push(this.getDependency('bufferView', accessorDef.sparse.values.bufferView));
  77197. }
  77198. return Promise.all(pendingBufferViews).then(function (bufferViews) {
  77199. var bufferView = bufferViews[0];
  77200. var itemSize = WEBGL_TYPE_SIZES[accessorDef.type];
  77201. var TypedArray = WEBGL_COMPONENT_TYPES[accessorDef.componentType];
  77202. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  77203. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  77204. var itemBytes = elementBytes * itemSize;
  77205. var byteOffset = accessorDef.byteOffset || 0;
  77206. var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[accessorDef.bufferView].byteStride : undefined;
  77207. var normalized = accessorDef.normalized === true;
  77208. var array, bufferAttribute;
  77209. // The buffer is not interleaved if the stride is the item size in bytes.
  77210. if (byteStride && byteStride !== itemBytes) {
  77211. // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer
  77212. // This makes sure that IBA.count reflects accessor.count properly
  77213. var ibSlice = Math.floor(byteOffset / byteStride);
  77214. var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count;
  77215. var ib = parser.cache.get(ibCacheKey);
  77216. if (!ib) {
  77217. array = new TypedArray(bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes);
  77218. // Integer parameters to IB/IBA are in array elements, not bytes.
  77219. ib = new InterleavedBuffer(array, byteStride / elementBytes);
  77220. parser.cache.add(ibCacheKey, ib);
  77221. }
  77222. bufferAttribute = new InterleavedBufferAttribute(ib, itemSize, byteOffset % byteStride / elementBytes, normalized);
  77223. } else {
  77224. if (bufferView === null) {
  77225. array = new TypedArray(accessorDef.count * itemSize);
  77226. } else {
  77227. array = new TypedArray(bufferView, byteOffset, accessorDef.count * itemSize);
  77228. }
  77229. bufferAttribute = new BufferAttribute(array, itemSize, normalized);
  77230. }
  77231. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  77232. if (accessorDef.sparse !== undefined) {
  77233. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  77234. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[accessorDef.sparse.indices.componentType];
  77235. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  77236. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  77237. var sparseIndices = new TypedArrayIndices(bufferViews[1], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices);
  77238. var sparseValues = new TypedArray(bufferViews[2], byteOffsetValues, accessorDef.sparse.count * itemSize);
  77239. if (bufferView !== null) {
  77240. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  77241. bufferAttribute = new BufferAttribute(bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized);
  77242. }
  77243. for (var i = 0, il = sparseIndices.length; i < il; i++) {
  77244. var index = sparseIndices[i];
  77245. bufferAttribute.setX(index, sparseValues[i * itemSize]);
  77246. if (itemSize >= 2) bufferAttribute.setY(index, sparseValues[i * itemSize + 1]);
  77247. if (itemSize >= 3) bufferAttribute.setZ(index, sparseValues[i * itemSize + 2]);
  77248. if (itemSize >= 4) bufferAttribute.setW(index, sparseValues[i * itemSize + 3]);
  77249. if (itemSize >= 5) throw new Error('THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.');
  77250. }
  77251. }
  77252. return bufferAttribute;
  77253. });
  77254. }
  77255. /**
  77256. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  77257. * @param {number} textureIndex
  77258. * @return {Promise<THREE.Texture>}
  77259. */
  77260. loadTexture(textureIndex) {
  77261. var json = this.json;
  77262. var options = this.options;
  77263. var textureDef = json.textures[textureIndex];
  77264. var sourceIndex = textureDef.source;
  77265. var sourceDef = json.images[sourceIndex];
  77266. var loader = this.textureLoader;
  77267. if (sourceDef.uri) {
  77268. var handler = options.manager.getHandler(sourceDef.uri);
  77269. if (handler !== null) loader = handler;
  77270. }
  77271. return this.loadTextureImage(textureIndex, sourceIndex, loader);
  77272. }
  77273. loadTextureImage(textureIndex, sourceIndex, loader) {
  77274. var parser = this;
  77275. var json = this.json;
  77276. var textureDef = json.textures[textureIndex];
  77277. var sourceDef = json.images[sourceIndex];
  77278. var cacheKey = (sourceDef.uri || sourceDef.bufferView) + ':' + textureDef.sampler;
  77279. if (this.textureCache[cacheKey]) {
  77280. // See https://github.com/mrdoob/three.js/issues/21559.
  77281. return this.textureCache[cacheKey];
  77282. }
  77283. var promise = this.loadImageSource(sourceIndex, loader).then(function (texture) {
  77284. texture.flipY = false;
  77285. texture.name = textureDef.name || sourceDef.name || '';
  77286. var samplers = json.samplers || {};
  77287. var sampler = samplers[textureDef.sampler] || {};
  77288. Potree.Utils.makeTexDontResize(texture); //add
  77289. /* //xzw 删除设置,因为已经makeTexDontResize
  77290. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || LinearFilter;
  77291. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || LinearMipmapLinearFilter;
  77292. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || RepeatWrapping;
  77293. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || RepeatWrapping;
  77294. */
  77295. parser.associations.set(texture, {
  77296. textures: textureIndex
  77297. });
  77298. return texture;
  77299. }).catch(function () {
  77300. return null;
  77301. });
  77302. this.textureCache[cacheKey] = promise;
  77303. return promise;
  77304. }
  77305. loadImageSource(sourceIndex, loader) {
  77306. var parser = this;
  77307. var json = this.json;
  77308. var options = this.options;
  77309. if (this.sourceCache[sourceIndex] !== undefined) {
  77310. return this.sourceCache[sourceIndex].then(texture => texture.clone());
  77311. }
  77312. var sourceDef = json.images[sourceIndex];
  77313. var URL = self.URL || self.webkitURL;
  77314. var sourceURI = sourceDef.uri || '';
  77315. var isObjectURL = false;
  77316. if (sourceDef.bufferView !== undefined) {
  77317. // Load binary image data from bufferView, if provided.
  77318. sourceURI = parser.getDependency('bufferView', sourceDef.bufferView).then(function (bufferView) {
  77319. isObjectURL = true;
  77320. var blob = new Blob([bufferView], {
  77321. type: sourceDef.mimeType
  77322. });
  77323. sourceURI = URL.createObjectURL(blob);
  77324. return sourceURI;
  77325. });
  77326. } else if (sourceDef.uri === undefined) {
  77327. throw new Error('THREE.GLTFLoader: Image ' + sourceIndex + ' is missing URI and bufferView');
  77328. }
  77329. var promise = Promise.resolve(sourceURI).then(function (sourceURI) {
  77330. return new Promise(function (resolve, reject) {
  77331. if (json.asset.generator == 'gltfpack 0.18') {
  77332. //4dkk场景的模型
  77333. var onLoad = resolve;
  77334. if (loader.isImageBitmapLoader === true) {
  77335. onLoad = function onLoad(imageBitmap) {
  77336. var texture = new Texture(imageBitmap);
  77337. texture.needsUpdate = true;
  77338. resolve(texture);
  77339. };
  77340. }
  77341. //loader.load( LoaderUtils.resolveURL( sourceURI, options.path ), onLoad, undefined, reject );
  77342. var url = parser.textureLoader.manager.resolveURL(sourceURI, options.path);
  77343. loader.load(url, onLoad, undefined, reject);
  77344. } else {
  77345. //为了防止chrome出现报错 The source image could not be decoded. 导致reject,重新写贴图加载方式: xzw //但不知道为何有的场景(如4dkk的)不成功
  77346. parser.textureLoader.load(sourceURI, tex => {
  77347. THREE.LinearMipmapLinearFilter; //原本:NearestMipMapNearestFilter 闪烁 有一个block文件离远了有裂缝,只能使用LinearFilter,但是这样似乎更卡,且锯齿
  77348. /* tex.minFilter = THREE.LinearFilter
  77349. tex.generateMipmaps = false */
  77350. //console.log(tex.image.width, tex.image.height)
  77351. resolve(tex);
  77352. }, null, e => {
  77353. console.log('error load tex', e);
  77354. });
  77355. }
  77356. });
  77357. }).then(function (texture) {
  77358. // Clean up resources and configure Texture.
  77359. if (isObjectURL === true) {
  77360. URL.revokeObjectURL(sourceURI);
  77361. }
  77362. texture.userData = {}; //xzw add
  77363. texture.userData.mimeType = sourceDef.mimeType || getImageURIMimeType(sourceDef.uri || sourceDef.mimeType);
  77364. return texture;
  77365. }).catch(function (error) {
  77366. console.error('THREE.GLTFLoader: Couldn\'t load texture', sourceURI);
  77367. throw error;
  77368. });
  77369. this.sourceCache[sourceIndex] = promise;
  77370. return promise;
  77371. }
  77372. /**
  77373. * Asynchronously assigns a texture to the given material parameters.
  77374. * @param {Object} materialParams
  77375. * @param {string} mapName
  77376. * @param {Object} mapDef
  77377. * @return {Promise<Texture>}
  77378. */
  77379. assignTexture(materialParams, mapName, mapDef, encoding) {
  77380. var parser = this;
  77381. return this.getDependency('texture', mapDef.index).then(function (texture) {
  77382. // Materials sample aoMap from UV set 1 and other maps from UV set 0 - this can't be configured
  77383. // However, we will copy UV set 0 to UV set 1 on demand for aoMap
  77384. if (mapDef.texCoord !== undefined && mapDef.texCoord != 0 && !(mapName === 'aoMap' && mapDef.texCoord == 1)) {
  77385. console.warn('THREE.GLTFLoader: Custom UV set ' + mapDef.texCoord + ' for texture ' + mapName + ' not yet supported.');
  77386. }
  77387. if (parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM]) {
  77388. var transform = mapDef.extensions !== undefined ? mapDef.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM] : undefined;
  77389. if (transform) {
  77390. var gltfReference = parser.associations.get(texture);
  77391. texture = parser.extensions[EXTENSIONS.KHR_TEXTURE_TRANSFORM].extendTexture(texture, transform);
  77392. parser.associations.set(texture, gltfReference);
  77393. }
  77394. }
  77395. if (encoding !== undefined) {
  77396. texture.encoding = encoding;
  77397. }
  77398. materialParams[mapName] = texture;
  77399. return texture;
  77400. });
  77401. }
  77402. /**
  77403. * Assigns final material to a Mesh, Line, or Points instance. The instance
  77404. * already has a material (generated from the glTF material options alone)
  77405. * but reuse of the same glTF material may require multiple threejs materials
  77406. * to accommodate different primitive types, defines, etc. New materials will
  77407. * be created if necessary, and reused from a cache.
  77408. * @param {Object3D} mesh Mesh, Line, or Points instance.
  77409. */
  77410. assignFinalMaterial(mesh) {
  77411. var geometry = mesh.geometry;
  77412. var material = mesh.material;
  77413. var useDerivativeTangents = geometry.attributes.tangent === undefined;
  77414. var useVertexColors = geometry.attributes.color !== undefined;
  77415. var useFlatShading = geometry.attributes.normal === undefined;
  77416. if (mesh.isPoints) {
  77417. var cacheKey = 'PointsMaterial:' + material.uuid;
  77418. var pointsMaterial = this.cache.get(cacheKey);
  77419. if (!pointsMaterial) {
  77420. pointsMaterial = new PointsMaterial();
  77421. Material.prototype.copy.call(pointsMaterial, material);
  77422. pointsMaterial.color.copy(material.color);
  77423. pointsMaterial.map = material.map;
  77424. pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px
  77425. this.cache.add(cacheKey, pointsMaterial);
  77426. }
  77427. material = pointsMaterial;
  77428. } else if (mesh.isLine) {
  77429. var _cacheKey = 'LineBasicMaterial:' + material.uuid;
  77430. var lineMaterial = this.cache.get(_cacheKey);
  77431. if (!lineMaterial) {
  77432. lineMaterial = new LineBasicMaterial();
  77433. Material.prototype.copy.call(lineMaterial, material);
  77434. lineMaterial.color.copy(material.color);
  77435. this.cache.add(_cacheKey, lineMaterial);
  77436. }
  77437. material = lineMaterial;
  77438. }
  77439. // Clone the material if it will be modified
  77440. if (useDerivativeTangents || useVertexColors || useFlatShading) {
  77441. var _cacheKey2 = 'ClonedMaterial:' + material.uuid + ':';
  77442. if (material.isGLTFSpecularGlossinessMaterial) _cacheKey2 += 'specular-glossiness:';
  77443. if (useDerivativeTangents) _cacheKey2 += 'derivative-tangents:';
  77444. if (useVertexColors) _cacheKey2 += 'vertex-colors:';
  77445. if (useFlatShading) _cacheKey2 += 'flat-shading:';
  77446. var cachedMaterial = this.cache.get(_cacheKey2);
  77447. if (!cachedMaterial) {
  77448. cachedMaterial = material.clone();
  77449. if (useVertexColors) cachedMaterial.vertexColors = true;
  77450. if (useFlatShading) cachedMaterial.flatShading = true;
  77451. if (useDerivativeTangents) {
  77452. // https://github.com/mrdoob/three.js/issues/11438#issuecomment-507003995
  77453. if (cachedMaterial.normalScale) cachedMaterial.normalScale.y *= -1;
  77454. if (cachedMaterial.clearcoatNormalScale) cachedMaterial.clearcoatNormalScale.y *= -1;
  77455. }
  77456. this.cache.add(_cacheKey2, cachedMaterial);
  77457. this.associations.set(cachedMaterial, this.associations.get(material));
  77458. }
  77459. material = cachedMaterial;
  77460. }
  77461. // workarounds for mesh and geometry
  77462. if (material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined) {
  77463. geometry.setAttribute('uv2', geometry.attributes.uv);
  77464. }
  77465. mesh.material = material;
  77466. }
  77467. getMaterialType( /* materialIndex */
  77468. ) {
  77469. return MeshStandardMaterial;
  77470. }
  77471. /**
  77472. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  77473. * @param {number} materialIndex
  77474. * @return {Promise<Material>}
  77475. */
  77476. loadMaterial(materialIndex) {
  77477. var parser = this;
  77478. var json = this.json;
  77479. var extensions = this.extensions;
  77480. var materialDef = json.materials[materialIndex];
  77481. var materialType;
  77482. var materialParams = {};
  77483. var materialExtensions = materialDef.extensions || {};
  77484. var pending = [];
  77485. if (materialExtensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS]) {
  77486. var sgExtension = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS];
  77487. materialType = BasicMaterial; //sgExtension.getMaterialType(); //xzw 改
  77488. pending.push(sgExtension.extendParams(materialParams, materialDef, parser));
  77489. } else if (materialExtensions[EXTENSIONS.KHR_MATERIALS_UNLIT]) {
  77490. var kmuExtension = extensions[EXTENSIONS.KHR_MATERIALS_UNLIT];
  77491. materialType = BasicMaterial; //kmuExtension.getMaterialType(); //xzw 改
  77492. pending.push(kmuExtension.extendParams(materialParams, materialDef, parser));
  77493. } else {
  77494. // Specification:
  77495. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  77496. var metallicRoughness = materialDef.pbrMetallicRoughness || {};
  77497. materialParams.color = new Color(1.0, 1.0, 1.0);
  77498. materialParams.opacity = 1.0;
  77499. if (Array.isArray(metallicRoughness.baseColorFactor)) {
  77500. var array = metallicRoughness.baseColorFactor;
  77501. materialParams.color.fromArray(array);
  77502. materialParams.opacity = array[3];
  77503. }
  77504. if (metallicRoughness.baseColorTexture !== undefined) {
  77505. pending.push(parser.assignTexture(materialParams, 'map', metallicRoughness.baseColorTexture, sRGBEncoding));
  77506. }
  77507. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  77508. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  77509. if (metallicRoughness.metallicRoughnessTexture !== undefined) {
  77510. pending.push(parser.assignTexture(materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture));
  77511. pending.push(parser.assignTexture(materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture));
  77512. }
  77513. materialType = this._invokeOne(function (ext) {
  77514. //return BasicMaterial //2024.7放弃使用这个,因为纯色的看上去连成一片
  77515. //kmuExtension.getMaterialType(); //xzw 改
  77516. return ext.getMaterialType && ext.getMaterialType(materialIndex);
  77517. });
  77518. pending.push(Promise.all(this._invokeAll(function (ext) {
  77519. return ext.extendMaterialParams && ext.extendMaterialParams(materialIndex, materialParams);
  77520. })));
  77521. }
  77522. if (materialDef.doubleSided === true) {
  77523. materialParams.side = DoubleSide;
  77524. }
  77525. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  77526. if (alphaMode === ALPHA_MODES.BLEND) {
  77527. materialParams.transparent = true;
  77528. // See: https://github.com/mrdoob/three.js/issues/17706
  77529. materialParams.depthWrite = false;
  77530. } else {
  77531. materialParams.transparent = false;
  77532. if (alphaMode === ALPHA_MODES.MASK) {
  77533. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  77534. }
  77535. }
  77536. if (materialDef.normalTexture !== undefined && materialType !== MeshBasicMaterial) {
  77537. pending.push(parser.assignTexture(materialParams, 'normalMap', materialDef.normalTexture));
  77538. materialParams.normalScale = new Vector2(1, 1);
  77539. if (materialDef.normalTexture.scale !== undefined) {
  77540. var scale = materialDef.normalTexture.scale;
  77541. materialParams.normalScale.set(scale, scale);
  77542. }
  77543. }
  77544. if (materialDef.occlusionTexture !== undefined && materialType !== MeshBasicMaterial) {
  77545. pending.push(parser.assignTexture(materialParams, 'aoMap', materialDef.occlusionTexture));
  77546. if (materialDef.occlusionTexture.strength !== undefined) {
  77547. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  77548. }
  77549. }
  77550. if (materialDef.emissiveFactor !== undefined && materialType !== MeshBasicMaterial) {
  77551. materialParams.emissive = new Color().fromArray(materialDef.emissiveFactor);
  77552. }
  77553. if (materialDef.emissiveTexture !== undefined && materialType !== MeshBasicMaterial) {
  77554. pending.push(parser.assignTexture(materialParams, 'emissiveMap', materialDef.emissiveTexture, sRGBEncoding));
  77555. }
  77556. return Promise.all(pending).then(function () {
  77557. var material;
  77558. if (materialType === GLTFMeshStandardSGMaterial) {
  77559. material = extensions[EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS].createMaterial(materialParams);
  77560. } else {
  77561. material = new materialType(materialParams);
  77562. }
  77563. if (materialDef.name) material.name = materialDef.name;
  77564. assignExtrasToUserData(material, materialDef);
  77565. parser.associations.set(material, {
  77566. materials: materialIndex
  77567. });
  77568. if (materialDef.extensions) addUnknownExtensionsToUserData(extensions, material, materialDef);
  77569. return material;
  77570. });
  77571. }
  77572. /** When Object3D instances are targeted by animation, they need unique names. */
  77573. createUniqueName(originalName) {
  77574. var sanitizedName = PropertyBinding.sanitizeNodeName(originalName || '');
  77575. var name = sanitizedName;
  77576. for (var i = 1; this.nodeNamesUsed[name]; ++i) {
  77577. name = sanitizedName + '_' + i;
  77578. }
  77579. this.nodeNamesUsed[name] = true;
  77580. return name;
  77581. }
  77582. /**
  77583. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  77584. *
  77585. * Creates BufferGeometries from primitives.
  77586. *
  77587. * @param {Array<GLTF.Primitive>} primitives
  77588. * @return {Promise<Array<BufferGeometry>>}
  77589. */
  77590. loadGeometries(primitives) {
  77591. var parser = this;
  77592. var extensions = this.extensions;
  77593. var cache = this.primitiveCache;
  77594. function createDracoPrimitive(primitive) {
  77595. return extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(primitive, parser).then(function (geometry) {
  77596. return addPrimitiveAttributes(geometry, primitive, parser);
  77597. });
  77598. }
  77599. var pending = [];
  77600. for (var i = 0, il = primitives.length; i < il; i++) {
  77601. var primitive = primitives[i];
  77602. var cacheKey = createPrimitiveKey(primitive);
  77603. // See if we've already created this geometry
  77604. var cached = cache[cacheKey];
  77605. if (cached) {
  77606. // Use the cached geometry if it exists
  77607. pending.push(cached.promise);
  77608. } else {
  77609. var geometryPromise = void 0;
  77610. if (primitive.extensions && primitive.extensions[EXTENSIONS.KHR_DRACO_MESH_COMPRESSION]) {
  77611. // Use DRACO geometry if available
  77612. geometryPromise = createDracoPrimitive(primitive);
  77613. } else {
  77614. // Otherwise create a new geometry
  77615. geometryPromise = addPrimitiveAttributes(new BufferGeometry(), primitive, parser);
  77616. }
  77617. // Cache this geometry
  77618. cache[cacheKey] = {
  77619. primitive: primitive,
  77620. promise: geometryPromise
  77621. };
  77622. pending.push(geometryPromise);
  77623. }
  77624. }
  77625. return Promise.all(pending);
  77626. }
  77627. /**
  77628. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  77629. * @param {number} meshIndex
  77630. * @return {Promise<Group|Mesh|SkinnedMesh>}
  77631. */
  77632. loadMesh(meshIndex) {
  77633. var parser = this;
  77634. var json = this.json;
  77635. var extensions = this.extensions;
  77636. var meshDef = json.meshes[meshIndex];
  77637. var primitives = meshDef.primitives;
  77638. var pending = [];
  77639. for (var i = 0, il = primitives.length; i < il; i++) {
  77640. var material = primitives[i].material === undefined ? createDefaultMaterial(this.cache) : this.getDependency('material', primitives[i].material);
  77641. pending.push(material);
  77642. }
  77643. pending.push(parser.loadGeometries(primitives));
  77644. return Promise.all(pending).then(function (results) {
  77645. var materials = results.slice(0, results.length - 1);
  77646. var geometries = results[results.length - 1];
  77647. var meshes = [];
  77648. for (var _i4 = 0, _il3 = geometries.length; _i4 < _il3; _i4++) {
  77649. var geometry = geometries[_i4];
  77650. var primitive = primitives[_i4];
  77651. // 1. create Mesh
  77652. var mesh = void 0;
  77653. var _material = materials[_i4];
  77654. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined) {
  77655. // .isSkinnedMesh isn't in glTF spec. See ._markDefs()
  77656. mesh = meshDef.isSkinnedMesh === true ? new SkinnedMesh(geometry, _material) : new Mesh(geometry, _material);
  77657. if (mesh.isSkinnedMesh === true && !mesh.geometry.attributes.skinWeight.normalized) {
  77658. // we normalize floating point skin weight array to fix malformed assets (see #15319)
  77659. // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs
  77660. mesh.normalizeSkinWeights();
  77661. }
  77662. if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP) {
  77663. mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleStripDrawMode);
  77664. } else if (primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN) {
  77665. mesh.geometry = toTrianglesDrawMode(mesh.geometry, TriangleFanDrawMode);
  77666. }
  77667. } else if (primitive.mode === WEBGL_CONSTANTS.LINES) {
  77668. mesh = new LineSegments(geometry, _material);
  77669. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_STRIP) {
  77670. mesh = new Line(geometry, _material);
  77671. } else if (primitive.mode === WEBGL_CONSTANTS.LINE_LOOP) {
  77672. mesh = new LineLoop(geometry, _material);
  77673. } else if (primitive.mode === WEBGL_CONSTANTS.POINTS) {
  77674. mesh = new Points(geometry, _material);
  77675. } else {
  77676. throw new Error('THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode);
  77677. }
  77678. if (Object.keys(mesh.geometry.morphAttributes).length > 0) {
  77679. updateMorphTargets(mesh, meshDef);
  77680. }
  77681. mesh.name = parser.createUniqueName(meshDef.name || 'mesh_' + meshIndex);
  77682. assignExtrasToUserData(mesh, meshDef);
  77683. if (primitive.extensions) addUnknownExtensionsToUserData(extensions, mesh, primitive);
  77684. parser.assignFinalMaterial(mesh);
  77685. meshes.push(mesh);
  77686. }
  77687. for (var _i5 = 0, _il4 = meshes.length; _i5 < _il4; _i5++) {
  77688. parser.associations.set(meshes[_i5], {
  77689. meshes: meshIndex,
  77690. primitives: _i5
  77691. });
  77692. }
  77693. if (meshes.length === 1) {
  77694. return meshes[0];
  77695. }
  77696. var group = new Group();
  77697. parser.associations.set(group, {
  77698. meshes: meshIndex
  77699. });
  77700. for (var _i6 = 0, _il5 = meshes.length; _i6 < _il5; _i6++) {
  77701. group.add(meshes[_i6]);
  77702. }
  77703. return group;
  77704. });
  77705. }
  77706. /**
  77707. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  77708. * @param {number} cameraIndex
  77709. * @return {Promise<THREE.Camera>}
  77710. */
  77711. loadCamera(cameraIndex) {
  77712. var camera;
  77713. var cameraDef = this.json.cameras[cameraIndex];
  77714. var params = cameraDef[cameraDef.type];
  77715. if (!params) {
  77716. console.warn('THREE.GLTFLoader: Missing camera parameters.');
  77717. return;
  77718. }
  77719. if (cameraDef.type === 'perspective') {
  77720. camera = new PerspectiveCamera(MathUtils.radToDeg(params.yfov), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6);
  77721. } else if (cameraDef.type === 'orthographic') {
  77722. camera = new OrthographicCamera(-params.xmag, params.xmag, params.ymag, -params.ymag, params.znear, params.zfar);
  77723. }
  77724. if (cameraDef.name) camera.name = this.createUniqueName(cameraDef.name);
  77725. assignExtrasToUserData(camera, cameraDef);
  77726. return Promise.resolve(camera);
  77727. }
  77728. /**
  77729. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  77730. * @param {number} skinIndex
  77731. * @return {Promise<Object>}
  77732. */
  77733. loadSkin(skinIndex) {
  77734. var skinDef = this.json.skins[skinIndex];
  77735. var skinEntry = {
  77736. joints: skinDef.joints
  77737. };
  77738. if (skinDef.inverseBindMatrices === undefined) {
  77739. return Promise.resolve(skinEntry);
  77740. }
  77741. return this.getDependency('accessor', skinDef.inverseBindMatrices).then(function (accessor) {
  77742. skinEntry.inverseBindMatrices = accessor;
  77743. return skinEntry;
  77744. });
  77745. }
  77746. /**
  77747. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  77748. * @param {number} animationIndex
  77749. * @return {Promise<AnimationClip>}
  77750. */
  77751. loadAnimation(animationIndex) {
  77752. var json = this.json;
  77753. var animationDef = json.animations[animationIndex];
  77754. var pendingNodes = [];
  77755. var pendingInputAccessors = [];
  77756. var pendingOutputAccessors = [];
  77757. var pendingSamplers = [];
  77758. var pendingTargets = [];
  77759. for (var i = 0, il = animationDef.channels.length; i < il; i++) {
  77760. var channel = animationDef.channels[i];
  77761. var sampler = animationDef.samplers[channel.sampler];
  77762. var target = channel.target;
  77763. var name = target.node;
  77764. var input = animationDef.parameters !== undefined ? animationDef.parameters[sampler.input] : sampler.input;
  77765. var output = animationDef.parameters !== undefined ? animationDef.parameters[sampler.output] : sampler.output;
  77766. pendingNodes.push(this.getDependency('node', name));
  77767. pendingInputAccessors.push(this.getDependency('accessor', input));
  77768. pendingOutputAccessors.push(this.getDependency('accessor', output));
  77769. pendingSamplers.push(sampler);
  77770. pendingTargets.push(target);
  77771. }
  77772. return Promise.all([Promise.all(pendingNodes), Promise.all(pendingInputAccessors), Promise.all(pendingOutputAccessors), Promise.all(pendingSamplers), Promise.all(pendingTargets)]).then(function (dependencies) {
  77773. var nodes = dependencies[0];
  77774. var inputAccessors = dependencies[1];
  77775. var outputAccessors = dependencies[2];
  77776. var samplers = dependencies[3];
  77777. var targets = dependencies[4];
  77778. var tracks = [];
  77779. var _loop2 = function _loop2() {
  77780. var node = nodes[_i7];
  77781. var inputAccessor = inputAccessors[_i7];
  77782. var outputAccessor = outputAccessors[_i7];
  77783. var sampler = samplers[_i7];
  77784. var target = targets[_i7];
  77785. if (node === undefined) return 1; // continue
  77786. node.updateMatrix();
  77787. var TypedKeyframeTrack;
  77788. switch (PATH_PROPERTIES[target.path]) {
  77789. case PATH_PROPERTIES.weights:
  77790. TypedKeyframeTrack = NumberKeyframeTrack;
  77791. break;
  77792. case PATH_PROPERTIES.rotation:
  77793. TypedKeyframeTrack = QuaternionKeyframeTrack;
  77794. break;
  77795. case PATH_PROPERTIES.position:
  77796. case PATH_PROPERTIES.scale:
  77797. default:
  77798. TypedKeyframeTrack = VectorKeyframeTrack;
  77799. break;
  77800. }
  77801. var targetName = node.name ? node.name : node.uuid;
  77802. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[sampler.interpolation] : InterpolateLinear;
  77803. var targetNames = [];
  77804. if (PATH_PROPERTIES[target.path] === PATH_PROPERTIES.weights) {
  77805. node.traverse(function (object) {
  77806. if (object.morphTargetInfluences) {
  77807. targetNames.push(object.name ? object.name : object.uuid);
  77808. }
  77809. });
  77810. } else {
  77811. targetNames.push(targetName);
  77812. }
  77813. var outputArray = outputAccessor.array;
  77814. if (outputAccessor.normalized) {
  77815. var scale = getNormalizedComponentScale(outputArray.constructor);
  77816. var scaled = new Float32Array(outputArray.length);
  77817. for (var j = 0, jl = outputArray.length; j < jl; j++) {
  77818. scaled[j] = outputArray[j] * scale;
  77819. }
  77820. outputArray = scaled;
  77821. }
  77822. for (var _j = 0, _jl = targetNames.length; _j < _jl; _j++) {
  77823. var track = new TypedKeyframeTrack(targetNames[_j] + '.' + PATH_PROPERTIES[target.path], inputAccessor.array, outputArray, interpolation);
  77824. // Override interpolation with custom factory method.
  77825. if (sampler.interpolation === 'CUBICSPLINE') {
  77826. track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline(result) {
  77827. // A CUBICSPLINE keyframe in glTF has three output values for each input value,
  77828. // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize()
  77829. // must be divided by three to get the interpolant's sampleSize argument.
  77830. var interpolantType = this instanceof QuaternionKeyframeTrack ? GLTFCubicSplineQuaternionInterpolant : GLTFCubicSplineInterpolant;
  77831. return new interpolantType(this.times, this.values, this.getValueSize() / 3, result);
  77832. };
  77833. // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants.
  77834. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true;
  77835. }
  77836. tracks.push(track);
  77837. }
  77838. };
  77839. for (var _i7 = 0, _il6 = nodes.length; _i7 < _il6; _i7++) {
  77840. if (_loop2()) continue;
  77841. }
  77842. var name = animationDef.name ? animationDef.name : 'animation_' + animationIndex;
  77843. return new AnimationClip(name, undefined, tracks);
  77844. });
  77845. }
  77846. createNodeMesh(nodeIndex) {
  77847. var json = this.json;
  77848. var parser = this;
  77849. var nodeDef = json.nodes[nodeIndex];
  77850. if (nodeDef.mesh === undefined) return null;
  77851. return parser.getDependency('mesh', nodeDef.mesh).then(function (mesh) {
  77852. var node = parser._getNodeRef(parser.meshCache, nodeDef.mesh, mesh);
  77853. // if weights are provided on the node, override weights on the mesh.
  77854. if (nodeDef.weights !== undefined) {
  77855. node.traverse(function (o) {
  77856. if (!o.isMesh) return;
  77857. for (var i = 0, il = nodeDef.weights.length; i < il; i++) {
  77858. o.morphTargetInfluences[i] = nodeDef.weights[i];
  77859. }
  77860. });
  77861. }
  77862. return node;
  77863. });
  77864. }
  77865. /**
  77866. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  77867. * @param {number} nodeIndex
  77868. * @return {Promise<Object3D>}
  77869. */
  77870. loadNode(nodeIndex) {
  77871. var json = this.json;
  77872. var extensions = this.extensions;
  77873. var parser = this;
  77874. var nodeDef = json.nodes[nodeIndex];
  77875. // reserve node's name before its dependencies, so the root has the intended name.
  77876. var nodeName = nodeDef.name ? parser.createUniqueName(nodeDef.name) : '';
  77877. return function () {
  77878. var pending = [];
  77879. var meshPromise = parser._invokeOne(function (ext) {
  77880. return ext.createNodeMesh && ext.createNodeMesh(nodeIndex);
  77881. });
  77882. if (meshPromise) {
  77883. pending.push(meshPromise);
  77884. }
  77885. if (nodeDef.camera !== undefined) {
  77886. pending.push(parser.getDependency('camera', nodeDef.camera).then(function (camera) {
  77887. return parser._getNodeRef(parser.cameraCache, nodeDef.camera, camera);
  77888. }));
  77889. }
  77890. parser._invokeAll(function (ext) {
  77891. return ext.createNodeAttachment && ext.createNodeAttachment(nodeIndex);
  77892. }).forEach(function (promise) {
  77893. pending.push(promise);
  77894. });
  77895. return Promise.all(pending);
  77896. }().then(function (objects) {
  77897. var node;
  77898. // .isBone isn't in glTF spec. See ._markDefs
  77899. if (nodeDef.isBone === true) {
  77900. node = new Bone();
  77901. } else if (objects.length > 1) {
  77902. node = new Group();
  77903. } else if (objects.length === 1) {
  77904. node = objects[0];
  77905. } else {
  77906. node = new Object3D();
  77907. }
  77908. if (node !== objects[0]) {
  77909. for (var i = 0, il = objects.length; i < il; i++) {
  77910. node.add(objects[i]);
  77911. }
  77912. }
  77913. if (nodeDef.name) {
  77914. node.userData.name = nodeDef.name;
  77915. node.name = nodeName;
  77916. }
  77917. assignExtrasToUserData(node, nodeDef);
  77918. if (nodeDef.extensions) addUnknownExtensionsToUserData(extensions, node, nodeDef);
  77919. if (nodeDef.matrix !== undefined) {
  77920. var matrix = new Matrix4();
  77921. matrix.fromArray(nodeDef.matrix);
  77922. node.applyMatrix4(matrix);
  77923. } else {
  77924. if (nodeDef.translation !== undefined) {
  77925. node.position.fromArray(nodeDef.translation);
  77926. }
  77927. if (nodeDef.rotation !== undefined) {
  77928. node.quaternion.fromArray(nodeDef.rotation);
  77929. }
  77930. if (nodeDef.scale !== undefined) {
  77931. node.scale.fromArray(nodeDef.scale);
  77932. }
  77933. }
  77934. if (!parser.associations.has(node)) {
  77935. parser.associations.set(node, {});
  77936. }
  77937. parser.associations.get(node).nodes = nodeIndex;
  77938. return node;
  77939. });
  77940. }
  77941. /**
  77942. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  77943. * @param {number} sceneIndex
  77944. * @return {Promise<Group>}
  77945. */
  77946. loadScene(sceneIndex) {
  77947. var json = this.json;
  77948. var extensions = this.extensions;
  77949. var sceneDef = this.json.scenes[sceneIndex];
  77950. var parser = this;
  77951. // Loader returns Group, not Scene.
  77952. // See: https://github.com/mrdoob/three.js/issues/18342#issuecomment-578981172
  77953. var scene = new Group();
  77954. if (sceneDef.name) scene.name = parser.createUniqueName(sceneDef.name);
  77955. assignExtrasToUserData(scene, sceneDef);
  77956. if (sceneDef.extensions) addUnknownExtensionsToUserData(extensions, scene, sceneDef);
  77957. var nodeIds = sceneDef.nodes || [];
  77958. var pending = [];
  77959. for (var i = 0, il = nodeIds.length; i < il; i++) {
  77960. pending.push(buildNodeHierarchy(nodeIds[i], scene, json, parser));
  77961. }
  77962. return Promise.all(pending).then(function () {
  77963. // Removes dangling associations, associations that reference a node that
  77964. // didn't make it into the scene.
  77965. var reduceAssociations = node => {
  77966. var reducedAssociations = new Map();
  77967. for (var [key, value] of parser.associations) {
  77968. if (key instanceof Material || key instanceof Texture) {
  77969. reducedAssociations.set(key, value);
  77970. }
  77971. }
  77972. node.traverse(node => {
  77973. var mappings = parser.associations.get(node);
  77974. if (mappings != null) {
  77975. reducedAssociations.set(node, mappings);
  77976. }
  77977. });
  77978. return reducedAssociations;
  77979. };
  77980. parser.associations = reduceAssociations(scene);
  77981. return scene;
  77982. });
  77983. }
  77984. }
  77985. function buildNodeHierarchy(nodeId, parentObject, json, parser) {
  77986. var nodeDef = json.nodes[nodeId];
  77987. return parser.getDependency('node', nodeId).then(function (node) {
  77988. if (nodeDef.skin === undefined) return node;
  77989. // build skeleton here as well
  77990. var skinEntry;
  77991. return parser.getDependency('skin', nodeDef.skin).then(function (skin) {
  77992. skinEntry = skin;
  77993. var pendingJoints = [];
  77994. for (var i = 0, il = skinEntry.joints.length; i < il; i++) {
  77995. pendingJoints.push(parser.getDependency('node', skinEntry.joints[i]));
  77996. }
  77997. return Promise.all(pendingJoints);
  77998. }).then(function (jointNodes) {
  77999. node.traverse(function (mesh) {
  78000. if (!mesh.isMesh) return;
  78001. var bones = [];
  78002. var boneInverses = [];
  78003. for (var j = 0, jl = jointNodes.length; j < jl; j++) {
  78004. var jointNode = jointNodes[j];
  78005. if (jointNode) {
  78006. bones.push(jointNode);
  78007. var mat = new Matrix4();
  78008. if (skinEntry.inverseBindMatrices !== undefined) {
  78009. mat.fromArray(skinEntry.inverseBindMatrices.array, j * 16);
  78010. }
  78011. boneInverses.push(mat);
  78012. } else {
  78013. console.warn('THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[j]);
  78014. }
  78015. }
  78016. mesh.bind(new Skeleton(bones, boneInverses), mesh.matrixWorld);
  78017. });
  78018. return node;
  78019. });
  78020. }).then(function (node) {
  78021. // build node hierachy
  78022. parentObject.add(node);
  78023. var pending = [];
  78024. if (nodeDef.children) {
  78025. var children = nodeDef.children;
  78026. for (var i = 0, il = children.length; i < il; i++) {
  78027. var child = children[i];
  78028. pending.push(buildNodeHierarchy(child, node, json, parser));
  78029. }
  78030. }
  78031. return Promise.all(pending);
  78032. });
  78033. }
  78034. /**
  78035. * @param {BufferGeometry} geometry
  78036. * @param {GLTF.Primitive} primitiveDef
  78037. * @param {GLTFParser} parser
  78038. */
  78039. function computeBounds(geometry, primitiveDef, parser) {
  78040. var attributes = primitiveDef.attributes;
  78041. var box = new Box3();
  78042. if (attributes.POSITION !== undefined) {
  78043. var accessor = parser.json.accessors[attributes.POSITION];
  78044. var min = accessor.min;
  78045. var max = accessor.max;
  78046. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  78047. if (min !== undefined && max !== undefined) {
  78048. box.set(new Vector3(min[0], min[1], min[2]), new Vector3(max[0], max[1], max[2]));
  78049. if (accessor.normalized) {
  78050. var boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[accessor.componentType]);
  78051. box.min.multiplyScalar(boxScale);
  78052. box.max.multiplyScalar(boxScale);
  78053. }
  78054. } else {
  78055. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  78056. return;
  78057. }
  78058. } else {
  78059. return;
  78060. }
  78061. var targets = primitiveDef.targets;
  78062. if (targets !== undefined) {
  78063. var maxDisplacement = new Vector3();
  78064. var vector = new Vector3();
  78065. for (var i = 0, il = targets.length; i < il; i++) {
  78066. var target = targets[i];
  78067. if (target.POSITION !== undefined) {
  78068. var _accessor = parser.json.accessors[target.POSITION];
  78069. var _min = _accessor.min;
  78070. var _max = _accessor.max;
  78071. // glTF requires 'min' and 'max', but VRM (which extends glTF) currently ignores that requirement.
  78072. if (_min !== undefined && _max !== undefined) {
  78073. // we need to get max of absolute components because target weight is [-1,1]
  78074. vector.setX(Math.max(Math.abs(_min[0]), Math.abs(_max[0])));
  78075. vector.setY(Math.max(Math.abs(_min[1]), Math.abs(_max[1])));
  78076. vector.setZ(Math.max(Math.abs(_min[2]), Math.abs(_max[2])));
  78077. if (_accessor.normalized) {
  78078. var _boxScale = getNormalizedComponentScale(WEBGL_COMPONENT_TYPES[_accessor.componentType]);
  78079. vector.multiplyScalar(_boxScale);
  78080. }
  78081. // Note: this assumes that the sum of all weights is at most 1. This isn't quite correct - it's more conservative
  78082. // to assume that each target can have a max weight of 1. However, for some use cases - notably, when morph targets
  78083. // are used to implement key-frame animations and as such only two are active at a time - this results in very large
  78084. // boxes. So for now we make a box that's sometimes a touch too small but is hopefully mostly of reasonable size.
  78085. maxDisplacement.max(vector);
  78086. } else {
  78087. console.warn('THREE.GLTFLoader: Missing min/max properties for accessor POSITION.');
  78088. }
  78089. }
  78090. }
  78091. // As per comment above this box isn't conservative, but has a reasonable size for a very large number of morph targets.
  78092. box.expandByVector(maxDisplacement);
  78093. }
  78094. geometry.boundingBox = box;
  78095. var sphere = new Sphere();
  78096. box.getCenter(sphere.center);
  78097. sphere.radius = box.min.distanceTo(box.max) / 2;
  78098. geometry.boundingSphere = sphere;
  78099. }
  78100. /**
  78101. * @param {BufferGeometry} geometry
  78102. * @param {GLTF.Primitive} primitiveDef
  78103. * @param {GLTFParser} parser
  78104. * @return {Promise<BufferGeometry>}
  78105. */
  78106. function addPrimitiveAttributes(geometry, primitiveDef, parser) {
  78107. var attributes = primitiveDef.attributes;
  78108. var pending = [];
  78109. function assignAttributeAccessor(accessorIndex, attributeName) {
  78110. return parser.getDependency('accessor', accessorIndex).then(function (accessor) {
  78111. geometry.setAttribute(attributeName, accessor);
  78112. });
  78113. }
  78114. for (var gltfAttributeName in attributes) {
  78115. var threeAttributeName = ATTRIBUTES[gltfAttributeName] || gltfAttributeName.toLowerCase();
  78116. // Skip attributes already provided by e.g. Draco extension.
  78117. if (threeAttributeName in geometry.attributes) continue;
  78118. pending.push(assignAttributeAccessor(attributes[gltfAttributeName], threeAttributeName));
  78119. }
  78120. if (primitiveDef.indices !== undefined && !geometry.index) {
  78121. var accessor = parser.getDependency('accessor', primitiveDef.indices).then(function (accessor) {
  78122. geometry.setIndex(accessor);
  78123. });
  78124. pending.push(accessor);
  78125. }
  78126. assignExtrasToUserData(geometry, primitiveDef);
  78127. computeBounds(geometry, primitiveDef, parser);
  78128. return Promise.all(pending).then(function () {
  78129. return primitiveDef.targets !== undefined ? addMorphTargets(geometry, primitiveDef.targets, parser) : geometry;
  78130. });
  78131. }
  78132. /**
  78133. * @param {BufferGeometry} geometry
  78134. * @param {Number} drawMode
  78135. * @return {BufferGeometry}
  78136. */
  78137. function toTrianglesDrawMode(geometry, drawMode) {
  78138. var index = geometry.getIndex();
  78139. // generate index if not present
  78140. if (index === null) {
  78141. var indices = [];
  78142. var position = geometry.getAttribute('position');
  78143. if (position !== undefined) {
  78144. for (var i = 0; i < position.count; i++) {
  78145. indices.push(i);
  78146. }
  78147. geometry.setIndex(indices);
  78148. index = geometry.getIndex();
  78149. } else {
  78150. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Undefined position attribute. Processing not possible.');
  78151. return geometry;
  78152. }
  78153. }
  78154. //
  78155. var numberOfTriangles = index.count - 2;
  78156. var newIndices = [];
  78157. if (drawMode === TriangleFanDrawMode) {
  78158. // gl.TRIANGLE_FAN
  78159. for (var _i8 = 1; _i8 <= numberOfTriangles; _i8++) {
  78160. newIndices.push(index.getX(0));
  78161. newIndices.push(index.getX(_i8));
  78162. newIndices.push(index.getX(_i8 + 1));
  78163. }
  78164. } else {
  78165. // gl.TRIANGLE_STRIP
  78166. for (var _i9 = 0; _i9 < numberOfTriangles; _i9++) {
  78167. if (_i9 % 2 === 0) {
  78168. newIndices.push(index.getX(_i9));
  78169. newIndices.push(index.getX(_i9 + 1));
  78170. newIndices.push(index.getX(_i9 + 2));
  78171. } else {
  78172. newIndices.push(index.getX(_i9 + 2));
  78173. newIndices.push(index.getX(_i9 + 1));
  78174. newIndices.push(index.getX(_i9));
  78175. }
  78176. }
  78177. }
  78178. if (newIndices.length / 3 !== numberOfTriangles) {
  78179. console.error('THREE.GLTFLoader.toTrianglesDrawMode(): Unable to generate correct amount of triangles.');
  78180. }
  78181. // build final geometry
  78182. var newGeometry = geometry.clone();
  78183. newGeometry.setIndex(newIndices);
  78184. return newGeometry;
  78185. }
  78186. var globalThis=window;//add 有的app没有globalThis. 2023.1
  78187. var rtcCenterGlobal=false;//默认false,也就是scale.z要乘以-1
  78188. /*! *****************************************************************************
  78189. github: https://github.com/nytimes/three-loader-3dtiles
  78190. Copyright (c) Microsoft Corporation.
  78191. Permission to use, copy, modify, and/or distribute this software for any
  78192. purpose with or without fee is hereby granted.
  78193. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  78194. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  78195. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  78196. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  78197. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  78198. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  78199. PERFORMANCE OF THIS SOFTWARE.
  78200. ***************************************************************************** */var visiGeoCount=0;var maxVertexVisi=5e6;var maxTexVisi=500;var maxDepth=100;function getGpuMemoryUsage(){var win=arguments.length>0&&arguments[0]!==undefined?arguments[0]:window;//总的
  78201. var c=0;viewer.objs.children.filter(e=>{if(e.fileType=='3dTiles'){e.traverse(child=>{if(child.runtime){var tileset3D=child.runtime.getTileset();c+=tileset3D.gpuMemoryUsageInBytes;return {stopContinue:true};}});}});if(win.parent!=win){//还有父级页面。 暂时只有子级需要考虑父级,假设父级在前台时子级已经销毁
  78202. c+=getGpuMemoryUsage(win.parent);}viewer.tiles3dMemoryUsage=c;return c;}function __awaiter(thisArg,_arguments,P,generator){function adopt(value){return value instanceof P?value:new P(function(resolve){resolve(value);});}return new(P||(P=Promise))(function(resolve,reject){function fulfilled(value){try{step(generator.next(value));}catch(e){reject(e);}}function rejected(value){try{step(generator["throw"](value));}catch(e){reject(e);}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected);}step((generator=generator.apply(thisArg,_arguments||[])).next());});}function assert$7(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}var isBrowser$2=Boolean(typeof process!=='object'||String(process)!=='[object process]'||process.browser);var matches$1=typeof process!=='undefined'&&process.version&&/v([0-9]*)/.exec(process.version);matches$1&&parseFloat(matches$1[1])||0;var VERSION$8="3.1.4";function assert$6(condition,message){if(!condition){throw new Error(message||'loaders.gl assertion failed.');}}var globals$1={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document};var global_=globals$1.global||globals$1.self||globals$1.window||{};var isBrowser$1=typeof process!=='object'||String(process)!=='[object process]'||process.browser;var isWorker=typeof importScripts==='function';var isMobile=typeof window!=='undefined'&&typeof window.orientation!=='undefined';var matches=typeof process!=='undefined'&&process.version&&/v([0-9]*)/.exec(process.version);matches&&parseFloat(matches[1])||0;function _defineProperty$1(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else {obj[key]=value;}return obj;}class WorkerJob{constructor(jobName,workerThread){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"workerThread",void 0);_defineProperty$1(this,"isRunning",void 0);_defineProperty$1(this,"result",void 0);_defineProperty$1(this,"_resolve",void 0);_defineProperty$1(this,"_reject",void 0);this.name=jobName;this.workerThread=workerThread;this.isRunning=true;this._resolve=()=>{};this._reject=()=>{};this.result=new Promise((resolve,reject)=>{this._resolve=resolve;this._reject=reject;});}postMessage(type,payload){this.workerThread.postMessage({source:'loaders.gl',type,payload});}done(value){assert$6(this.isRunning);this.isRunning=false;this._resolve(value);}error(error){assert$6(this.isRunning);this.isRunning=false;this._reject(error);}}var workerURLCache=new Map();function getLoadableWorkerURL(props){assert$6(props.source&&!props.url||!props.source&&props.url);var workerURL=workerURLCache.get(props.source||props.url);if(!workerURL){if(props.url){workerURL=getLoadableWorkerURLFromURL(props.url);workerURLCache.set(props.url,workerURL);}if(props.source){workerURL=getLoadableWorkerURLFromSource(props.source);workerURLCache.set(props.source,workerURL);}}assert$6(workerURL);return workerURL;}function getLoadableWorkerURLFromURL(url){if(!url.startsWith('http')){return url;}var workerSource=buildScriptSource(url);return getLoadableWorkerURLFromSource(workerSource);}function getLoadableWorkerURLFromSource(workerSource){var blob=new Blob([workerSource],{type:'application/javascript'});return URL.createObjectURL(blob);}function buildScriptSource(workerUrl){return "try {\n importScripts('".concat(workerUrl,"');\n} catch (error) {\n console.error(error);\n throw error;\n}");}function getTransferList(object){var recursive=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var transfers=arguments.length>2?arguments[2]:undefined;var transfersSet=transfers||new Set();if(!object);else if(isTransferable(object)){transfersSet.add(object);}else if(isTransferable(object.buffer)){transfersSet.add(object.buffer);}else if(ArrayBuffer.isView(object));else if(recursive&&typeof object==='object'){for(var key in object){getTransferList(object[key],recursive,transfersSet);}}return transfers===undefined?Array.from(transfersSet):[];}function isTransferable(object){if(!object){return false;}if(object instanceof ArrayBuffer){return true;}if(typeof MessagePort!=='undefined'&&object instanceof MessagePort){return true;}if(typeof ImageBitmap!=='undefined'&&object instanceof ImageBitmap){return true;}if(typeof OffscreenCanvas!=='undefined'&&object instanceof OffscreenCanvas){return true;}return false;}var NOOP=()=>{};class WorkerThread{static isSupported(){return typeof Worker!=='undefined';}constructor(props){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"source",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"terminated",false);_defineProperty$1(this,"worker",void 0);_defineProperty$1(this,"onMessage",void 0);_defineProperty$1(this,"onError",void 0);_defineProperty$1(this,"_loadableURL",'');var{name,source,url}=props;assert$6(source||url);this.name=name;this.source=source;this.url=url;this.onMessage=NOOP;this.onError=error=>console.log(error);this.worker=this._createBrowserWorker();}destroy(){this.onMessage=NOOP;this.onError=NOOP;this.worker.terminate();this.terminated=true;}get isRunning(){return Boolean(this.onMessage);}postMessage(data,transferList){transferList=transferList||getTransferList(data);this.worker.postMessage(data,transferList);}_getErrorFromErrorEvent(event){var message='Failed to load ';message+="worker ".concat(this.name," from ").concat(this.url,". ");if(event.message){message+="".concat(event.message," in ");}if(event.lineno){message+=":".concat(event.lineno,":").concat(event.colno);}return new Error(message);}_createBrowserWorker(){this._loadableURL=getLoadableWorkerURL({source:this.source,url:this.url});var worker=new Worker(this._loadableURL,{name:this.name});worker.onmessage=event=>{if(!event.data){this.onError(new Error('No data received'));}else {this.onMessage(event.data);}};worker.onerror=error=>{this.onError(this._getErrorFromErrorEvent(error));this.terminated=true;};worker.onmessageerror=event=>console.error(event);return worker;}}class WorkerPool$2{constructor(props){_defineProperty$1(this,"name",'unnamed');_defineProperty$1(this,"source",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"maxConcurrency",1);_defineProperty$1(this,"maxMobileConcurrency",1);_defineProperty$1(this,"onDebug",()=>{});_defineProperty$1(this,"reuseWorkers",true);_defineProperty$1(this,"props",{});_defineProperty$1(this,"jobQueue",[]);_defineProperty$1(this,"idleQueue",[]);_defineProperty$1(this,"count",0);_defineProperty$1(this,"isDestroyed",false);this.source=props.source;this.url=props.url;this.setProps(props);}destroy(){this.idleQueue.forEach(worker=>worker.destroy());this.isDestroyed=true;}setProps(props){this.props=_objectSpread2(_objectSpread2({},this.props),props);if(props.name!==undefined){this.name=props.name;}if(props.maxConcurrency!==undefined){this.maxConcurrency=props.maxConcurrency;}if(props.maxMobileConcurrency!==undefined){this.maxMobileConcurrency=props.maxMobileConcurrency;}if(props.reuseWorkers!==undefined){this.reuseWorkers=props.reuseWorkers;}if(props.onDebug!==undefined){this.onDebug=props.onDebug;}}startJob(name){var _arguments2=arguments,_this=this;return _asyncToGenerator(function*(){var onMessage=_arguments2.length>1&&_arguments2[1]!==undefined?_arguments2[1]:(job,type,data)=>job.done(data);var onError=_arguments2.length>2&&_arguments2[2]!==undefined?_arguments2[2]:(job,error)=>job.error(error);var startPromise=new Promise(onStart=>{_this.jobQueue.push({name,onMessage,onError,onStart});return _this;});_this._startQueuedJob();return yield startPromise;})();}_startQueuedJob(){var _this2=this;return _asyncToGenerator(function*(){if(!_this2.jobQueue.length){return;}var workerThread=_this2._getAvailableWorker();if(!workerThread){return;}var queuedJob=_this2.jobQueue.shift();if(queuedJob){_this2.onDebug({message:'Starting job',name:queuedJob.name,workerThread,backlog:_this2.jobQueue.length});var job=new WorkerJob(queuedJob.name,workerThread);workerThread.onMessage=data=>queuedJob.onMessage(job,data.type,data.payload);workerThread.onError=error=>queuedJob.onError(job,error);queuedJob.onStart(job);try{yield job.result;}finally{_this2.returnWorkerToQueue(workerThread);}}})();}returnWorkerToQueue(worker){var shouldDestroyWorker=this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency();if(shouldDestroyWorker){worker.destroy();this.count--;}else {this.idleQueue.push(worker);}if(!this.isDestroyed){this._startQueuedJob();}}_getAvailableWorker(){if(this.idleQueue.length>0){return this.idleQueue.shift()||null;}if(this.count<this._getMaxConcurrency()){this.count++;var _name="".concat(this.name.toLowerCase()," (#").concat(this.count," of ").concat(this.maxConcurrency,")");return new WorkerThread({name:_name,source:this.source,url:this.url});}return null;}_getMaxConcurrency(){return isMobile?this.maxMobileConcurrency:this.maxConcurrency;}}var DEFAULT_PROPS$3={maxConcurrency:3,maxMobileConcurrency:1,onDebug:()=>{},reuseWorkers:true};class WorkerFarm{static isSupported(){return WorkerThread.isSupported();}static getWorkerFarm(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};WorkerFarm._workerFarm=WorkerFarm._workerFarm||new WorkerFarm({});WorkerFarm._workerFarm.setProps(props);return WorkerFarm._workerFarm;}constructor(props){_defineProperty$1(this,"props",void 0);_defineProperty$1(this,"workerPools",new Map());this.props=_objectSpread2({},DEFAULT_PROPS$3);this.setProps(props);this.workerPools=new Map();}destroy(){for(var workerPool of this.workerPools.values()){workerPool.destroy();}}setProps(props){this.props=_objectSpread2(_objectSpread2({},this.props),props);for(var workerPool of this.workerPools.values()){workerPool.setProps(this._getWorkerPoolProps());}}getWorkerPool(options){var{name,source,url}=options;var workerPool=this.workerPools.get(name);if(!workerPool){workerPool=new WorkerPool$2({name,source,url});workerPool.setProps(this._getWorkerPoolProps());this.workerPools.set(name,workerPool);}return workerPool;}_getWorkerPoolProps(){return {maxConcurrency:this.props.maxConcurrency,maxMobileConcurrency:this.props.maxMobileConcurrency,reuseWorkers:this.props.reuseWorkers,onDebug:this.props.onDebug};}}_defineProperty$1(WorkerFarm,"_workerFarm",void 0);var NPM_TAG='latest';function getWorkerURL(worker){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var workerOptions=options[worker.id]||{};var workerFile="".concat(worker.id,"-worker.js");var url=workerOptions.workerUrl;if(!url&&worker.id==='compression'){url=options.workerUrl;}if(options._workerType==='test'){url="modules/".concat(worker.module,"/dist/").concat(workerFile);}if(!url){var version=worker.version;if(version==='latest'){version=NPM_TAG;}var versionTag=version?"@".concat(version):'';url="https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag,"/dist/").concat(workerFile);}assert$6(url);return url;}function validateWorkerVersion(worker){var coreVersion=arguments.length>1&&arguments[1]!==undefined?arguments[1]:VERSION$8;assert$6(worker,'no worker provided');var workerVersion=worker.version;if(!coreVersion||!workerVersion){return false;}return true;}var ChildProcessProxy={};var node=/*#__PURE__*/Object.freeze(/*#__PURE__*/Object.assign(/*#__PURE__*/Object.create(null),ChildProcessProxy,{'default':ChildProcessProxy}));var VERSION$7="3.1.4";var loadLibraryPromises={};function loadLibrary(_x7){return _loadLibrary.apply(this,arguments);}function _loadLibrary(){_loadLibrary=_asyncToGenerator(function*(libraryUrl){var moduleName=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(moduleName){libraryUrl=getLibraryUrl(libraryUrl,moduleName,options);}loadLibraryPromises[libraryUrl]=loadLibraryPromises[libraryUrl]||loadLibraryFromFile(libraryUrl);return yield loadLibraryPromises[libraryUrl];});return _loadLibrary.apply(this,arguments);}function getLibraryUrl(library,moduleName,options){if(library.startsWith('http')){return library;}var modules=options.modules||{};if(modules[library]){return modules[library];}if(!isBrowser$1){return "modules/".concat(moduleName,"/dist/libs/").concat(library);}if(options.CDN){assert$6(options.CDN.startsWith('http'));return "".concat(options.CDN,"/").concat(moduleName,"@").concat(VERSION$7,"/dist/libs/").concat(library);}if(isWorker){return "../src/libs/".concat(library);}return "modules/".concat(moduleName,"/src/libs/").concat(library);}function loadLibraryFromFile(_x8){return _loadLibraryFromFile.apply(this,arguments);}function _loadLibraryFromFile(){_loadLibraryFromFile=_asyncToGenerator(function*(libraryUrl){if(libraryUrl.endsWith('wasm')){var _response=yield fetch(libraryUrl);return yield _response.arrayBuffer();}if(!isBrowser$1){try{return node&&ChildProcessProxy.requireFromFile&&(yield ChildProcessProxy.requireFromFile(libraryUrl));}catch(_unused2){return null;}}if(isWorker){return importScripts(libraryUrl);}var response=yield fetch(libraryUrl);var scriptSource=yield response.text();return loadLibraryFromString(scriptSource,libraryUrl);});return _loadLibraryFromFile.apply(this,arguments);}function loadLibraryFromString(scriptSource,id){if(!isBrowser$1){return ChildProcessProxy.requireFromString&&ChildProcessProxy.requireFromString(scriptSource,id);}if(isWorker){eval.call(global_,scriptSource);return null;}var script=document.createElement('script');script.id=id;try{script.appendChild(document.createTextNode(scriptSource));}catch(e){script.text=scriptSource;}document.body.appendChild(script);return null;}function canParseWithWorker(loader,options){if(!WorkerFarm.isSupported()){return false;}return loader.worker&&(options===null||options===void 0?void 0:options.worker);}function parseWithWorker(_x9,_x10,_x11,_x12,_x13){return _parseWithWorker.apply(this,arguments);}function _parseWithWorker(){_parseWithWorker=_asyncToGenerator(function*(loader,data,options,context,parseOnMainThread){var name=loader.id;var url=getWorkerURL(loader,options);var workerFarm=WorkerFarm.getWorkerFarm(options);var workerPool=workerFarm.getWorkerPool({name,url});options=JSON.parse(JSON.stringify(options));var job=yield workerPool.startJob('process-on-worker',onMessage.bind(null,parseOnMainThread));job.postMessage('process',{input:data,options});var result=yield job.result;return yield result.result;});return _parseWithWorker.apply(this,arguments);}function onMessage(_x14,_x15,_x16,_x17){return _onMessage.apply(this,arguments);}function _onMessage(){_onMessage=_asyncToGenerator(function*(parseOnMainThread,job,type,payload){switch(type){case'done':job.done(payload);break;case'error':job.error(new Error(payload.error));break;case'process':var{id,input,options}=payload;try{var result=yield parseOnMainThread(input,options);job.postMessage('done',{id,result});}catch(error){var message=error instanceof Error?error.message:'unknown error';job.postMessage('error',{id,error:message});}break;default:console.warn("parse-with-worker unknown message ".concat(type));}});return _onMessage.apply(this,arguments);}function getFirstCharacters$1(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$3(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$3(data,byteOffset,length);}return '';}function getMagicString$3(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength<=byteOffset+length){return '';}var dataView=new DataView(arrayBuffer);var magic='';for(var _i=0;_i<length;_i++){magic+=String.fromCharCode(dataView.getUint8(byteOffset+_i));}return magic;}function parseJSON(string){try{return JSON.parse(string);}catch(_){throw new Error("Failed to parse JSON from data starting with \"".concat(getFirstCharacters$1(string),"\""));}}function isBuffer$1(value){return value&&typeof value==='object'&&value.isBuffer;}function bufferToArrayBuffer(buffer){if(isBuffer$1(buffer)){var typedArray=new Uint8Array(buffer.buffer,buffer.byteOffset,buffer.length);return typedArray.slice().buffer;}return buffer;}function toArrayBuffer(data){if(isBuffer$1(data)){return bufferToArrayBuffer(data);}if(data instanceof ArrayBuffer){return data;}if(ArrayBuffer.isView(data)){if(data.byteOffset===0&&data.byteLength===data.buffer.byteLength){return data.buffer;}return data.buffer.slice(data.byteOffset,data.byteOffset+data.byteLength);}if(typeof data==='string'){var text=data;var uint8Array=new TextEncoder().encode(text);return uint8Array.buffer;}if(data&&typeof data==='object'&&data._toArrayBuffer){return data._toArrayBuffer();}throw new Error('toArrayBuffer');}function compareArrayBuffers(arrayBuffer1,arrayBuffer2,byteLength){byteLength=byteLength||arrayBuffer1.byteLength;if(arrayBuffer1.byteLength<byteLength||arrayBuffer2.byteLength<byteLength){return false;}var array1=new Uint8Array(arrayBuffer1);var array2=new Uint8Array(arrayBuffer2);for(var _i2=0;_i2<array1.length;++_i2){if(array1[_i2]!==array2[_i2]){return false;}}return true;}function concatenateArrayBuffers(){for(var _len2=arguments.length,sources=new Array(_len2),_key2=0;_key2<_len2;_key2++){sources[_key2]=arguments[_key2];}var sourceArrays=sources.map(source2=>source2 instanceof ArrayBuffer?new Uint8Array(source2):source2);var byteLength=sourceArrays.reduce((length,typedArray)=>length+typedArray.byteLength,0);var result=new Uint8Array(byteLength);var offset=0;for(var sourceArray of sourceArrays){result.set(sourceArray,offset);offset+=sourceArray.byteLength;}return result.buffer;}function sliceArrayBuffer(arrayBuffer,byteOffset,byteLength){var subArray=byteLength!==undefined?new Uint8Array(arrayBuffer).subarray(byteOffset,byteOffset+byteLength):new Uint8Array(arrayBuffer).subarray(byteOffset);var arrayCopy=new Uint8Array(subArray);return arrayCopy.buffer;}function padToNBytes(byteLength,padding){assert$7(byteLength>=0);assert$7(padding>0);return byteLength+(padding-1)&~(padding-1);}function copyToArray(source,target,targetOffset){var sourceArray;if(source instanceof ArrayBuffer){sourceArray=new Uint8Array(source);}else {var srcByteOffset=source.byteOffset;var srcByteLength=source.byteLength;sourceArray=new Uint8Array(source.buffer||source.arrayBuffer,srcByteOffset,srcByteLength);}target.set(sourceArray,targetOffset);return targetOffset+padToNBytes(sourceArray.byteLength,4);}function concatenateArrayBuffersAsync(_x18){return _concatenateArrayBuffersAsync.apply(this,arguments);}function _concatenateArrayBuffersAsync(){_concatenateArrayBuffersAsync=_asyncToGenerator(function*(asyncIterator){var arrayBuffers=[];var _iteratorAbruptCompletion=false;var _didIteratorError=false;var _iteratorError;try{for(var _iterator=_asyncIterator(asyncIterator),_step;_iteratorAbruptCompletion=!(_step=yield _iterator.next()).done;_iteratorAbruptCompletion=false){var chunk=_step.value;{arrayBuffers.push(chunk);}}}catch(err){_didIteratorError=true;_iteratorError=err;}finally{try{if(_iteratorAbruptCompletion&&_iterator.return!=null){yield _iterator.return();}}finally{if(_didIteratorError){throw _iteratorError;}}}return concatenateArrayBuffers(...arrayBuffers);});return _concatenateArrayBuffersAsync.apply(this,arguments);}function getHiResTimestamp$1(){var timestamp;if(typeof window!=='undefined'&&window.performance){timestamp=window.performance.now();}else if(typeof process!=='undefined'&&process.hrtime){var timeParts=process.hrtime();timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else {timestamp=Date.now();}return timestamp;}class Stat{constructor(name,type){_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"sampleSize",1);_defineProperty$1(this,"time",void 0);_defineProperty$1(this,"count",void 0);_defineProperty$1(this,"samples",void 0);_defineProperty$1(this,"lastTiming",void 0);_defineProperty$1(this,"lastSampleTime",void 0);_defineProperty$1(this,"lastSampleCount",void 0);_defineProperty$1(this,"_count",0);_defineProperty$1(this,"_time",0);_defineProperty$1(this,"_samples",0);_defineProperty$1(this,"_startTime",0);_defineProperty$1(this,"_timerPending",false);this.name=name;this.type=type;this.reset();}setSampleSize(samples){this.sampleSize=samples;return this;}incrementCount(){this.addCount(1);return this;}decrementCount(){this.subtractCount(1);return this;}addCount(value){this._count+=value;this._samples++;this._checkSampling();return this;}subtractCount(value){this._count-=value;this._samples++;this._checkSampling();return this;}addTime(time){this._time+=time;this.lastTiming=time;this._samples++;this._checkSampling();return this;}timeStart(){this._startTime=getHiResTimestamp$1();this._timerPending=true;return this;}timeEnd(){if(!this._timerPending){return this;}this.addTime(getHiResTimestamp$1()-this._startTime);this._timerPending=false;this._checkSampling();return this;}getSampleAverageCount(){return this.sampleSize>0?this.lastSampleCount/this.sampleSize:0;}getSampleAverageTime(){return this.sampleSize>0?this.lastSampleTime/this.sampleSize:0;}getSampleHz(){return this.lastSampleTime>0?this.sampleSize/(this.lastSampleTime/1000):0;}getAverageCount(){return this.samples>0?this.count/this.samples:0;}getAverageTime(){return this.samples>0?this.time/this.samples:0;}getHz(){return this.time>0?this.samples/(this.time/1000):0;}reset(){this.time=0;this.count=0;this.samples=0;this.lastTiming=0;this.lastSampleTime=0;this.lastSampleCount=0;this._count=0;this._time=0;this._samples=0;this._startTime=0;this._timerPending=false;return this;}_checkSampling(){if(this._samples===this.sampleSize){this.lastSampleTime=this._time;this.lastSampleCount=this._count;this.count+=this._count;this.time+=this._time;this.samples+=this._samples;this._time=0;this._count=0;this._samples=0;}}}class Stats$1{constructor(options){_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"stats",{});this.id=options.id;this.stats={};this._initializeStats(options.stats);Object.seal(this);}get(name){var type=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'count';return this._getOrCreate({name,type});}get size(){return Object.keys(this.stats).length;}reset(){for(var key in this.stats){this.stats[key].reset();}return this;}forEach(fn){for(var key in this.stats){fn(this.stats[key]);}}getTable(){var table={};this.forEach(stat=>{table[stat.name]={time:stat.time||0,count:stat.count||0,average:stat.getAverageTime()||0,hz:stat.getHz()||0};});return table;}_initializeStats(){var stats=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];stats.forEach(stat=>this._getOrCreate(stat));}_getOrCreate(stat){if(!stat||!stat.name){return null;}var{name,type}=stat;if(!this.stats[name]){if(stat instanceof Stat){this.stats[name]=stat;}else {this.stats[name]=new Stat(name,type);}}return this.stats[name];}}var STAT_QUEUED_REQUESTS='Queued Requests';var STAT_ACTIVE_REQUESTS='Active Requests';var STAT_CANCELLED_REQUESTS='Cancelled Requests';var STAT_QUEUED_REQUESTS_EVER='Queued Requests Ever';var STAT_ACTIVE_REQUESTS_EVER='Active Requests Ever';var DEFAULT_PROPS$2={id:'request-scheduler',throttleRequests:true,maxRequests:6};class RequestScheduler{constructor(){var props=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};_defineProperty$1(this,"props",void 0);_defineProperty$1(this,"stats",void 0);_defineProperty$1(this,"activeRequestCount",0);_defineProperty$1(this,"requestQueue",[]);_defineProperty$1(this,"requestMap",new Map());_defineProperty$1(this,"deferredUpdate",null);this.props=_objectSpread2(_objectSpread2({},DEFAULT_PROPS$2),props);this.stats=new Stats$1({id:this.props.id});this.stats.get(STAT_QUEUED_REQUESTS);this.stats.get(STAT_ACTIVE_REQUESTS);this.stats.get(STAT_CANCELLED_REQUESTS);this.stats.get(STAT_QUEUED_REQUESTS_EVER);this.stats.get(STAT_ACTIVE_REQUESTS_EVER);}scheduleRequest(handle){var getPriority=arguments.length>1&&arguments[1]!==undefined?arguments[1]:()=>0;if(!this.props.throttleRequests){return Promise.resolve({done:()=>{}});}if(this.requestMap.has(handle)){return this.requestMap.get(handle);}var request={handle,priority:0,getPriority};var promise=new Promise(resolve=>{request.resolve=resolve;return request;});this.requestQueue.push(request);this.requestMap.set(handle,promise);this._issueNewRequests();return promise;}_issueRequest(request){var{handle,resolve}=request;var isDone=false;var done=()=>{if(!isDone){isDone=true;this.requestMap.delete(handle);this.activeRequestCount--;this._issueNewRequests();}};this.activeRequestCount++;return resolve?resolve({done}):Promise.resolve({done});}_issueNewRequests(){if(!this.deferredUpdate){this.deferredUpdate=setTimeout(()=>this._issueNewRequestsAsync(),0);}}_issueNewRequestsAsync(){this.deferredUpdate=null;var freeSlots=Math.max(this.props.maxRequests-this.activeRequestCount,0);if(freeSlots===0){return;}this._updateAllRequests();for(var _i3=0;_i3<freeSlots;++_i3){var request=this.requestQueue.shift();if(request){this._issueRequest(request);}}}_updateAllRequests(){var requestQueue=this.requestQueue;for(var _i4=0;_i4<requestQueue.length;++_i4){var request=requestQueue[_i4];if(!this._updateRequest(request)){requestQueue.splice(_i4,1);this.requestMap.delete(request.handle);_i4--;}}requestQueue.sort((a,b)=>a.priority-b.priority);}_updateRequest(request){request.priority=request.getPriority(request.handle);if(request.priority<0){request.resolve(null);return false;}return true;}}var pathPrefix='';var fileAliases={};function resolvePath(filename){for(var alias in fileAliases){if(filename.startsWith(alias)){var replacement=fileAliases[alias];filename=filename.replace(alias,replacement);}}if(!filename.startsWith('http://')&&!filename.startsWith('https://')){filename="".concat(pathPrefix).concat(filename);}return filename;}function filename(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(slashIndex+1):'';}function dirname(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(0,slashIndex):'';}var isBoolean=x=>typeof x==='boolean';var isFunction=x=>typeof x==='function';var isObject=x=>x!==null&&typeof x==='object';var isPureObject=x=>isObject(x)&&x.constructor==={}.constructor;var isIterable=x=>x&&typeof x[Symbol.iterator]==='function';var isAsyncIterable=x=>x&&typeof x[Symbol.asyncIterator]==='function';var isResponse=x=>typeof Response!=='undefined'&&x instanceof Response||x&&x.arrayBuffer&&x.text&&x.json;var isBlob=x=>typeof Blob!=='undefined'&&x instanceof Blob;var isBuffer=x=>x&&typeof x==='object'&&x.isBuffer;var isReadableDOMStream=x=>typeof ReadableStream!=='undefined'&&x instanceof ReadableStream||isObject(x)&&isFunction(x.tee)&&isFunction(x.cancel)&&isFunction(x.getReader);var isReadableNodeStream=x=>isObject(x)&&isFunction(x.read)&&isFunction(x.pipe)&&isBoolean(x.readable);var isReadableStream=x=>isReadableDOMStream(x)||isReadableNodeStream(x);var DATA_URL_PATTERN=/^data:([-\w.]+\/[-\w.+]+)(;|,)/;var MIME_TYPE_PATTERN=/^([-\w.]+\/[-\w.+]+)/;function parseMIMEType(mimeString){var matches=MIME_TYPE_PATTERN.exec(mimeString);if(matches){return matches[1];}return mimeString;}function parseMIMETypeFromURL(url){var matches=DATA_URL_PATTERN.exec(url);if(matches){return matches[1];}return '';}var QUERY_STRING_PATTERN=/\?.*/;function getResourceUrlAndType(resource){if(isResponse(resource)){var url=stripQueryString(resource.url||'');var contentTypeHeader=resource.headers.get('content-type')||'';return {url,type:parseMIMEType(contentTypeHeader)||parseMIMETypeFromURL(url)};}if(isBlob(resource)){return {url:stripQueryString(resource.name||''),type:resource.type||''};}if(typeof resource==='string'){return {url:stripQueryString(resource),type:parseMIMETypeFromURL(resource)};}return {url:'',type:''};}function getResourceContentLength(resource){if(isResponse(resource)){return resource.headers['content-length']||-1;}if(isBlob(resource)){return resource.size;}if(typeof resource==='string'){return resource.length;}if(resource instanceof ArrayBuffer){return resource.byteLength;}if(ArrayBuffer.isView(resource)){return resource.byteLength;}return -1;}function stripQueryString(url){return url.replace(QUERY_STRING_PATTERN,'');}function makeResponse(_x19){return _makeResponse.apply(this,arguments);}function _makeResponse(){_makeResponse=_asyncToGenerator(function*(resource){if(isResponse(resource)){return resource;}var headers={};var contentLength=getResourceContentLength(resource);if(contentLength>=0){headers['content-length']=String(contentLength);}var{url,type}=getResourceUrlAndType(resource);if(type){headers['content-type']=type;}var initialDataUrl=yield getInitialDataUrl(resource);if(initialDataUrl){headers['x-first-bytes']=initialDataUrl;}if(typeof resource==='string'){resource=new TextEncoder().encode(resource);}var response=new Response(resource,{headers});Object.defineProperty(response,'url',{value:url});return response;});return _makeResponse.apply(this,arguments);}function checkResponse(_x20){return _checkResponse.apply(this,arguments);}function _checkResponse(){_checkResponse=_asyncToGenerator(function*(response){if(!response.ok){var message=yield getResponseError(response);throw new Error(message);}});return _checkResponse.apply(this,arguments);}function getResponseError(_x21){return _getResponseError.apply(this,arguments);}function _getResponseError(){_getResponseError=_asyncToGenerator(function*(response){var message="Failed to fetch resource ".concat(response.url," (").concat(response.status,"): ");try{var contentType=response.headers.get('Content-Type');var text=response.statusText;if(contentType.includes('application/json')){text+=" ".concat(yield response.text());}message+=text;message=message.length>60?"".concat(message.slice(60),"..."):message;}catch(error){}return message;});return _getResponseError.apply(this,arguments);}function getInitialDataUrl(_x22){return _getInitialDataUrl.apply(this,arguments);}function _getInitialDataUrl(){_getInitialDataUrl=_asyncToGenerator(function*(resource){var INITIAL_DATA_LENGTH=5;if(typeof resource==='string'){return "data:,".concat(resource.slice(0,INITIAL_DATA_LENGTH));}if(resource instanceof Blob){var blobSlice=resource.slice(0,5);return yield new Promise(resolve=>{var reader=new FileReader();reader.onload=event=>{var _event$target;return resolve(event===null||event===void 0?void 0:(_event$target=event.target)===null||_event$target===void 0?void 0:_event$target.result);};reader.readAsDataURL(blobSlice);});}if(resource instanceof ArrayBuffer){var slice=resource.slice(0,INITIAL_DATA_LENGTH);var base64=arrayBufferToBase64(slice);return "data:base64,".concat(base64);}return null;});return _getInitialDataUrl.apply(this,arguments);}function arrayBufferToBase64(buffer){var binary='';var bytes=new Uint8Array(buffer);for(var _i5=0;_i5<bytes.byteLength;_i5++){binary+=String.fromCharCode(bytes[_i5]);}return btoa(binary);}function fetchFile(_x23,_x24){return _fetchFile.apply(this,arguments);}function _fetchFile(){_fetchFile=_asyncToGenerator(function*(url,options){if(typeof url==='string'){url=resolvePath(url);var fetchOptions=options;if(options!==null&&options!==void 0&&options.fetch&&typeof(options===null||options===void 0?void 0:options.fetch)!=='function'){fetchOptions=options.fetch;}return yield fetch(url,fetchOptions);}return yield makeResponse(url);});return _fetchFile.apply(this,arguments);}function isElectron(mockUserAgent){if(typeof window!=='undefined'&&typeof window.process==='object'&&window.process.type==='renderer'){return true;}if(typeof process!=='undefined'&&typeof process.versions==='object'&&Boolean(process.versions.electron)){return true;}var realUserAgent=typeof navigator==='object'&&typeof navigator.userAgent==='string'&&navigator.userAgent;var userAgent=mockUserAgent||realUserAgent;if(userAgent&&userAgent.indexOf('Electron')>=0){return true;}return false;}function isBrowser(){var isNode=typeof process==='object'&&String(process)==='[object process]'&&!process.browser;return !isNode||isElectron();}var globals={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:typeof process==='object'&&process};var window_=globals.window||globals.self||globals.global;var process_=globals.process||{};var VERSION$6=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';isBrowser();function getStorage(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}class LocalStorage{constructor(id){var defaultSettings=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_defineProperty$1(this,"storage",void 0);_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"config",{});this.storage=getStorage(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}getConfiguration(){return this.config;}setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}_loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}function formatTime(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else {formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return "".concat(' '.repeat(padLength)).concat(string);}function formatImage(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return ["".concat(message," %c+"),style];}var COLOR;(function(COLOR){COLOR[COLOR["BLACK"]=30]="BLACK";COLOR[COLOR["RED"]=31]="RED";COLOR[COLOR["GREEN"]=32]="GREEN";COLOR[COLOR["YELLOW"]=33]="YELLOW";COLOR[COLOR["BLUE"]=34]="BLUE";COLOR[COLOR["MAGENTA"]=35]="MAGENTA";COLOR[COLOR["CYAN"]=36]="CYAN";COLOR[COLOR["WHITE"]=37]="WHITE";COLOR[COLOR["BRIGHT_BLACK"]=90]="BRIGHT_BLACK";COLOR[COLOR["BRIGHT_RED"]=91]="BRIGHT_RED";COLOR[COLOR["BRIGHT_GREEN"]=92]="BRIGHT_GREEN";COLOR[COLOR["BRIGHT_YELLOW"]=93]="BRIGHT_YELLOW";COLOR[COLOR["BRIGHT_BLUE"]=94]="BRIGHT_BLUE";COLOR[COLOR["BRIGHT_MAGENTA"]=95]="BRIGHT_MAGENTA";COLOR[COLOR["BRIGHT_CYAN"]=96]="BRIGHT_CYAN";COLOR[COLOR["BRIGHT_WHITE"]=97]="BRIGHT_WHITE";})(COLOR||(COLOR={}));function getColor$1(color){return typeof color==='string'?COLOR[color.toUpperCase()]||COLOR.WHITE:color;}function addColor(string,color,background){if(!isBrowser&&typeof string==='string'){if(color){color=getColor$1(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor$1(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _loop=function _loop(key){if(typeof obj[key]==='function'){if(!predefined.find(name=>key===name)){obj[key]=obj[key].bind(obj);}}};for(var key of propNames){_loop(key);}}function assert$5(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp(){var timestamp;if(isBrowser&&'performance'in window_){var _window$performance,_window$performance$n;timestamp=window_===null||window_===void 0?void 0:(_window$performance=window_.performance)===null||_window$performance===void 0?void 0:(_window$performance$n=_window$performance.now)===null||_window$performance$n===void 0?void 0:_window$performance$n.call(_window$performance);}else if('hrtime'in process_){var _process$hrtime;var timeParts=process_===null||process_===void 0?void 0:(_process$hrtime=process_.hrtime)===null||_process$hrtime===void 0?void 0:_process$hrtime.call(process_);timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else {timestamp=Date.now();}return timestamp;}var originalConsole={debug:isBrowser?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS={enabled:true,level:0};function noop$1(){}var cache={};var ONCE={once:true};class Log{constructor(){var{id}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''};_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"VERSION",VERSION$6);_defineProperty$1(this,"_startTs",getHiResTimestamp());_defineProperty$1(this,"_deltaTs",getHiResTimestamp());_defineProperty$1(this,"_storage",void 0);_defineProperty$1(this,"userData",{});_defineProperty$1(this,"LOG_THROTTLE_TIMEOUT",0);this.id=id;this._storage=new LocalStorage("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS);this.userData={};this.timeStamp("".concat(this.id," started"));autobind(this);Object.seal(this);}set level(newLevel){this.setLevel(newLevel);}get level(){return this.getLevel();}isEnabled(){return this._storage.config.enabled;}getLevel(){return this._storage.config.level;}getTotal(){return Number((getHiResTimestamp()-this._startTs).toPrecision(10));}getDelta(){return Number((getHiResTimestamp()-this._deltaTs).toPrecision(10));}set priority(newPriority){this.level=newPriority;}get priority(){return this.level;}getPriority(){return this.level;}enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled});return this;}setLevel(level){this._storage.updateConfiguration({level});return this;}get(setting){return this._storage.config[setting];}set(setting,value){this._storage.updateConfiguration({[setting]:value});}settings(){if(console.table){console.table(this._storage.config);}else {console.log(this._storage.config);}}assert(condition,message){assert$5(condition,message);}warn(message){return this._getLogFunction(0,message,originalConsole.warn,arguments,ONCE);}error(message){return this._getLogFunction(0,message,originalConsole.error,arguments);}deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.log,arguments,{time:true,once:true});}log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.debug,arguments);}info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}once(logLevel,message){for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}return this._getLogFunction(logLevel,message,originalConsole.debug||originalConsole.info,arguments,ONCE);}table(logLevel,table,columns){if(table){return this._getLogFunction(logLevel,table,console.table||noop$1,columns&&[columns],{tag:getTableHeader(table)});}return noop$1;}image(_ref){var{logLevel,priority,image,message='',scale=1}=_ref;if(!this._shouldLog(logLevel||priority)){return noop$1;}return isBrowser?logImageInBrowser({image,message,scale}):logImageInNode({image,message,scale});}time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop$1);}group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};var options=normalizeArguments({logLevel,message,opts});var{collapsed}=opts;options.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(options);}groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop$1);}withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}trace(){if(console.trace){console.trace();}}_shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel(logLevel);}_getLogFunction(logLevel,message,method,args,opts){if(this._shouldLog(logLevel)){opts=normalizeArguments({logLevel,message,args,opts});method=method||opts.method;assert$5(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp();var tag=opts.tag||opts.message;if(opts.once){if(!cache[tag]){cache[tag]=getHiResTimestamp();}else {return noop$1;}}message=decorateMessage(this.id,opts.message,opts);return method.bind(console,message,...opts.args);}return noop$1;}}_defineProperty$1(Log,"VERSION",VERSION$6);function normalizeLogLevel(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(typeof logLevel){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$5(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments(opts){var{logLevel,message}=opts;opts.logLevel=normalizeLogLevel(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}switch(typeof logLevel){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=typeof opts.message;assert$5(messageType==='string'||messageType==='object');return Object.assign(opts,{args},opts.opts);}function decorateMessage(id,message,opts){if(typeof message==='string'){var time=opts.time?leftPad(formatTime(opts.total)):'';message=opts.time?"".concat(id,": ").concat(time," ").concat(message):"".concat(id,": ").concat(message);message=addColor(message,opts.color,opts.background);}return message;}function logImageInNode(_ref2){var{image,message='',scale=1}=_ref2;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return ()=>asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(data=>console.log(data));}return noop$1;}function logImageInBrowser(_ref3){var{image,message='',scale=1}=_ref3;if(typeof image==='string'){var img=new Image();img.onload=()=>{var args=formatImage(img,message,scale);console.log(...args);};img.src=image;return noop$1;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){console.log(...formatImage(image,message,scale));return noop$1;}if(element.toLowerCase()==='canvas'){var _img=new Image();_img.onload=()=>console.log(...formatImage(_img,message,scale));_img.src=image.toDataURL();return noop$1;}return noop$1;}function getTableHeader(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return 'empty';}var probeLog=new Log({id:'loaders.gl'});class NullLog{log(){return ()=>{};}info(){return ()=>{};}warn(){return ()=>{};}error(){return ()=>{};}}class ConsoleLog{constructor(){_defineProperty$1(this,"console",void 0);this.console=console;}log(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3];}return this.console.log.bind(this.console,...args);}info(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4];}return this.console.info.bind(this.console,...args);}warn(){for(var _len5=arguments.length,args=new Array(_len5),_key5=0;_key5<_len5;_key5++){args[_key5]=arguments[_key5];}return this.console.warn.bind(this.console,...args);}error(){for(var _len6=arguments.length,args=new Array(_len6),_key6=0;_key6<_len6;_key6++){args[_key6]=arguments[_key6];}return this.console.error.bind(this.console,...args);}}var DEFAULT_LOADER_OPTIONS={fetch:null,mimeType:undefined,nothrow:false,log:new ConsoleLog(),CDN:'https://unpkg.com/@loaders.gl',worker:true,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:true,_workerType:'',limit:0,_limitMB:0,batchSize:'auto',batchDebounceMs:0,metadata:false,transforms:[]};var REMOVED_LOADER_OPTIONS={throws:'nothrow',dataType:'(no longer used)',uri:'baseUri',method:'fetch.method',headers:'fetch.headers',body:'fetch.body',mode:'fetch.mode',credentials:'fetch.credentials',cache:'fetch.cache',redirect:'fetch.redirect',referrer:'fetch.referrer',referrerPolicy:'fetch.referrerPolicy',integrity:'fetch.integrity',keepalive:'fetch.keepalive',signal:'fetch.signal'};function getGlobalLoaderState(){globalThis.loaders=globalThis.loaders||{};var{loaders}=globalThis;loaders._state=loaders._state||{};return loaders._state;}var getGlobalLoaderOptions=()=>{var state=getGlobalLoaderState();state.globalOptions=state.globalOptions||_objectSpread2({},DEFAULT_LOADER_OPTIONS);return state.globalOptions;};function normalizeOptions(options,loader,loaders,url){loaders=loaders||[];loaders=Array.isArray(loaders)?loaders:[loaders];validateOptions(options,loaders);return normalizeOptionsInternal(loader,options,url);}function getFetchFunction(options,context){var globalOptions=getGlobalLoaderOptions();var fetchOptions=options||globalOptions;if(typeof fetchOptions.fetch==='function'){return fetchOptions.fetch;}if(isObject(fetchOptions.fetch)){return url=>fetchFile(url,fetchOptions);}if(context!==null&&context!==void 0&&context.fetch){return context===null||context===void 0?void 0:context.fetch;}return fetchFile;}function validateOptions(options,loaders){validateOptionsObject(options,null,DEFAULT_LOADER_OPTIONS,REMOVED_LOADER_OPTIONS,loaders);for(var loader of loaders){var idOptions=options&&options[loader.id]||{};var loaderOptions=loader.options&&loader.options[loader.id]||{};var deprecatedOptions=loader.deprecatedOptions&&loader.deprecatedOptions[loader.id]||{};validateOptionsObject(idOptions,loader.id,loaderOptions,deprecatedOptions,loaders);}}function validateOptionsObject(options,id,defaultOptions,deprecatedOptions,loaders){var loaderName=id||'Top level';var prefix=id?"".concat(id,"."):'';for(var key in options){var isSubOptions=!id&&isObject(options[key]);var isBaseUriOption=key==='baseUri'&&!id;var isWorkerUrlOption=key==='workerUrl'&&id;if(!(key in defaultOptions)&&!isBaseUriOption&&!isWorkerUrlOption){if(key in deprecatedOptions){probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' no longer supported, use '").concat(deprecatedOptions[key],"'"))();}else if(!isSubOptions){var suggestion=findSimilarOption(key,loaders);probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' not recognized. ").concat(suggestion))();}}}}function findSimilarOption(optionKey,loaders){var lowerCaseOptionKey=optionKey.toLowerCase();var bestSuggestion='';for(var loader of loaders){for(var key in loader.options){if(optionKey===key){return "Did you mean '".concat(loader.id,".").concat(key,"'?");}var lowerCaseKey=key.toLowerCase();var isPartialMatch=lowerCaseOptionKey.startsWith(lowerCaseKey)||lowerCaseKey.startsWith(lowerCaseOptionKey);if(isPartialMatch){bestSuggestion=bestSuggestion||"Did you mean '".concat(loader.id,".").concat(key,"'?");}}}return bestSuggestion;}function normalizeOptionsInternal(loader,options,url){var loaderDefaultOptions=loader.options||{};var mergedOptions=_objectSpread2({},loaderDefaultOptions);addUrlOptions(mergedOptions,url);if(mergedOptions.log===null){mergedOptions.log=new NullLog();}mergeNestedFields(mergedOptions,getGlobalLoaderOptions());mergeNestedFields(mergedOptions,options);return mergedOptions;}function mergeNestedFields(mergedOptions,options){for(var key in options){if(key in options){var value=options[key];if(isPureObject(value)&&isPureObject(mergedOptions[key])){mergedOptions[key]=_objectSpread2(_objectSpread2({},mergedOptions[key]),options[key]);}else {mergedOptions[key]=options[key];}}}}function addUrlOptions(options,url){if(url&&!('baseUri'in options)){options.baseUri=url;}}function isLoaderObject(loader){var _loader;if(!loader){return false;}if(Array.isArray(loader)){loader=loader[0];}var hasExtensions=Array.isArray((_loader=loader)===null||_loader===void 0?void 0:_loader.extensions);return hasExtensions;}function normalizeLoader(loader){var _loader2,_loader3;assert$7(loader,'null loader');assert$7(isLoaderObject(loader),'invalid loader');var options;if(Array.isArray(loader)){options=loader[1];loader=loader[0];loader=_objectSpread2(_objectSpread2({},loader),{},{options:_objectSpread2(_objectSpread2({},loader.options),options)});}if((_loader2=loader)!==null&&_loader2!==void 0&&_loader2.parseTextSync||(_loader3=loader)!==null&&_loader3!==void 0&&_loader3.parseText){loader.text=true;}if(!loader.text){loader.binary=true;}return loader;}var getGlobalLoaderRegistry=()=>{var state=getGlobalLoaderState();state.loaderRegistry=state.loaderRegistry||[];return state.loaderRegistry;};function getRegisteredLoaders(){return getGlobalLoaderRegistry();}var EXT_PATTERN=/\.([^.]+)$/;function selectLoader(_x25){return _selectLoader.apply(this,arguments);}function _selectLoader(){_selectLoader=_asyncToGenerator(function*(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}var loader=selectLoaderSync(data,loaders,_objectSpread2(_objectSpread2({},options),{},{nothrow:true}),context);if(loader){return loader;}if(isBlob(data)){data=yield data.slice(0,10).arrayBuffer();loader=selectLoaderSync(data,loaders,options,context);}if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;});return _selectLoader.apply(this,arguments);}function selectLoaderSync(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}if(loaders&&!Array.isArray(loaders)){return normalizeLoader(loaders);}var candidateLoaders=[];if(loaders){candidateLoaders=candidateLoaders.concat(loaders);}if(!(options!==null&&options!==void 0&&options.ignoreRegisteredLoaders)){candidateLoaders.push(...getRegisteredLoaders());}normalizeLoaders(candidateLoaders);var loader=selectLoaderInternal(data,candidateLoaders,options,context);if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;}function selectLoaderInternal(data,loaders,options,context){var{url,type}=getResourceUrlAndType(data);var testUrl=url||(context===null||context===void 0?void 0:context.url);var loader=null;if(options!==null&&options!==void 0&&options.mimeType){loader=findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.mimeType);}loader=loader||findLoaderByUrl(loaders,testUrl);loader=loader||findLoaderByMIMEType(loaders,type);loader=loader||findLoaderByInitialBytes(loaders,data);loader=loader||findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.fallbackMimeType);return loader;}function validHTTPResponse(data){if(data instanceof Response){if(data.status===204){return false;}}return true;}function getNoValidLoaderMessage(data){var{url,type}=getResourceUrlAndType(data);var message='No valid loader found (';message+=url?"".concat(filename(url),", "):'no url provided, ';message+="MIME type: ".concat(type?"\"".concat(type,"\""):'not provided',", ");var firstCharacters=data?getFirstCharacters(data):'';message+=firstCharacters?" first bytes: \"".concat(firstCharacters,"\""):'first bytes: not available';message+=')';return message;}function normalizeLoaders(loaders){for(var loader of loaders){normalizeLoader(loader);}}function findLoaderByUrl(loaders,url){var match=url&&EXT_PATTERN.exec(url);var extension=match&&match[1];return extension?findLoaderByExtension(loaders,extension):null;}function findLoaderByExtension(loaders,extension){extension=extension.toLowerCase();for(var loader of loaders){for(var loaderExtension of loader.extensions){if(loaderExtension.toLowerCase()===extension){return loader;}}}return null;}function findLoaderByMIMEType(loaders,mimeType){for(var loader of loaders){if(loader.mimeTypes&&loader.mimeTypes.includes(mimeType)){return loader;}if(mimeType==="application/x.".concat(loader.id)){return loader;}}return null;}function findLoaderByInitialBytes(loaders,data){if(!data){return null;}for(var loader of loaders){if(typeof data==='string'){if(testDataAgainstText(data,loader)){return loader;}}else if(ArrayBuffer.isView(data)){if(testDataAgainstBinary(data.buffer,data.byteOffset,loader)){return loader;}}else if(data instanceof ArrayBuffer){var byteOffset=0;if(testDataAgainstBinary(data,byteOffset,loader)){return loader;}}}return null;}function testDataAgainstText(data,loader){if(loader.testText){return loader.testText(data);}var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(test=>data.startsWith(test));}function testDataAgainstBinary(data,byteOffset,loader){var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(test=>testBinary(data,byteOffset,loader,test));}function testBinary(data,byteOffset,loader,test){if(test instanceof ArrayBuffer){return compareArrayBuffers(test,data,test.byteLength);}switch(typeof test){case'function':return test(data,loader);case'string':var magic=getMagicString$2(data,byteOffset,test.length);return test===magic;default:return false;}}function getFirstCharacters(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$2(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$2(data,byteOffset,length);}return '';}function getMagicString$2(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength<byteOffset+length){return '';}var dataView=new DataView(arrayBuffer);var magic='';for(var _i6=0;_i6<length;_i6++){magic+=String.fromCharCode(dataView.getUint8(byteOffset+_i6));}return magic;}var DEFAULT_CHUNK_SIZE$2=256*1024;function*makeStringIterator(string,options){var chunkSize=(options===null||options===void 0?void 0:options.chunkSize)||DEFAULT_CHUNK_SIZE$2;var offset=0;var textEncoder=new TextEncoder();while(offset<string.length){var chunkLength=Math.min(string.length-offset,chunkSize);var chunk=string.slice(offset,offset+chunkLength);offset+=chunkLength;yield textEncoder.encode(chunk);}}var DEFAULT_CHUNK_SIZE$1=256*1024;function makeArrayBufferIterator(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return function*(){var{chunkSize=DEFAULT_CHUNK_SIZE$1}=options;var byteOffset=0;while(byteOffset<arrayBuffer.byteLength){var chunkByteLength=Math.min(arrayBuffer.byteLength-byteOffset,chunkSize);var chunk=new ArrayBuffer(chunkByteLength);var sourceArray=new Uint8Array(arrayBuffer,byteOffset,chunkByteLength);var chunkArray=new Uint8Array(chunk);chunkArray.set(sourceArray);byteOffset+=chunkByteLength;yield chunk;}}();}var DEFAULT_CHUNK_SIZE=1024*1024;function makeBlobIterator(_x,_x2){return _makeBlobIterator.apply(this,arguments);}function _makeBlobIterator(){_makeBlobIterator=_wrapAsyncGenerator(function*(blob,options){var chunkSize=(options===null||options===void 0?void 0:options.chunkSize)||DEFAULT_CHUNK_SIZE;var offset=0;while(offset<blob.size){var end=offset+chunkSize;var chunk=yield _awaitAsyncGenerator(blob.slice(offset,end).arrayBuffer());offset=end;yield chunk;}});return _makeBlobIterator.apply(this,arguments);}function makeStreamIterator(stream,options){return isBrowser$2?makeBrowserStreamIterator(stream,options):makeNodeStreamIterator(stream);}function makeBrowserStreamIterator(_x3,_x4){return _makeBrowserStreamIterator.apply(this,arguments);}function _makeBrowserStreamIterator(){_makeBrowserStreamIterator=_wrapAsyncGenerator(function*(stream,options){var reader=stream.getReader();var nextBatchPromise;try{while(true){var currentBatchPromise=nextBatchPromise||reader.read();if(options!==null&&options!==void 0&&options._streamReadAhead){nextBatchPromise=reader.read();}var{done,value}=yield _awaitAsyncGenerator(currentBatchPromise);if(done){return;}yield toArrayBuffer(value);}}catch(error){reader.releaseLock();}});return _makeBrowserStreamIterator.apply(this,arguments);}function makeNodeStreamIterator(_x5,_x6){return _makeNodeStreamIterator.apply(this,arguments);}function _makeNodeStreamIterator(){_makeNodeStreamIterator=_wrapAsyncGenerator(function*(stream,options){var _iteratorAbruptCompletion2=false;var _didIteratorError2=false;var _iteratorError2;try{for(var _iterator2=_asyncIterator(stream),_step2;_iteratorAbruptCompletion2=!(_step2=yield _awaitAsyncGenerator(_iterator2.next())).done;_iteratorAbruptCompletion2=false){var chunk=_step2.value;{yield toArrayBuffer(chunk);}}}catch(err){_didIteratorError2=true;_iteratorError2=err;}finally{try{if(_iteratorAbruptCompletion2&&_iterator2.return!=null){yield _awaitAsyncGenerator(_iterator2.return());}}finally{if(_didIteratorError2){throw _iteratorError2;}}}});return _makeNodeStreamIterator.apply(this,arguments);}function makeIterator(data,options){if(typeof data==='string'){return makeStringIterator(data,options);}if(data instanceof ArrayBuffer){return makeArrayBufferIterator(data,options);}if(isBlob(data)){return makeBlobIterator(data,options);}if(isReadableStream(data)){return makeStreamIterator(data,options);}if(isResponse(data)){var response=data;return makeStreamIterator(response.body,options);}throw new Error('makeIterator');}var ERR_DATA='Cannot convert supplied data type';function getArrayBufferOrStringFromDataSync(data,loader,options){if(loader.text&&typeof data==='string'){return data;}if(isBuffer(data)){data=data.buffer;}if(data instanceof ArrayBuffer){var arrayBuffer=data;if(loader.text&&!loader.binary){var textDecoder=new TextDecoder('utf8');return textDecoder.decode(arrayBuffer);}return arrayBuffer;}if(ArrayBuffer.isView(data)){if(loader.text&&!loader.binary){var _textDecoder=new TextDecoder('utf8');return _textDecoder.decode(data);}var _arrayBuffer=data.buffer;var byteLength=data.byteLength||data.length;if(data.byteOffset!==0||byteLength!==_arrayBuffer.byteLength){_arrayBuffer=_arrayBuffer.slice(data.byteOffset,data.byteOffset+byteLength);}return _arrayBuffer;}throw new Error(ERR_DATA);}function getArrayBufferOrStringFromData(_x26,_x27,_x28){return _getArrayBufferOrStringFromData.apply(this,arguments);}function _getArrayBufferOrStringFromData(){_getArrayBufferOrStringFromData=_asyncToGenerator(function*(data,loader,options){var isArrayBuffer=data instanceof ArrayBuffer||ArrayBuffer.isView(data);if(typeof data==='string'||isArrayBuffer){return getArrayBufferOrStringFromDataSync(data,loader);}if(isBlob(data)){data=yield makeResponse(data);}if(isResponse(data)){var response=data;yield checkResponse(response);return loader.binary?yield response.arrayBuffer():yield response.text();}if(isReadableStream(data)){data=makeIterator(data,options);}if(isIterable(data)||isAsyncIterable(data)){return concatenateArrayBuffersAsync(data);}throw new Error(ERR_DATA);});return _getArrayBufferOrStringFromData.apply(this,arguments);}function getLoaderContext(context,options){var previousContext=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(previousContext){return previousContext;}var resolvedContext=_objectSpread2({fetch:getFetchFunction(options,context)},context);if(!Array.isArray(resolvedContext.loaders)){resolvedContext.loaders=null;}return resolvedContext;}function getLoadersFromContext(loaders,context){if(!context&&loaders&&!Array.isArray(loaders)){return loaders;}var candidateLoaders;if(loaders){candidateLoaders=Array.isArray(loaders)?loaders:[loaders];}if(context&&context.loaders){var contextLoaders=Array.isArray(context.loaders)?context.loaders:[context.loaders];candidateLoaders=candidateLoaders?[...candidateLoaders,...contextLoaders]:contextLoaders;}return candidateLoaders&&candidateLoaders.length?candidateLoaders:null;}function parse$3(_x29,_x30,_x31,_x32){return _parse$.apply(this,arguments);}function _parse$(){_parse$=_asyncToGenerator(function*(data,loaders,options,context){assert$6(!context||typeof context==='object');if(loaders&&!Array.isArray(loaders)&&!isLoaderObject(loaders)){context=undefined;options=loaders;loaders=undefined;}data=yield data;options=options||{};var{url}=getResourceUrlAndType(data);var typedLoaders=loaders;var candidateLoaders=getLoadersFromContext(typedLoaders,context);var loader=yield selectLoader(data,candidateLoaders,options);if(!loader){return null;}options=normalizeOptions(options,loader,candidateLoaders,url);context=getLoaderContext({url,parse:parse$3,loaders:candidateLoaders},options,context);return yield parseWithLoader(loader,data,options,context);});return _parse$.apply(this,arguments);}function parseWithLoader(_x33,_x34,_x35,_x36){return _parseWithLoader.apply(this,arguments);}function _parseWithLoader(){_parseWithLoader=_asyncToGenerator(function*(loader,data,options,context){validateWorkerVersion(loader);data=yield getArrayBufferOrStringFromData(data,loader,options);if(loader.parseTextSync&&typeof data==='string'){options.dataType='text';return loader.parseTextSync(data,options,context,loader);}if(canParseWithWorker(loader,options)){return yield parseWithWorker(loader,data,options,context,parse$3);}if(loader.parseText&&typeof data==='string'){return yield loader.parseText(data,options,context,loader);}if(loader.parse){return yield loader.parse(data,options,context,loader);}assert$6(!loader.parseSync);throw new Error("".concat(loader.id," loader - no parser found and worker is disabled"));});return _parseWithLoader.apply(this,arguments);}function load(_x37,_x38,_x39,_x40){return _load.apply(this,arguments);}function _load(){_load=_asyncToGenerator(function*(url,loaders,options,context){if(!Array.isArray(loaders)&&!isLoaderObject(loaders)){options=loaders;loaders=undefined;}var fetch=getFetchFunction(options);var data=url;if(typeof url==='string'){data=yield fetch(url);}if(isBlob(url)){data=yield fetch(url);}return yield parse$3(data,loaders,options);});return _load.apply(this,arguments);}function assert$4(condition,message){if(!condition){throw new Error("math.gl assertion ".concat(message));}}var RADIANS_TO_DEGREES=1/Math.PI*180;var DEGREES_TO_RADIANS=1/180*Math.PI;var config$2={};config$2.EPSILON=1e-12;config$2.debug=false;config$2.precision=4;config$2.printTypes=false;config$2.printDegrees=false;config$2.printRowMajor=true;function round(value){return Math.round(value/config$2.EPSILON)*config$2.EPSILON;}function formatValue(value){var{precision=config$2.precision||4}=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};value=round(value);return "".concat(parseFloat(value.toPrecision(precision)));}function isArray(value){return Array.isArray(value)||ArrayBuffer.isView(value)&&!(value instanceof DataView);}function duplicateArray(array){return array.clone?array.clone():new Array(array.length);}function map$1(value,func,result){if(isArray(value)){result=result||duplicateArray(value);for(var _i7=0;_i7<result.length&&_i7<value.length;++_i7){result[_i7]=func(value[_i7],_i7,result);}return result;}return func(value);}function toRadians(degrees){return radians(degrees);}function toDegrees(radians){return degrees(radians);}function radians(degrees,result){return map$1(degrees,degrees=>degrees*DEGREES_TO_RADIANS,result);}function degrees(radians,result){return map$1(radians,radians=>radians*RADIANS_TO_DEGREES,result);}function clamp$1(value,min,max){return map$1(value,value=>Math.max(min,Math.min(max,value)));}function equals$1(a,b,epsilon){var oldEpsilon=config$2.EPSILON;if(epsilon){config$2.EPSILON=epsilon;}try{if(a===b){return true;}if(isArray(a)&&isArray(b)){if(a.length!==b.length){return false;}for(var _i8=0;_i8<a.length;++_i8){if(!equals$1(a[_i8],b[_i8])){return false;}}return true;}if(a&&a.equals){return a.equals(b);}if(b&&b.equals){return b.equals(a);}if(Number.isFinite(a)&&Number.isFinite(b)){return Math.abs(a-b)<=config$2.EPSILON*Math.max(1.0,Math.abs(a),Math.abs(b));}return false;}finally{config$2.EPSILON=oldEpsilon;}}function _extendableBuiltin(cls){function ExtendableBuiltin(){var instance=Reflect.construct(cls,Array.from(arguments));Object.setPrototypeOf(instance,Object.getPrototypeOf(this));return instance;}ExtendableBuiltin.prototype=Object.create(cls.prototype,{constructor:{value:cls,enumerable:false,writable:true,configurable:true}});if(Object.setPrototypeOf){Object.setPrototypeOf(ExtendableBuiltin,cls);}else {ExtendableBuiltin.__proto__=cls;}return ExtendableBuiltin;}class MathArray extends _extendableBuiltin(Array){get ELEMENTS(){assert$4(false);return 0;}clone(){return new this.constructor().copy(this);}from(arrayOrObject){return Array.isArray(arrayOrObject)?this.copy(arrayOrObject):this.fromObject(arrayOrObject);}fromArray(array){var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i9=0;_i9<this.ELEMENTS;++_i9){this[_i9]=array[_i9+offset];}return this.check();}to(arrayOrObject){if(arrayOrObject===this){return this;}return isArray(arrayOrObject)?this.toArray(arrayOrObject):this.toObject(arrayOrObject);}toTarget(target){return target?this.to(target):this;}toArray(){var array=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var offset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;for(var _i10=0;_i10<this.ELEMENTS;++_i10){array[offset+_i10]=this[_i10];}return array;}toFloat32Array(){return new Float32Array(this);}toString(){return this.formatString(config$2);}formatString(opts){var string='';for(var _i11=0;_i11<this.ELEMENTS;++_i11){string+=(_i11>0?', ':'')+formatValue(this[_i11],opts);}return "".concat(opts.printTypes?this.constructor.name:'',"[").concat(string,"]");}equals(array){if(!array||this.length!==array.length){return false;}for(var _i12=0;_i12<this.ELEMENTS;++_i12){if(!equals$1(this[_i12],array[_i12])){return false;}}return true;}exactEquals(array){if(!array||this.length!==array.length){return false;}for(var _i13=0;_i13<this.ELEMENTS;++_i13){if(this[_i13]!==array[_i13]){return false;}}return true;}negate(){for(var _i14=0;_i14<this.ELEMENTS;++_i14){this[_i14]=-this[_i14];}return this.check();}lerp(a,b,t){if(t===undefined){t=b;b=a;a=this;}for(var _i15=0;_i15<this.ELEMENTS;++_i15){var ai=a[_i15];this[_i15]=ai+t*(b[_i15]-ai);}return this.check();}min(vector){for(var _i16=0;_i16<this.ELEMENTS;++_i16){this[_i16]=Math.min(vector[_i16],this[_i16]);}return this.check();}max(vector){for(var _i17=0;_i17<this.ELEMENTS;++_i17){this[_i17]=Math.max(vector[_i17],this[_i17]);}return this.check();}clamp(minVector,maxVector){for(var _i18=0;_i18<this.ELEMENTS;++_i18){this[_i18]=Math.min(Math.max(this[_i18],minVector[_i18]),maxVector[_i18]);}return this.check();}add(){for(var _len7=arguments.length,vectors=new Array(_len7),_key7=0;_key7<_len7;_key7++){vectors[_key7]=arguments[_key7];}for(var vector of vectors){for(var _i19=0;_i19<this.ELEMENTS;++_i19){this[_i19]+=vector[_i19];}}return this.check();}subtract(){for(var _len8=arguments.length,vectors=new Array(_len8),_key8=0;_key8<_len8;_key8++){vectors[_key8]=arguments[_key8];}for(var vector of vectors){for(var _i20=0;_i20<this.ELEMENTS;++_i20){this[_i20]-=vector[_i20];}}return this.check();}scale(scale){if(Array.isArray(scale)){return this.multiply(scale);}for(var _i21=0;_i21<this.ELEMENTS;++_i21){this[_i21]*=scale;}return this.check();}sub(a){return this.subtract(a);}setScalar(a){for(var _i22=0;_i22<this.ELEMENTS;++_i22){this[_i22]=a;}return this.check();}addScalar(a){for(var _i23=0;_i23<this.ELEMENTS;++_i23){this[_i23]+=a;}return this.check();}subScalar(a){return this.addScalar(-a);}multiplyScalar(scalar){for(var _i24=0;_i24<this.ELEMENTS;++_i24){this[_i24]*=scalar;}return this.check();}divideScalar(a){return this.scale(1/a);}clampScalar(min,max){for(var _i25=0;_i25<this.ELEMENTS;++_i25){this[_i25]=Math.min(Math.max(this[_i25],min),max);}return this.check();}multiplyByScalar(scalar){return this.scale(scalar);}get elements(){return this;}check(){if(config$2.debug&&!this.validate()){throw new Error("math.gl: ".concat(this.constructor.name," some fields set to invalid numbers'"));}return this;}validate(){var valid=this.length===this.ELEMENTS;for(var _i26=0;_i26<this.ELEMENTS;++_i26){valid=valid&&Number.isFinite(this[_i26]);}return valid;}}function validateVector(v,length){if(v.length!==length){return false;}for(var _i27=0;_i27<v.length;++_i27){if(!Number.isFinite(v[_i27])){return false;}}return true;}function checkNumber(value){if(!Number.isFinite(value)){throw new Error("Invalid number ".concat(value));}return value;}function checkVector(v,length){var callerName=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';if(config$2.debug&&!validateVector(v,length)){throw new Error("math.gl: ".concat(callerName," some fields set to invalid numbers'"));}return v;}var map={};function deprecated(method,version){if(!map[method]){map[method]=true;console.warn("".concat(method," has been removed in version ").concat(version,", see upgrade guide for more information"));}}class Vector extends MathArray{get ELEMENTS(){assert$4(false);return 0;}copy(vector){assert$4(false);return this;}get x(){return this[0];}set x(value){this[0]=checkNumber(value);}get y(){return this[1];}set y(value){this[1]=checkNumber(value);}len(){return Math.sqrt(this.lengthSquared());}magnitude(){return this.len();}lengthSquared(){var length=0;for(var _i28=0;_i28<this.ELEMENTS;++_i28){length+=this[_i28]*this[_i28];}return length;}magnitudeSquared(){return this.lengthSquared();}distance(mathArray){return Math.sqrt(this.distanceSquared(mathArray));}distanceSquared(mathArray){var length=0;for(var _i29=0;_i29<this.ELEMENTS;++_i29){var dist=this[_i29]-mathArray[_i29];length+=dist*dist;}return checkNumber(length);}dot(mathArray){var product=0;for(var _i30=0;_i30<this.ELEMENTS;++_i30){product+=this[_i30]*mathArray[_i30];}return checkNumber(product);}normalize(){var length=this.magnitude();if(length!==0){for(var _i31=0;_i31<this.ELEMENTS;++_i31){this[_i31]/=length;}}return this.check();}multiply(){for(var _len9=arguments.length,vectors=new Array(_len9),_key9=0;_key9<_len9;_key9++){vectors[_key9]=arguments[_key9];}for(var vector of vectors){for(var _i32=0;_i32<this.ELEMENTS;++_i32){this[_i32]*=vector[_i32];}}return this.check();}divide(){for(var _len10=arguments.length,vectors=new Array(_len10),_key10=0;_key10<_len10;_key10++){vectors[_key10]=arguments[_key10];}for(var vector of vectors){for(var _i33=0;_i33<this.ELEMENTS;++_i33){this[_i33]/=vector[_i33];}}return this.check();}lengthSq(){return this.lengthSquared();}distanceTo(vector){return this.distance(vector);}distanceToSquared(vector){return this.distanceSquared(vector);}getComponent(i){assert$4(i>=0&&i<this.ELEMENTS,'index is out of range');return checkNumber(this[i]);}setComponent(i,value){assert$4(i>=0&&i<this.ELEMENTS,'index is out of range');this[i]=value;return this.check();}addVectors(a,b){return this.copy(a).add(b);}subVectors(a,b){return this.copy(a).subtract(b);}multiplyVectors(a,b){return this.copy(a).multiply(b);}addScaledVector(a,b){return this.add(new this.constructor(a).multiplyScalar(b));}}/**
  78203. * Common utilities
  78204. * @module glMatrix
  78205. */ // Configuration Constants
  78206. var EPSILON=0.000001;var ARRAY_TYPE=typeof Float32Array!=='undefined'?Float32Array:Array;if(!Math.hypot)Math.hypot=function(){var y=0,i=arguments.length;while(i--){y+=arguments[i]*arguments[i];}return Math.sqrt(y);};/**
  78207. * 2 Dimensional Vector
  78208. * @module vec2
  78209. */ /**
  78210. * Creates a new, empty vec2
  78211. *
  78212. * @returns {vec2} a new 2D vector
  78213. */function create$4(){var out=new ARRAY_TYPE(2);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;}return out;}/**
  78214. * Transforms the vec2 with a mat2
  78215. *
  78216. * @param {vec2} out the receiving vector
  78217. * @param {ReadonlyVec2} a the vector to transform
  78218. * @param {ReadonlyMat2} m matrix to transform with
  78219. * @returns {vec2} out
  78220. */function transformMat2(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;return out;}/**
  78221. * Transforms the vec2 with a mat2d
  78222. *
  78223. * @param {vec2} out the receiving vector
  78224. * @param {ReadonlyVec2} a the vector to transform
  78225. * @param {ReadonlyMat2d} m matrix to transform with
  78226. * @returns {vec2} out
  78227. */function transformMat2d(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[2]*y+m[4];out[1]=m[1]*x+m[3]*y+m[5];return out;}/**
  78228. * Transforms the vec2 with a mat3
  78229. * 3rd vector component is implicitly '1'
  78230. *
  78231. * @param {vec2} out the receiving vector
  78232. * @param {ReadonlyVec2} a the vector to transform
  78233. * @param {ReadonlyMat3} m matrix to transform with
  78234. * @returns {vec2} out
  78235. */function transformMat3$1(out,a,m){var x=a[0],y=a[1];out[0]=m[0]*x+m[3]*y+m[6];out[1]=m[1]*x+m[4]*y+m[7];return out;}/**
  78236. * Transforms the vec2 with a mat4
  78237. * 3rd vector component is implicitly '0'
  78238. * 4th vector component is implicitly '1'
  78239. *
  78240. * @param {vec2} out the receiving vector
  78241. * @param {ReadonlyVec2} a the vector to transform
  78242. * @param {ReadonlyMat4} m matrix to transform with
  78243. * @returns {vec2} out
  78244. */function transformMat4$2(out,a,m){var x=a[0];var y=a[1];out[0]=m[0]*x+m[4]*y+m[12];out[1]=m[1]*x+m[5]*y+m[13];return out;}/**
  78245. * Perform some operation over an array of vec2s.
  78246. *
  78247. * @param {Array} a the array of vectors to iterate over
  78248. * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed
  78249. * @param {Number} offset Number of elements to skip at the beginning of the array
  78250. * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array
  78251. * @param {Function} fn Function to call for each vector in the array
  78252. * @param {Object} [arg] additional argument to pass to fn
  78253. * @returns {Array} a
  78254. * @function
  78255. */(function(){var vec=create$4();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=2;}if(!offset){offset=0;}if(count){l=Math.min(count*stride+offset,a.length);}else {l=a.length;}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];}return a;};})();function vec2_transformMat4AsVector(out,a,m){var x=a[0];var y=a[1];var w=m[3]*x+m[7]*y||1.0;out[0]=(m[0]*x+m[4]*y)/w;out[1]=(m[1]*x+m[5]*y)/w;return out;}function vec3_transformMat4AsVector(out,a,m){var x=a[0];var y=a[1];var z=a[2];var w=m[3]*x+m[7]*y+m[11]*z||1.0;out[0]=(m[0]*x+m[4]*y+m[8]*z)/w;out[1]=(m[1]*x+m[5]*y+m[9]*z)/w;out[2]=(m[2]*x+m[6]*y+m[10]*z)/w;return out;}function vec3_transformMat2(out,a,m){var x=a[0];var y=a[1];out[0]=m[0]*x+m[2]*y;out[1]=m[1]*x+m[3]*y;out[2]=a[2];return out;}function vec4_transformMat3(out,a,m){var x=a[0];var y=a[1];var z=a[2];out[0]=m[0]*x+m[3]*y+m[6]*z;out[1]=m[1]*x+m[4]*y+m[7]*z;out[2]=m[2]*x+m[5]*y+m[8]*z;out[3]=a[3];return out;}class Vector2$1 extends Vector{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;super(2);if(isArray(x)&&arguments.length===1){this.copy(x);}else {if(config$2.debug){checkNumber(x);checkNumber(y);}this[0]=x;this[1]=y;}}set(x,y){this[0]=x;this[1]=y;return this.check();}copy(array){this[0]=array[0];this[1]=array[1];return this.check();}fromObject(object){if(config$2.debug){checkNumber(object.x);checkNumber(object.y);}this[0]=object.x;this[1]=object.y;return this.check();}toObject(object){object.x=this[0];object.y=this[1];return object;}get ELEMENTS(){return 2;}horizontalAngle(){return Math.atan2(this.y,this.x);}verticalAngle(){return Math.atan2(this.x,this.y);}transform(matrix4){return this.transformAsPoint(matrix4);}transformAsPoint(matrix4){transformMat4$2(this,this,matrix4);return this.check();}transformAsVector(matrix4){vec2_transformMat4AsVector(this,this,matrix4);return this.check();}transformByMatrix3(matrix3){transformMat3$1(this,this,matrix3);return this.check();}transformByMatrix2x3(matrix2x3){transformMat2d(this,this,matrix2x3);return this.check();}transformByMatrix2(matrix2){transformMat2(this,this,matrix2);return this.check();}}/**
  78256. * 3 Dimensional Vector
  78257. * @module vec3
  78258. */ /**
  78259. * Creates a new, empty vec3
  78260. *
  78261. * @returns {vec3} a new 3D vector
  78262. */function create$3(){var out=new ARRAY_TYPE(3);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0;}return out;}/**
  78263. * Calculates the length of a vec3
  78264. *
  78265. * @param {ReadonlyVec3} a vector to calculate length of
  78266. * @returns {Number} length of a
  78267. */function length$2(a){var x=a[0];var y=a[1];var z=a[2];return Math.hypot(x,y,z);}/**
  78268. * Creates a new vec3 initialized with the given values
  78269. *
  78270. * @param {Number} x X component
  78271. * @param {Number} y Y component
  78272. * @param {Number} z Z component
  78273. * @returns {vec3} a new 3D vector
  78274. */function fromValues(x,y,z){var out=new ARRAY_TYPE(3);out[0]=x;out[1]=y;out[2]=z;return out;}/**
  78275. * Normalize a vec3
  78276. *
  78277. * @param {vec3} out the receiving vector
  78278. * @param {ReadonlyVec3} a vector to normalize
  78279. * @returns {vec3} out
  78280. */function normalize$2(out,a){var x=a[0];var y=a[1];var z=a[2];var len=x*x+y*y+z*z;if(len>0){//TODO: evaluate use of glm_invsqrt here?
  78281. len=1/Math.sqrt(len);}out[0]=a[0]*len;out[1]=a[1]*len;out[2]=a[2]*len;return out;}/**
  78282. * Calculates the dot product of two vec3's
  78283. *
  78284. * @param {ReadonlyVec3} a the first operand
  78285. * @param {ReadonlyVec3} b the second operand
  78286. * @returns {Number} dot product of a and b
  78287. */function dot$2(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2];}/**
  78288. * Computes the cross product of two vec3's
  78289. *
  78290. * @param {vec3} out the receiving vector
  78291. * @param {ReadonlyVec3} a the first operand
  78292. * @param {ReadonlyVec3} b the second operand
  78293. * @returns {vec3} out
  78294. */function cross(out,a,b){var ax=a[0],ay=a[1],az=a[2];var bx=b[0],by=b[1],bz=b[2];out[0]=ay*bz-az*by;out[1]=az*bx-ax*bz;out[2]=ax*by-ay*bx;return out;}/**
  78295. * Transforms the vec3 with a mat4.
  78296. * 4th vector component is implicitly '1'
  78297. *
  78298. * @param {vec3} out the receiving vector
  78299. * @param {ReadonlyVec3} a the vector to transform
  78300. * @param {ReadonlyMat4} m matrix to transform with
  78301. * @returns {vec3} out
  78302. */function transformMat4$1(out,a,m){var x=a[0],y=a[1],z=a[2];var w=m[3]*x+m[7]*y+m[11]*z+m[15];w=w||1.0;out[0]=(m[0]*x+m[4]*y+m[8]*z+m[12])/w;out[1]=(m[1]*x+m[5]*y+m[9]*z+m[13])/w;out[2]=(m[2]*x+m[6]*y+m[10]*z+m[14])/w;return out;}/**
  78303. * Transforms the vec3 with a mat3.
  78304. *
  78305. * @param {vec3} out the receiving vector
  78306. * @param {ReadonlyVec3} a the vector to transform
  78307. * @param {ReadonlyMat3} m the 3x3 matrix to transform with
  78308. * @returns {vec3} out
  78309. */function transformMat3(out,a,m){var x=a[0],y=a[1],z=a[2];out[0]=x*m[0]+y*m[3]+z*m[6];out[1]=x*m[1]+y*m[4]+z*m[7];out[2]=x*m[2]+y*m[5]+z*m[8];return out;}/**
  78310. * Transforms the vec3 with a quat
  78311. * Can also be used for dual quaternions. (Multiply it with the real part)
  78312. *
  78313. * @param {vec3} out the receiving vector
  78314. * @param {ReadonlyVec3} a the vector to transform
  78315. * @param {ReadonlyQuat} q quaternion to transform with
  78316. * @returns {vec3} out
  78317. */function transformQuat$1(out,a,q){// benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed
  78318. var qx=q[0],qy=q[1],qz=q[2],qw=q[3];var x=a[0],y=a[1],z=a[2];// var qvec = [qx, qy, qz];
  78319. // var uv = vec3.cross([], qvec, a);
  78320. var uvx=qy*z-qz*y,uvy=qz*x-qx*z,uvz=qx*y-qy*x;// var uuv = vec3.cross([], qvec, uv);
  78321. var uuvx=qy*uvz-qz*uvy,uuvy=qz*uvx-qx*uvz,uuvz=qx*uvy-qy*uvx;// vec3.scale(uv, uv, 2 * w);
  78322. var w2=qw*2;uvx*=w2;uvy*=w2;uvz*=w2;// vec3.scale(uuv, uuv, 2);
  78323. uuvx*=2;uuvy*=2;uuvz*=2;// return vec3.add(out, a, vec3.add(out, uv, uuv));
  78324. out[0]=x+uvx+uuvx;out[1]=y+uvy+uuvy;out[2]=z+uvz+uuvz;return out;}/**
  78325. * Rotate a 3D vector around the x-axis
  78326. * @param {vec3} out The receiving vec3
  78327. * @param {ReadonlyVec3} a The vec3 point to rotate
  78328. * @param {ReadonlyVec3} b The origin of the rotation
  78329. * @param {Number} rad The angle of rotation in radians
  78330. * @returns {vec3} out
  78331. */function rotateX$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin
  78332. p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation
  78333. r[0]=p[0];r[1]=p[1]*Math.cos(rad)-p[2]*Math.sin(rad);r[2]=p[1]*Math.sin(rad)+p[2]*Math.cos(rad);//translate to correct position
  78334. out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/**
  78335. * Rotate a 3D vector around the y-axis
  78336. * @param {vec3} out The receiving vec3
  78337. * @param {ReadonlyVec3} a The vec3 point to rotate
  78338. * @param {ReadonlyVec3} b The origin of the rotation
  78339. * @param {Number} rad The angle of rotation in radians
  78340. * @returns {vec3} out
  78341. */function rotateY$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin
  78342. p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation
  78343. r[0]=p[2]*Math.sin(rad)+p[0]*Math.cos(rad);r[1]=p[1];r[2]=p[2]*Math.cos(rad)-p[0]*Math.sin(rad);//translate to correct position
  78344. out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/**
  78345. * Rotate a 3D vector around the z-axis
  78346. * @param {vec3} out The receiving vec3
  78347. * @param {ReadonlyVec3} a The vec3 point to rotate
  78348. * @param {ReadonlyVec3} b The origin of the rotation
  78349. * @param {Number} rad The angle of rotation in radians
  78350. * @returns {vec3} out
  78351. */function rotateZ$2(out,a,b,rad){var p=[],r=[];//Translate point to the origin
  78352. p[0]=a[0]-b[0];p[1]=a[1]-b[1];p[2]=a[2]-b[2];//perform rotation
  78353. r[0]=p[0]*Math.cos(rad)-p[1]*Math.sin(rad);r[1]=p[0]*Math.sin(rad)+p[1]*Math.cos(rad);r[2]=p[2];//translate to correct position
  78354. out[0]=r[0]+b[0];out[1]=r[1]+b[1];out[2]=r[2]+b[2];return out;}/**
  78355. * Get the angle between two 3D vectors
  78356. * @param {ReadonlyVec3} a The first operand
  78357. * @param {ReadonlyVec3} b The second operand
  78358. * @returns {Number} The angle in radians
  78359. */function angle$1(a,b){var ax=a[0],ay=a[1],az=a[2],bx=b[0],by=b[1],bz=b[2],mag1=Math.sqrt(ax*ax+ay*ay+az*az),mag2=Math.sqrt(bx*bx+by*by+bz*bz),mag=mag1*mag2,cosine=mag&&dot$2(a,b)/mag;return Math.acos(Math.min(Math.max(cosine,-1),1));}/**
  78360. * Alias for {@link vec3.length}
  78361. * @function
  78362. */var len=length$2;/**
  78363. * Perform some operation over an array of vec3s.
  78364. *
  78365. * @param {Array} a the array of vectors to iterate over
  78366. * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed
  78367. * @param {Number} offset Number of elements to skip at the beginning of the array
  78368. * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array
  78369. * @param {Function} fn Function to call for each vector in the array
  78370. * @param {Object} [arg] additional argument to pass to fn
  78371. * @returns {Array} a
  78372. * @function
  78373. */(function(){var vec=create$3();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=3;}if(!offset){offset=0;}if(count){l=Math.min(count*stride+offset,a.length);}else {l=a.length;}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];}return a;};})();var ORIGIN=[0,0,0];var constants$2={};class Vector3$1 extends Vector{static get ZERO(){return constants$2.ZERO=constants$2.ZERO||Object.freeze(new Vector3$1(0,0,0,0));}constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;super(-0,-0,-0);if(arguments.length===1&&isArray(x)){this.copy(x);}else {if(config$2.debug){checkNumber(x);checkNumber(y);checkNumber(z);}this[0]=x;this[1]=y;this[2]=z;}}set(x,y,z){this[0]=x;this[1]=y;this[2]=z;return this.check();}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];return this.check();}fromObject(object){if(config$2.debug){checkNumber(object.x);checkNumber(object.y);checkNumber(object.z);}this[0]=object.x;this[1]=object.y;this[2]=object.z;return this.check();}toObject(object){object.x=this[0];object.y=this[1];object.z=this[2];return object;}get ELEMENTS(){return 3;}get z(){return this[2];}set z(value){this[2]=checkNumber(value);}angle(vector){return angle$1(this,vector);}cross(vector){cross(this,this,vector);return this.check();}rotateX(_ref4){var{radians,origin=ORIGIN}=_ref4;rotateX$2(this,this,origin,radians);return this.check();}rotateY(_ref5){var{radians,origin=ORIGIN}=_ref5;rotateY$2(this,this,origin,radians);return this.check();}rotateZ(_ref6){var{radians,origin=ORIGIN}=_ref6;rotateZ$2(this,this,origin,radians);return this.check();}transform(matrix4){return this.transformAsPoint(matrix4);}transformAsPoint(matrix4){transformMat4$1(this,this,matrix4);return this.check();}transformAsVector(matrix4){vec3_transformMat4AsVector(this,this,matrix4);return this.check();}transformByMatrix3(matrix3){transformMat3(this,this,matrix3);return this.check();}transformByMatrix2(matrix2){vec3_transformMat2(this,this,matrix2);return this.check();}transformByQuaternion(quaternion){transformQuat$1(this,this,quaternion);return this.check();}}class Matrix extends MathArray{get ELEMENTS(){assert$4(false);return 0;}get RANK(){assert$4(false);return 0;}toString(){var string='[';if(config$2.printRowMajor){string+='row-major:';for(var row=0;row<this.RANK;++row){for(var col=0;col<this.RANK;++col){string+=" ".concat(this[col*this.RANK+row]);}}}else {string+='column-major:';for(var _i34=0;_i34<this.ELEMENTS;++_i34){string+=" ".concat(this[_i34]);}}string+=']';return string;}getElementIndex(row,col){return col*this.RANK+row;}getElement(row,col){return this[col*this.RANK+row];}setElement(row,col,value){this[col*this.RANK+row]=checkNumber(value);return this;}getColumn(columnIndex){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Array(this.RANK).fill(-0);var firstIndex=columnIndex*this.RANK;for(var _i35=0;_i35<this.RANK;++_i35){result[_i35]=this[firstIndex+_i35];}return result;}setColumn(columnIndex,columnVector){var firstIndex=columnIndex*this.RANK;for(var _i36=0;_i36<this.RANK;++_i36){this[firstIndex+_i36]=columnVector[_i36];}return this;}}/**
  78374. * 3x3 Matrix
  78375. * @module mat3
  78376. */ /**
  78377. * Creates a new identity mat3
  78378. *
  78379. * @returns {mat3} a new 3x3 matrix
  78380. */function create$2(){var out=new ARRAY_TYPE(9);if(ARRAY_TYPE!=Float32Array){out[1]=0;out[2]=0;out[3]=0;out[5]=0;out[6]=0;out[7]=0;}out[0]=1;out[4]=1;out[8]=1;return out;}/**
  78381. * Transpose the values of a mat3
  78382. *
  78383. * @param {mat3} out the receiving matrix
  78384. * @param {ReadonlyMat3} a the source matrix
  78385. * @returns {mat3} out
  78386. */function transpose$1(out,a){// If we are transposing ourselves we can skip a few steps but have to cache some values
  78387. if(out===a){var a01=a[1],a02=a[2],a12=a[5];out[1]=a[3];out[2]=a[6];out[3]=a01;out[5]=a[7];out[6]=a02;out[7]=a12;}else {out[0]=a[0];out[1]=a[3];out[2]=a[6];out[3]=a[1];out[4]=a[4];out[5]=a[7];out[6]=a[2];out[7]=a[5];out[8]=a[8];}return out;}/**
  78388. * Inverts a mat3
  78389. *
  78390. * @param {mat3} out the receiving matrix
  78391. * @param {ReadonlyMat3} a the source matrix
  78392. * @returns {mat3} out
  78393. */function invert$2(out,a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b01=a22*a11-a12*a21;var b11=-a22*a10+a12*a20;var b21=a21*a10-a11*a20;// Calculate the determinant
  78394. var det=a00*b01+a01*b11+a02*b21;if(!det){return null;}det=1.0/det;out[0]=b01*det;out[1]=(-a22*a01+a02*a21)*det;out[2]=(a12*a01-a02*a11)*det;out[3]=b11*det;out[4]=(a22*a00-a02*a20)*det;out[5]=(-a12*a00+a02*a10)*det;out[6]=b21*det;out[7]=(-a21*a00+a01*a20)*det;out[8]=(a11*a00-a01*a10)*det;return out;}/**
  78395. * Calculates the determinant of a mat3
  78396. *
  78397. * @param {ReadonlyMat3} a the source matrix
  78398. * @returns {Number} determinant of a
  78399. */function determinant$1(a){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];return a00*(a22*a11-a12*a21)+a01*(-a22*a10+a12*a20)+a02*(a21*a10-a11*a20);}/**
  78400. * Multiplies two mat3's
  78401. *
  78402. * @param {mat3} out the receiving matrix
  78403. * @param {ReadonlyMat3} a the first operand
  78404. * @param {ReadonlyMat3} b the second operand
  78405. * @returns {mat3} out
  78406. */function multiply$2(out,a,b){var a00=a[0],a01=a[1],a02=a[2];var a10=a[3],a11=a[4],a12=a[5];var a20=a[6],a21=a[7],a22=a[8];var b00=b[0],b01=b[1],b02=b[2];var b10=b[3],b11=b[4],b12=b[5];var b20=b[6],b21=b[7],b22=b[8];out[0]=b00*a00+b01*a10+b02*a20;out[1]=b00*a01+b01*a11+b02*a21;out[2]=b00*a02+b01*a12+b02*a22;out[3]=b10*a00+b11*a10+b12*a20;out[4]=b10*a01+b11*a11+b12*a21;out[5]=b10*a02+b11*a12+b12*a22;out[6]=b20*a00+b21*a10+b22*a20;out[7]=b20*a01+b21*a11+b22*a21;out[8]=b20*a02+b21*a12+b22*a22;return out;}/**
  78407. * Translate a mat3 by the given vector
  78408. *
  78409. * @param {mat3} out the receiving matrix
  78410. * @param {ReadonlyMat3} a the matrix to translate
  78411. * @param {ReadonlyVec2} v vector to translate by
  78412. * @returns {mat3} out
  78413. */function translate$1(out,a,v){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],x=v[0],y=v[1];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a10;out[4]=a11;out[5]=a12;out[6]=x*a00+y*a10+a20;out[7]=x*a01+y*a11+a21;out[8]=x*a02+y*a12+a22;return out;}/**
  78414. * Rotates a mat3 by the given angle
  78415. *
  78416. * @param {mat3} out the receiving matrix
  78417. * @param {ReadonlyMat3} a the matrix to rotate
  78418. * @param {Number} rad the angle to rotate the matrix by
  78419. * @returns {mat3} out
  78420. */function rotate$1(out,a,rad){var a00=a[0],a01=a[1],a02=a[2],a10=a[3],a11=a[4],a12=a[5],a20=a[6],a21=a[7],a22=a[8],s=Math.sin(rad),c=Math.cos(rad);out[0]=c*a00+s*a10;out[1]=c*a01+s*a11;out[2]=c*a02+s*a12;out[3]=c*a10-s*a00;out[4]=c*a11-s*a01;out[5]=c*a12-s*a02;out[6]=a20;out[7]=a21;out[8]=a22;return out;}/**
  78421. * Scales the mat3 by the dimensions in the given vec2
  78422. *
  78423. * @param {mat3} out the receiving matrix
  78424. * @param {ReadonlyMat3} a the matrix to rotate
  78425. * @param {ReadonlyVec2} v the vec2 to scale the matrix by
  78426. * @returns {mat3} out
  78427. **/function scale$3(out,a,v){var x=v[0],y=v[1];out[0]=x*a[0];out[1]=x*a[1];out[2]=x*a[2];out[3]=y*a[3];out[4]=y*a[4];out[5]=y*a[5];out[6]=a[6];out[7]=a[7];out[8]=a[8];return out;}/**
  78428. * Calculates a 3x3 matrix from the given quaternion
  78429. *
  78430. * @param {mat3} out mat3 receiving operation result
  78431. * @param {ReadonlyQuat} q Quaternion to create matrix from
  78432. *
  78433. * @returns {mat3} out
  78434. */function fromQuat$1(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[3]=yx-wz;out[6]=zx+wy;out[1]=yx+wz;out[4]=1-xx-zz;out[7]=zy-wx;out[2]=zx-wy;out[5]=zy+wx;out[8]=1-xx-yy;return out;}var IDENTITY$1=Object.freeze([1,0,0,0,1,0,0,0,1]);var ZERO$1=Object.freeze([0,0,0,0,0,0,0,0,0]);var INDICES$1=Object.freeze({COL0ROW0:0,COL0ROW1:1,COL0ROW2:2,COL1ROW0:3,COL1ROW1:4,COL1ROW2:5,COL2ROW0:6,COL2ROW1:7,COL2ROW2:8});var constants$1={};class Matrix3$1 extends Matrix{static get IDENTITY(){constants$1.IDENTITY=constants$1.IDENTITY||Object.freeze(new Matrix3$1(IDENTITY$1));return constants$1.IDENTITY;}static get ZERO(){constants$1.ZERO=constants$1.ZERO||Object.freeze(new Matrix3$1(ZERO$1));return constants$1.ZERO;}get ELEMENTS(){return 9;}get RANK(){return 3;}get INDICES(){return INDICES$1;}constructor(array){super(-0,-0,-0,-0,-0,-0,-0,-0,-0);if(arguments.length===1&&Array.isArray(array)){this.copy(array);}else {this.identity();}}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];this[3]=array[3];this[4]=array[4];this[5]=array[5];this[6]=array[6];this[7]=array[7];this[8]=array[8];return this.check();}set(m00,m10,m20,m01,m11,m21,m02,m12,m22){this[0]=m00;this[1]=m10;this[2]=m20;this[3]=m01;this[4]=m11;this[5]=m21;this[6]=m02;this[7]=m12;this[8]=m22;return this.check();}setRowMajor(m00,m01,m02,m10,m11,m12,m20,m21,m22){this[0]=m00;this[1]=m10;this[2]=m20;this[3]=m01;this[4]=m11;this[5]=m21;this[6]=m02;this[7]=m12;this[8]=m22;return this.check();}determinant(){return determinant$1(this);}identity(){return this.copy(IDENTITY$1);}fromQuaternion(q){fromQuat$1(this,q);return this.check();}transpose(){transpose$1(this,this);return this.check();}invert(){invert$2(this,this);return this.check();}multiplyLeft(a){multiply$2(this,a,this);return this.check();}multiplyRight(a){multiply$2(this,this,a);return this.check();}rotate(radians){rotate$1(this,this,radians);return this.check();}scale(factor){if(Array.isArray(factor)){scale$3(this,this,factor);}else {scale$3(this,this,[factor,factor,factor]);}return this.check();}translate(vec){translate$1(this,this,vec);return this.check();}transform(vector,result){switch(vector.length){case 2:result=transformMat3$1(result||[-0,-0],vector,this);break;case 3:result=transformMat3(result||[-0,-0,-0],vector,this);break;case 4:result=vec4_transformMat3(result||[-0,-0,-0,-0],vector,this);break;default:throw new Error('Illegal vector');}checkVector(result,vector.length);return result;}transformVector(vector,result){deprecated('Matrix3.transformVector');return this.transform(vector,result);}transformVector2(vector,result){deprecated('Matrix3.transformVector');return this.transform(vector,result);}transformVector3(vector,result){deprecated('Matrix3.transformVector');return this.transform(vector,result);}}/**
  78435. * Set a mat4 to the identity matrix
  78436. *
  78437. * @param {mat4} out the receiving matrix
  78438. * @returns {mat4} out
  78439. */function identity$1(out){out[0]=1;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=1;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=1;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}/**
  78440. * Transpose the values of a mat4
  78441. *
  78442. * @param {mat4} out the receiving matrix
  78443. * @param {ReadonlyMat4} a the source matrix
  78444. * @returns {mat4} out
  78445. */function transpose(out,a){// If we are transposing ourselves we can skip a few steps but have to cache some values
  78446. if(out===a){var a01=a[1],a02=a[2],a03=a[3];var a12=a[6],a13=a[7];var a23=a[11];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a01;out[6]=a[9];out[7]=a[13];out[8]=a02;out[9]=a12;out[11]=a[14];out[12]=a03;out[13]=a13;out[14]=a23;}else {out[0]=a[0];out[1]=a[4];out[2]=a[8];out[3]=a[12];out[4]=a[1];out[5]=a[5];out[6]=a[9];out[7]=a[13];out[8]=a[2];out[9]=a[6];out[10]=a[10];out[11]=a[14];out[12]=a[3];out[13]=a[7];out[14]=a[11];out[15]=a[15];}return out;}/**
  78447. * Inverts a mat4
  78448. *
  78449. * @param {mat4} out the receiving matrix
  78450. * @param {ReadonlyMat4} a the source matrix
  78451. * @returns {mat4} out
  78452. */function invert$1(out,a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;// Calculate the determinant
  78453. var det=b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;if(!det){return null;}det=1.0/det;out[0]=(a11*b11-a12*b10+a13*b09)*det;out[1]=(a02*b10-a01*b11-a03*b09)*det;out[2]=(a31*b05-a32*b04+a33*b03)*det;out[3]=(a22*b04-a21*b05-a23*b03)*det;out[4]=(a12*b08-a10*b11-a13*b07)*det;out[5]=(a00*b11-a02*b08+a03*b07)*det;out[6]=(a32*b02-a30*b05-a33*b01)*det;out[7]=(a20*b05-a22*b02+a23*b01)*det;out[8]=(a10*b10-a11*b08+a13*b06)*det;out[9]=(a01*b08-a00*b10-a03*b06)*det;out[10]=(a30*b04-a31*b02+a33*b00)*det;out[11]=(a21*b02-a20*b04-a23*b00)*det;out[12]=(a11*b07-a10*b09-a12*b06)*det;out[13]=(a00*b09-a01*b07+a02*b06)*det;out[14]=(a31*b01-a30*b03-a32*b00)*det;out[15]=(a20*b03-a21*b01+a22*b00)*det;return out;}/**
  78454. * Calculates the determinant of a mat4
  78455. *
  78456. * @param {ReadonlyMat4} a the source matrix
  78457. * @returns {Number} determinant of a
  78458. */function determinant(a){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];var b00=a00*a11-a01*a10;var b01=a00*a12-a02*a10;var b02=a00*a13-a03*a10;var b03=a01*a12-a02*a11;var b04=a01*a13-a03*a11;var b05=a02*a13-a03*a12;var b06=a20*a31-a21*a30;var b07=a20*a32-a22*a30;var b08=a20*a33-a23*a30;var b09=a21*a32-a22*a31;var b10=a21*a33-a23*a31;var b11=a22*a33-a23*a32;// Calculate the determinant
  78459. return b00*b11-b01*b10+b02*b09+b03*b08-b04*b07+b05*b06;}/**
  78460. * Multiplies two mat4s
  78461. *
  78462. * @param {mat4} out the receiving matrix
  78463. * @param {ReadonlyMat4} a the first operand
  78464. * @param {ReadonlyMat4} b the second operand
  78465. * @returns {mat4} out
  78466. */function multiply$1(out,a,b){var a00=a[0],a01=a[1],a02=a[2],a03=a[3];var a10=a[4],a11=a[5],a12=a[6],a13=a[7];var a20=a[8],a21=a[9],a22=a[10],a23=a[11];var a30=a[12],a31=a[13],a32=a[14],a33=a[15];// Cache only the current line of the second matrix
  78467. var b0=b[0],b1=b[1],b2=b[2],b3=b[3];out[0]=b0*a00+b1*a10+b2*a20+b3*a30;out[1]=b0*a01+b1*a11+b2*a21+b3*a31;out[2]=b0*a02+b1*a12+b2*a22+b3*a32;out[3]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[4];b1=b[5];b2=b[6];b3=b[7];out[4]=b0*a00+b1*a10+b2*a20+b3*a30;out[5]=b0*a01+b1*a11+b2*a21+b3*a31;out[6]=b0*a02+b1*a12+b2*a22+b3*a32;out[7]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[8];b1=b[9];b2=b[10];b3=b[11];out[8]=b0*a00+b1*a10+b2*a20+b3*a30;out[9]=b0*a01+b1*a11+b2*a21+b3*a31;out[10]=b0*a02+b1*a12+b2*a22+b3*a32;out[11]=b0*a03+b1*a13+b2*a23+b3*a33;b0=b[12];b1=b[13];b2=b[14];b3=b[15];out[12]=b0*a00+b1*a10+b2*a20+b3*a30;out[13]=b0*a01+b1*a11+b2*a21+b3*a31;out[14]=b0*a02+b1*a12+b2*a22+b3*a32;out[15]=b0*a03+b1*a13+b2*a23+b3*a33;return out;}/**
  78468. * Translate a mat4 by the given vector
  78469. *
  78470. * @param {mat4} out the receiving matrix
  78471. * @param {ReadonlyMat4} a the matrix to translate
  78472. * @param {ReadonlyVec3} v vector to translate by
  78473. * @returns {mat4} out
  78474. */function translate(out,a,v){var x=v[0],y=v[1],z=v[2];var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;if(a===out){out[12]=a[0]*x+a[4]*y+a[8]*z+a[12];out[13]=a[1]*x+a[5]*y+a[9]*z+a[13];out[14]=a[2]*x+a[6]*y+a[10]*z+a[14];out[15]=a[3]*x+a[7]*y+a[11]*z+a[15];}else {a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];out[0]=a00;out[1]=a01;out[2]=a02;out[3]=a03;out[4]=a10;out[5]=a11;out[6]=a12;out[7]=a13;out[8]=a20;out[9]=a21;out[10]=a22;out[11]=a23;out[12]=a00*x+a10*y+a20*z+a[12];out[13]=a01*x+a11*y+a21*z+a[13];out[14]=a02*x+a12*y+a22*z+a[14];out[15]=a03*x+a13*y+a23*z+a[15];}return out;}/**
  78475. * Scales the mat4 by the dimensions in the given vec3 not using vectorization
  78476. *
  78477. * @param {mat4} out the receiving matrix
  78478. * @param {ReadonlyMat4} a the matrix to scale
  78479. * @param {ReadonlyVec3} v the vec3 to scale the matrix by
  78480. * @returns {mat4} out
  78481. **/function scale$2(out,a,v){var x=v[0],y=v[1],z=v[2];out[0]=a[0]*x;out[1]=a[1]*x;out[2]=a[2]*x;out[3]=a[3]*x;out[4]=a[4]*y;out[5]=a[5]*y;out[6]=a[6]*y;out[7]=a[7]*y;out[8]=a[8]*z;out[9]=a[9]*z;out[10]=a[10]*z;out[11]=a[11]*z;out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];return out;}/**
  78482. * Rotates a mat4 by the given angle around the given axis
  78483. *
  78484. * @param {mat4} out the receiving matrix
  78485. * @param {ReadonlyMat4} a the matrix to rotate
  78486. * @param {Number} rad the angle to rotate the matrix by
  78487. * @param {ReadonlyVec3} axis the axis to rotate around
  78488. * @returns {mat4} out
  78489. */function rotate(out,a,rad,axis){var x=axis[0],y=axis[1],z=axis[2];var len=Math.hypot(x,y,z);var s,c,t;var a00,a01,a02,a03;var a10,a11,a12,a13;var a20,a21,a22,a23;var b00,b01,b02;var b10,b11,b12;var b20,b21,b22;if(len<EPSILON){return null;}len=1/len;x*=len;y*=len;z*=len;s=Math.sin(rad);c=Math.cos(rad);t=1-c;a00=a[0];a01=a[1];a02=a[2];a03=a[3];a10=a[4];a11=a[5];a12=a[6];a13=a[7];a20=a[8];a21=a[9];a22=a[10];a23=a[11];// Construct the elements of the rotation matrix
  78490. b00=x*x*t+c;b01=y*x*t+z*s;b02=z*x*t-y*s;b10=x*y*t-z*s;b11=y*y*t+c;b12=z*y*t+x*s;b20=x*z*t+y*s;b21=y*z*t-x*s;b22=z*z*t+c;// Perform rotation-specific matrix multiplication
  78491. out[0]=a00*b00+a10*b01+a20*b02;out[1]=a01*b00+a11*b01+a21*b02;out[2]=a02*b00+a12*b01+a22*b02;out[3]=a03*b00+a13*b01+a23*b02;out[4]=a00*b10+a10*b11+a20*b12;out[5]=a01*b10+a11*b11+a21*b12;out[6]=a02*b10+a12*b11+a22*b12;out[7]=a03*b10+a13*b11+a23*b12;out[8]=a00*b20+a10*b21+a20*b22;out[9]=a01*b20+a11*b21+a21*b22;out[10]=a02*b20+a12*b21+a22*b22;out[11]=a03*b20+a13*b21+a23*b22;if(a!==out){// If the source and destination differ, copy the unchanged last row
  78492. out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}return out;}/**
  78493. * Rotates a matrix by the given angle around the X axis
  78494. *
  78495. * @param {mat4} out the receiving matrix
  78496. * @param {ReadonlyMat4} a the matrix to rotate
  78497. * @param {Number} rad the angle to rotate the matrix by
  78498. * @returns {mat4} out
  78499. */function rotateX$1(out,a,rad){var s=Math.sin(rad);var c=Math.cos(rad);var a10=a[4];var a11=a[5];var a12=a[6];var a13=a[7];var a20=a[8];var a21=a[9];var a22=a[10];var a23=a[11];if(a!==out){// If the source and destination differ, copy the unchanged rows
  78500. out[0]=a[0];out[1]=a[1];out[2]=a[2];out[3]=a[3];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}// Perform axis-specific matrix multiplication
  78501. out[4]=a10*c+a20*s;out[5]=a11*c+a21*s;out[6]=a12*c+a22*s;out[7]=a13*c+a23*s;out[8]=a20*c-a10*s;out[9]=a21*c-a11*s;out[10]=a22*c-a12*s;out[11]=a23*c-a13*s;return out;}/**
  78502. * Rotates a matrix by the given angle around the Y axis
  78503. *
  78504. * @param {mat4} out the receiving matrix
  78505. * @param {ReadonlyMat4} a the matrix to rotate
  78506. * @param {Number} rad the angle to rotate the matrix by
  78507. * @returns {mat4} out
  78508. */function rotateY$1(out,a,rad){var s=Math.sin(rad);var c=Math.cos(rad);var a00=a[0];var a01=a[1];var a02=a[2];var a03=a[3];var a20=a[8];var a21=a[9];var a22=a[10];var a23=a[11];if(a!==out){// If the source and destination differ, copy the unchanged rows
  78509. out[4]=a[4];out[5]=a[5];out[6]=a[6];out[7]=a[7];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}// Perform axis-specific matrix multiplication
  78510. out[0]=a00*c-a20*s;out[1]=a01*c-a21*s;out[2]=a02*c-a22*s;out[3]=a03*c-a23*s;out[8]=a00*s+a20*c;out[9]=a01*s+a21*c;out[10]=a02*s+a22*c;out[11]=a03*s+a23*c;return out;}/**
  78511. * Rotates a matrix by the given angle around the Z axis
  78512. *
  78513. * @param {mat4} out the receiving matrix
  78514. * @param {ReadonlyMat4} a the matrix to rotate
  78515. * @param {Number} rad the angle to rotate the matrix by
  78516. * @returns {mat4} out
  78517. */function rotateZ$1(out,a,rad){var s=Math.sin(rad);var c=Math.cos(rad);var a00=a[0];var a01=a[1];var a02=a[2];var a03=a[3];var a10=a[4];var a11=a[5];var a12=a[6];var a13=a[7];if(a!==out){// If the source and destination differ, copy the unchanged last row
  78518. out[8]=a[8];out[9]=a[9];out[10]=a[10];out[11]=a[11];out[12]=a[12];out[13]=a[13];out[14]=a[14];out[15]=a[15];}// Perform axis-specific matrix multiplication
  78519. out[0]=a00*c+a10*s;out[1]=a01*c+a11*s;out[2]=a02*c+a12*s;out[3]=a03*c+a13*s;out[4]=a10*c-a00*s;out[5]=a11*c-a01*s;out[6]=a12*c-a02*s;out[7]=a13*c-a03*s;return out;}/**
  78520. * Returns the scaling factor component of a transformation
  78521. * matrix. If a matrix is built with fromRotationTranslationScale
  78522. * with a normalized Quaternion paramter, the returned vector will be
  78523. * the same as the scaling vector
  78524. * originally supplied.
  78525. * @param {vec3} out Vector to receive scaling factor component
  78526. * @param {ReadonlyMat4} mat Matrix to be decomposed (input)
  78527. * @return {vec3} out
  78528. */function getScaling(out,mat){var m11=mat[0];var m12=mat[1];var m13=mat[2];var m21=mat[4];var m22=mat[5];var m23=mat[6];var m31=mat[8];var m32=mat[9];var m33=mat[10];out[0]=Math.hypot(m11,m12,m13);out[1]=Math.hypot(m21,m22,m23);out[2]=Math.hypot(m31,m32,m33);return out;}/**
  78529. * Calculates a 4x4 matrix from the given quaternion
  78530. *
  78531. * @param {mat4} out mat4 receiving operation result
  78532. * @param {ReadonlyQuat} q Quaternion to create matrix from
  78533. *
  78534. * @returns {mat4} out
  78535. */function fromQuat(out,q){var x=q[0],y=q[1],z=q[2],w=q[3];var x2=x+x;var y2=y+y;var z2=z+z;var xx=x*x2;var yx=y*x2;var yy=y*y2;var zx=z*x2;var zy=z*y2;var zz=z*z2;var wx=w*x2;var wy=w*y2;var wz=w*z2;out[0]=1-yy-zz;out[1]=yx+wz;out[2]=zx-wy;out[3]=0;out[4]=yx-wz;out[5]=1-xx-zz;out[6]=zy+wx;out[7]=0;out[8]=zx+wy;out[9]=zy-wx;out[10]=1-xx-yy;out[11]=0;out[12]=0;out[13]=0;out[14]=0;out[15]=1;return out;}/**
  78536. * Generates a frustum matrix with the given bounds
  78537. *
  78538. * @param {mat4} out mat4 frustum matrix will be written into
  78539. * @param {Number} left Left bound of the frustum
  78540. * @param {Number} right Right bound of the frustum
  78541. * @param {Number} bottom Bottom bound of the frustum
  78542. * @param {Number} top Top bound of the frustum
  78543. * @param {Number} near Near bound of the frustum
  78544. * @param {Number} far Far bound of the frustum
  78545. * @returns {mat4} out
  78546. */function frustum(out,left,right,bottom,top,near,far){var rl=1/(right-left);var tb=1/(top-bottom);var nf=1/(near-far);out[0]=near*2*rl;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=near*2*tb;out[6]=0;out[7]=0;out[8]=(right+left)*rl;out[9]=(top+bottom)*tb;out[10]=(far+near)*nf;out[11]=-1;out[12]=0;out[13]=0;out[14]=far*near*2*nf;out[15]=0;return out;}/**
  78547. * Generates a perspective projection matrix with the given bounds.
  78548. * Passing null/undefined/no value for far will generate infinite projection matrix.
  78549. *
  78550. * @param {mat4} out mat4 frustum matrix will be written into
  78551. * @param {number} fovy Vertical field of view in radians
  78552. * @param {number} aspect Aspect ratio. typically viewport width/height
  78553. * @param {number} near Near bound of the frustum
  78554. * @param {number} far Far bound of the frustum, can be null or Infinity
  78555. * @returns {mat4} out
  78556. */function perspective(out,fovy,aspect,near,far){var f=1.0/Math.tan(fovy/2),nf;out[0]=f/aspect;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=f;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[11]=-1;out[12]=0;out[13]=0;out[15]=0;if(far!=null&&far!==Infinity){nf=1/(near-far);out[10]=(far+near)*nf;out[14]=2*far*near*nf;}else {out[10]=-1;out[14]=-2*near;}return out;}/**
  78557. * Generates a orthogonal projection matrix with the given bounds
  78558. *
  78559. * @param {mat4} out mat4 frustum matrix will be written into
  78560. * @param {number} left Left bound of the frustum
  78561. * @param {number} right Right bound of the frustum
  78562. * @param {number} bottom Bottom bound of the frustum
  78563. * @param {number} top Top bound of the frustum
  78564. * @param {number} near Near bound of the frustum
  78565. * @param {number} far Far bound of the frustum
  78566. * @returns {mat4} out
  78567. */function ortho(out,left,right,bottom,top,near,far){var lr=1/(left-right);var bt=1/(bottom-top);var nf=1/(near-far);out[0]=-2*lr;out[1]=0;out[2]=0;out[3]=0;out[4]=0;out[5]=-2*bt;out[6]=0;out[7]=0;out[8]=0;out[9]=0;out[10]=2*nf;out[11]=0;out[12]=(left+right)*lr;out[13]=(top+bottom)*bt;out[14]=(far+near)*nf;out[15]=1;return out;}/**
  78568. * Generates a look-at matrix with the given eye position, focal point, and up axis.
  78569. * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.
  78570. *
  78571. * @param {mat4} out mat4 frustum matrix will be written into
  78572. * @param {ReadonlyVec3} eye Position of the viewer
  78573. * @param {ReadonlyVec3} center Point the viewer is looking at
  78574. * @param {ReadonlyVec3} up vec3 pointing up
  78575. * @returns {mat4} out
  78576. */function lookAt(out,eye,center,up){var x0,x1,x2,y0,y1,y2,z0,z1,z2,len;var eyex=eye[0];var eyey=eye[1];var eyez=eye[2];var upx=up[0];var upy=up[1];var upz=up[2];var centerx=center[0];var centery=center[1];var centerz=center[2];if(Math.abs(eyex-centerx)<EPSILON&&Math.abs(eyey-centery)<EPSILON&&Math.abs(eyez-centerz)<EPSILON){return identity$1(out);}z0=eyex-centerx;z1=eyey-centery;z2=eyez-centerz;len=1/Math.hypot(z0,z1,z2);z0*=len;z1*=len;z2*=len;x0=upy*z2-upz*z1;x1=upz*z0-upx*z2;x2=upx*z1-upy*z0;len=Math.hypot(x0,x1,x2);if(!len){x0=0;x1=0;x2=0;}else {len=1/len;x0*=len;x1*=len;x2*=len;}y0=z1*x2-z2*x1;y1=z2*x0-z0*x2;y2=z0*x1-z1*x0;len=Math.hypot(y0,y1,y2);if(!len){y0=0;y1=0;y2=0;}else {len=1/len;y0*=len;y1*=len;y2*=len;}out[0]=x0;out[1]=y0;out[2]=z0;out[3]=0;out[4]=x1;out[5]=y1;out[6]=z1;out[7]=0;out[8]=x2;out[9]=y2;out[10]=z2;out[11]=0;out[12]=-(x0*eyex+x1*eyey+x2*eyez);out[13]=-(y0*eyex+y1*eyey+y2*eyez);out[14]=-(z0*eyex+z1*eyey+z2*eyez);out[15]=1;return out;}/**
  78577. * 4 Dimensional Vector
  78578. * @module vec4
  78579. */ /**
  78580. * Creates a new, empty vec4
  78581. *
  78582. * @returns {vec4} a new 4D vector
  78583. */function create$1(){var out=new ARRAY_TYPE(4);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0;out[3]=0;}return out;}/**
  78584. * Adds two vec4's
  78585. *
  78586. * @param {vec4} out the receiving vector
  78587. * @param {ReadonlyVec4} a the first operand
  78588. * @param {ReadonlyVec4} b the second operand
  78589. * @returns {vec4} out
  78590. */function add$1(out,a,b){out[0]=a[0]+b[0];out[1]=a[1]+b[1];out[2]=a[2]+b[2];out[3]=a[3]+b[3];return out;}/**
  78591. * Scales a vec4 by a scalar number
  78592. *
  78593. * @param {vec4} out the receiving vector
  78594. * @param {ReadonlyVec4} a the vector to scale
  78595. * @param {Number} b amount to scale the vector by
  78596. * @returns {vec4} out
  78597. */function scale$1(out,a,b){out[0]=a[0]*b;out[1]=a[1]*b;out[2]=a[2]*b;out[3]=a[3]*b;return out;}/**
  78598. * Calculates the length of a vec4
  78599. *
  78600. * @param {ReadonlyVec4} a vector to calculate length of
  78601. * @returns {Number} length of a
  78602. */function length$1(a){var x=a[0];var y=a[1];var z=a[2];var w=a[3];return Math.hypot(x,y,z,w);}/**
  78603. * Calculates the squared length of a vec4
  78604. *
  78605. * @param {ReadonlyVec4} a vector to calculate squared length of
  78606. * @returns {Number} squared length of a
  78607. */function squaredLength$1(a){var x=a[0];var y=a[1];var z=a[2];var w=a[3];return x*x+y*y+z*z+w*w;}/**
  78608. * Normalize a vec4
  78609. *
  78610. * @param {vec4} out the receiving vector
  78611. * @param {ReadonlyVec4} a vector to normalize
  78612. * @returns {vec4} out
  78613. */function normalize$1(out,a){var x=a[0];var y=a[1];var z=a[2];var w=a[3];var len=x*x+y*y+z*z+w*w;if(len>0){len=1/Math.sqrt(len);}out[0]=x*len;out[1]=y*len;out[2]=z*len;out[3]=w*len;return out;}/**
  78614. * Calculates the dot product of two vec4's
  78615. *
  78616. * @param {ReadonlyVec4} a the first operand
  78617. * @param {ReadonlyVec4} b the second operand
  78618. * @returns {Number} dot product of a and b
  78619. */function dot$1(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3];}/**
  78620. * Performs a linear interpolation between two vec4's
  78621. *
  78622. * @param {vec4} out the receiving vector
  78623. * @param {ReadonlyVec4} a the first operand
  78624. * @param {ReadonlyVec4} b the second operand
  78625. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  78626. * @returns {vec4} out
  78627. */function lerp$1$1(out,a,b,t){var ax=a[0];var ay=a[1];var az=a[2];var aw=a[3];out[0]=ax+t*(b[0]-ax);out[1]=ay+t*(b[1]-ay);out[2]=az+t*(b[2]-az);out[3]=aw+t*(b[3]-aw);return out;}/**
  78628. * Transforms the vec4 with a mat4.
  78629. *
  78630. * @param {vec4} out the receiving vector
  78631. * @param {ReadonlyVec4} a the vector to transform
  78632. * @param {ReadonlyMat4} m matrix to transform with
  78633. * @returns {vec4} out
  78634. */function transformMat4(out,a,m){var x=a[0],y=a[1],z=a[2],w=a[3];out[0]=m[0]*x+m[4]*y+m[8]*z+m[12]*w;out[1]=m[1]*x+m[5]*y+m[9]*z+m[13]*w;out[2]=m[2]*x+m[6]*y+m[10]*z+m[14]*w;out[3]=m[3]*x+m[7]*y+m[11]*z+m[15]*w;return out;}/**
  78635. * Transforms the vec4 with a quat
  78636. *
  78637. * @param {vec4} out the receiving vector
  78638. * @param {ReadonlyVec4} a the vector to transform
  78639. * @param {ReadonlyQuat} q quaternion to transform with
  78640. * @returns {vec4} out
  78641. */function transformQuat(out,a,q){var x=a[0],y=a[1],z=a[2];var qx=q[0],qy=q[1],qz=q[2],qw=q[3];// calculate quat * vec
  78642. var ix=qw*x+qy*z-qz*y;var iy=qw*y+qz*x-qx*z;var iz=qw*z+qx*y-qy*x;var iw=-qx*x-qy*y-qz*z;// calculate result * inverse quat
  78643. out[0]=ix*qw+iw*-qx+iy*-qz-iz*-qy;out[1]=iy*qw+iw*-qy+iz*-qx-ix*-qz;out[2]=iz*qw+iw*-qz+ix*-qy-iy*-qx;out[3]=a[3];return out;}/**
  78644. * Perform some operation over an array of vec4s.
  78645. *
  78646. * @param {Array} a the array of vectors to iterate over
  78647. * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed
  78648. * @param {Number} offset Number of elements to skip at the beginning of the array
  78649. * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array
  78650. * @param {Function} fn Function to call for each vector in the array
  78651. * @param {Object} [arg] additional argument to pass to fn
  78652. * @returns {Array} a
  78653. * @function
  78654. */(function(){var vec=create$1();return function(a,stride,offset,count,fn,arg){var i,l;if(!stride){stride=4;}if(!offset){offset=0;}if(count){l=Math.min(count*stride+offset,a.length);}else {l=a.length;}for(i=offset;i<l;i+=stride){vec[0]=a[i];vec[1]=a[i+1];vec[2]=a[i+2];vec[3]=a[i+3];fn(vec,vec,arg);a[i]=vec[0];a[i+1]=vec[1];a[i+2]=vec[2];a[i+3]=vec[3];}return a;};})();var IDENTITY=Object.freeze([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);var ZERO=Object.freeze([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);var INDICES=Object.freeze({COL0ROW0:0,COL0ROW1:1,COL0ROW2:2,COL0ROW3:3,COL1ROW0:4,COL1ROW1:5,COL1ROW2:6,COL1ROW3:7,COL2ROW0:8,COL2ROW1:9,COL2ROW2:10,COL2ROW3:11,COL3ROW0:12,COL3ROW1:13,COL3ROW2:14,COL3ROW3:15});var constants={};class Matrix4$1 extends Matrix{static get IDENTITY(){constants.IDENTITY=constants.IDENTITY||Object.freeze(new Matrix4$1(IDENTITY));return constants.IDENTITY;}static get ZERO(){constants.ZERO=constants.ZERO||Object.freeze(new Matrix4$1(ZERO));return constants.ZERO;}get INDICES(){return INDICES;}get ELEMENTS(){return 16;}get RANK(){return 4;}constructor(array){super(-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0);if(arguments.length===1&&Array.isArray(array)){this.copy(array);}else {this.identity();}}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];this[3]=array[3];this[4]=array[4];this[5]=array[5];this[6]=array[6];this[7]=array[7];this[8]=array[8];this[9]=array[9];this[10]=array[10];this[11]=array[11];this[12]=array[12];this[13]=array[13];this[14]=array[14];this[15]=array[15];return this.check();}set(m00,m10,m20,m30,m01,m11,m21,m31,m02,m12,m22,m32,m03,m13,m23,m33){this[0]=m00;this[1]=m10;this[2]=m20;this[3]=m30;this[4]=m01;this[5]=m11;this[6]=m21;this[7]=m31;this[8]=m02;this[9]=m12;this[10]=m22;this[11]=m32;this[12]=m03;this[13]=m13;this[14]=m23;this[15]=m33;return this.check();}setRowMajor(m00,m01,m02,m03,m10,m11,m12,m13,m20,m21,m22,m23,m30,m31,m32,m33){this[0]=m00;this[1]=m10;this[2]=m20;this[3]=m30;this[4]=m01;this[5]=m11;this[6]=m21;this[7]=m31;this[8]=m02;this[9]=m12;this[10]=m22;this[11]=m32;this[12]=m03;this[13]=m13;this[14]=m23;this[15]=m33;return this.check();}toRowMajor(result){result[0]=this[0];result[1]=this[4];result[2]=this[8];result[3]=this[12];result[4]=this[1];result[5]=this[5];result[6]=this[9];result[7]=this[13];result[8]=this[2];result[9]=this[6];result[10]=this[10];result[11]=this[14];result[12]=this[3];result[13]=this[7];result[14]=this[11];result[15]=this[15];return result;}identity(){return this.copy(IDENTITY);}fromQuaternion(q){fromQuat(this,q);return this.check();}frustum(_ref7){var{left,right,bottom,top,near,far}=_ref7;if(far===Infinity){Matrix4$1._computeInfinitePerspectiveOffCenter(this,left,right,bottom,top,near);}else {frustum(this,left,right,bottom,top,near,far);}return this.check();}static _computeInfinitePerspectiveOffCenter(result,left,right,bottom,top,near){var column0Row0=2.0*near/(right-left);var column1Row1=2.0*near/(top-bottom);var column2Row0=(right+left)/(right-left);var column2Row1=(top+bottom)/(top-bottom);var column2Row2=-1.0;var column2Row3=-1.0;var column3Row2=-2.0*near;result[0]=column0Row0;result[1]=0.0;result[2]=0.0;result[3]=0.0;result[4]=0.0;result[5]=column1Row1;result[6]=0.0;result[7]=0.0;result[8]=column2Row0;result[9]=column2Row1;result[10]=column2Row2;result[11]=column2Row3;result[12]=0.0;result[13]=0.0;result[14]=column3Row2;result[15]=0.0;return result;}lookAt(eye,center,up){if(arguments.length===1){({eye,center,up}=eye);}center=center||[0,0,0];up=up||[0,1,0];lookAt(this,eye,center,up);return this.check();}ortho(_ref8){var{left,right,bottom,top,near=0.1,far=500}=_ref8;ortho(this,left,right,bottom,top,near,far);return this.check();}orthographic(_ref9){var{fovy=45*Math.PI/180,aspect=1,focalDistance=1,near=0.1,far=500}=_ref9;if(fovy>Math.PI*2){throw Error('radians');}var halfY=fovy/2;var top=focalDistance*Math.tan(halfY);var right=top*aspect;return new Matrix4$1().ortho({left:-right,right,bottom:-top,top,near,far});}perspective(){var{fovy=undefined,fov=45*Math.PI/180,aspect=1,near=0.1,far=500}=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};fovy=fovy||fov;if(fovy>Math.PI*2){throw Error('radians');}perspective(this,fovy,aspect,near,far);return this.check();}determinant(){return determinant(this);}getScale(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0];result[0]=Math.sqrt(this[0]*this[0]+this[1]*this[1]+this[2]*this[2]);result[1]=Math.sqrt(this[4]*this[4]+this[5]*this[5]+this[6]*this[6]);result[2]=Math.sqrt(this[8]*this[8]+this[9]*this[9]+this[10]*this[10]);return result;}getTranslation(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0];result[0]=this[12];result[1]=this[13];result[2]=this[14];return result;}getRotation(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0,-0];var scaleResult=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var scale=this.getScale(scaleResult||[-0,-0,-0]);var inverseScale0=1/scale[0];var inverseScale1=1/scale[1];var inverseScale2=1/scale[2];result[0]=this[0]*inverseScale0;result[1]=this[1]*inverseScale1;result[2]=this[2]*inverseScale2;result[3]=0;result[4]=this[4]*inverseScale0;result[5]=this[5]*inverseScale1;result[6]=this[6]*inverseScale2;result[7]=0;result[8]=this[8]*inverseScale0;result[9]=this[9]*inverseScale1;result[10]=this[10]*inverseScale2;result[11]=0;result[12]=0;result[13]=0;result[14]=0;result[15]=1;return result;}getRotationMatrix3(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[-0,-0,-0,-0,-0,-0,-0,-0,-0];var scaleResult=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var scale=this.getScale(scaleResult||[-0,-0,-0]);var inverseScale0=1/scale[0];var inverseScale1=1/scale[1];var inverseScale2=1/scale[2];result[0]=this[0]*inverseScale0;result[1]=this[1]*inverseScale1;result[2]=this[2]*inverseScale2;result[3]=this[4]*inverseScale0;result[4]=this[5]*inverseScale1;result[5]=this[6]*inverseScale2;result[6]=this[8]*inverseScale0;result[7]=this[9]*inverseScale1;result[8]=this[10]*inverseScale2;return result;}transpose(){transpose(this,this);return this.check();}invert(){invert$1(this,this);return this.check();}multiplyLeft(a){multiply$1(this,a,this);return this.check();}multiplyRight(a){multiply$1(this,this,a);return this.check();}rotateX(radians){rotateX$1(this,this,radians);return this.check();}rotateY(radians){rotateY$1(this,this,radians);return this.check();}rotateZ(radians){rotateZ$1(this,this,radians);return this.check();}rotateXYZ(_ref10){var[rx,ry,rz]=_ref10;return this.rotateX(rx).rotateY(ry).rotateZ(rz);}rotateAxis(radians,axis){rotate(this,this,radians,axis);return this.check();}scale(factor){if(Array.isArray(factor)){scale$2(this,this,factor);}else {scale$2(this,this,[factor,factor,factor]);}return this.check();}translate(vec){translate(this,this,vec);return this.check();}transform(vector,result){if(vector.length===4){result=transformMat4(result||[-0,-0,-0,-0],vector,this);checkVector(result,4);return result;}return this.transformAsPoint(vector,result);}transformAsPoint(vector,result){var{length}=vector;switch(length){case 2:result=transformMat4$2(result||[-0,-0],vector,this);break;case 3:result=transformMat4$1(result||[-0,-0,-0],vector,this);break;default:throw new Error('Illegal vector');}checkVector(result,vector.length);return result;}transformAsVector(vector,result){switch(vector.length){case 2:result=vec2_transformMat4AsVector(result||[-0,-0],vector,this);break;case 3:result=vec3_transformMat4AsVector(result||[-0,-0,-0],vector,this);break;default:throw new Error('Illegal vector');}checkVector(result,vector.length);return result;}makeRotationX(radians){return this.identity().rotateX(radians);}makeTranslation(x,y,z){return this.identity().translate([x,y,z]);}transformPoint(vector,result){deprecated('Matrix4.transformPoint','3.0');return this.transformAsPoint(vector,result);}transformVector(vector,result){deprecated('Matrix4.transformVector','3.0');return this.transformAsPoint(vector,result);}transformDirection(vector,result){deprecated('Matrix4.transformDirection','3.0');return this.transformAsVector(vector,result);}}/**
  78655. * Quaternion
  78656. * @module quat
  78657. */ /**
  78658. * Creates a new identity quat
  78659. *
  78660. * @returns {quat} a new quaternion
  78661. */function create(){var out=new ARRAY_TYPE(4);if(ARRAY_TYPE!=Float32Array){out[0]=0;out[1]=0;out[2]=0;}out[3]=1;return out;}/**
  78662. * Set a quat to the identity quaternion
  78663. *
  78664. * @param {quat} out the receiving quaternion
  78665. * @returns {quat} out
  78666. */function identity(out){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}/**
  78667. * Sets a quat from the given angle and rotation axis,
  78668. * then returns it.
  78669. *
  78670. * @param {quat} out the receiving quaternion
  78671. * @param {ReadonlyVec3} axis the axis around which to rotate
  78672. * @param {Number} rad the angle in radians
  78673. * @returns {quat} out
  78674. **/function setAxisAngle(out,axis,rad){rad=rad*0.5;var s=Math.sin(rad);out[0]=s*axis[0];out[1]=s*axis[1];out[2]=s*axis[2];out[3]=Math.cos(rad);return out;}/**
  78675. * Multiplies two quat's
  78676. *
  78677. * @param {quat} out the receiving quaternion
  78678. * @param {ReadonlyQuat} a the first operand
  78679. * @param {ReadonlyQuat} b the second operand
  78680. * @returns {quat} out
  78681. */function multiply(out,a,b){var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];out[0]=ax*bw+aw*bx+ay*bz-az*by;out[1]=ay*bw+aw*by+az*bx-ax*bz;out[2]=az*bw+aw*bz+ax*by-ay*bx;out[3]=aw*bw-ax*bx-ay*by-az*bz;return out;}/**
  78682. * Rotates a quaternion by the given angle about the X axis
  78683. *
  78684. * @param {quat} out quat receiving operation result
  78685. * @param {ReadonlyQuat} a quat to rotate
  78686. * @param {number} rad angle (in radians) to rotate
  78687. * @returns {quat} out
  78688. */function rotateX(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+aw*bx;out[1]=ay*bw+az*bx;out[2]=az*bw-ay*bx;out[3]=aw*bw-ax*bx;return out;}/**
  78689. * Rotates a quaternion by the given angle about the Y axis
  78690. *
  78691. * @param {quat} out quat receiving operation result
  78692. * @param {ReadonlyQuat} a quat to rotate
  78693. * @param {number} rad angle (in radians) to rotate
  78694. * @returns {quat} out
  78695. */function rotateY(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var by=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw-az*by;out[1]=ay*bw+aw*by;out[2]=az*bw+ax*by;out[3]=aw*bw-ay*by;return out;}/**
  78696. * Rotates a quaternion by the given angle about the Z axis
  78697. *
  78698. * @param {quat} out quat receiving operation result
  78699. * @param {ReadonlyQuat} a quat to rotate
  78700. * @param {number} rad angle (in radians) to rotate
  78701. * @returns {quat} out
  78702. */function rotateZ(out,a,rad){rad*=0.5;var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bz=Math.sin(rad),bw=Math.cos(rad);out[0]=ax*bw+ay*bz;out[1]=ay*bw-ax*bz;out[2]=az*bw+aw*bz;out[3]=aw*bw-az*bz;return out;}/**
  78703. * Calculates the W component of a quat from the X, Y, and Z components.
  78704. * Assumes that quaternion is 1 unit in length.
  78705. * Any existing W component will be ignored.
  78706. *
  78707. * @param {quat} out the receiving quaternion
  78708. * @param {ReadonlyQuat} a quat to calculate W component of
  78709. * @returns {quat} out
  78710. */function calculateW(out,a){var x=a[0],y=a[1],z=a[2];out[0]=x;out[1]=y;out[2]=z;out[3]=Math.sqrt(Math.abs(1.0-x*x-y*y-z*z));return out;}/**
  78711. * Performs a spherical linear interpolation between two quat
  78712. *
  78713. * @param {quat} out the receiving quaternion
  78714. * @param {ReadonlyQuat} a the first operand
  78715. * @param {ReadonlyQuat} b the second operand
  78716. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  78717. * @returns {quat} out
  78718. */function slerp(out,a,b,t){// benchmarks:
  78719. // http://jsperf.com/quaternion-slerp-implementations
  78720. var ax=a[0],ay=a[1],az=a[2],aw=a[3];var bx=b[0],by=b[1],bz=b[2],bw=b[3];var omega,cosom,sinom,scale0,scale1;// calc cosine
  78721. cosom=ax*bx+ay*by+az*bz+aw*bw;// adjust signs (if necessary)
  78722. if(cosom<0.0){cosom=-cosom;bx=-bx;by=-by;bz=-bz;bw=-bw;}// calculate coefficients
  78723. if(1.0-cosom>EPSILON){// standard case (slerp)
  78724. omega=Math.acos(cosom);sinom=Math.sin(omega);scale0=Math.sin((1.0-t)*omega)/sinom;scale1=Math.sin(t*omega)/sinom;}else {// "from" and "to" quaternions are very close
  78725. // ... so we can do a linear interpolation
  78726. scale0=1.0-t;scale1=t;}// calculate final values
  78727. out[0]=scale0*ax+scale1*bx;out[1]=scale0*ay+scale1*by;out[2]=scale0*az+scale1*bz;out[3]=scale0*aw+scale1*bw;return out;}/**
  78728. * Calculates the inverse of a quat
  78729. *
  78730. * @param {quat} out the receiving quaternion
  78731. * @param {ReadonlyQuat} a quat to calculate inverse of
  78732. * @returns {quat} out
  78733. */function invert(out,a){var a0=a[0],a1=a[1],a2=a[2],a3=a[3];var dot=a0*a0+a1*a1+a2*a2+a3*a3;var invDot=dot?1.0/dot:0;// TODO: Would be faster to return [0,0,0,0] immediately if dot == 0
  78734. out[0]=-a0*invDot;out[1]=-a1*invDot;out[2]=-a2*invDot;out[3]=a3*invDot;return out;}/**
  78735. * Calculates the conjugate of a quat
  78736. * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
  78737. *
  78738. * @param {quat} out the receiving quaternion
  78739. * @param {ReadonlyQuat} a quat to calculate conjugate of
  78740. * @returns {quat} out
  78741. */function conjugate(out,a){out[0]=-a[0];out[1]=-a[1];out[2]=-a[2];out[3]=a[3];return out;}/**
  78742. * Creates a quaternion from the given 3x3 rotation matrix.
  78743. *
  78744. * NOTE: The resultant quaternion is not normalized, so you should be sure
  78745. * to renormalize the quaternion yourself where necessary.
  78746. *
  78747. * @param {quat} out the receiving quaternion
  78748. * @param {ReadonlyMat3} m rotation matrix
  78749. * @returns {quat} out
  78750. * @function
  78751. */function fromMat3(out,m){// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
  78752. // article "Quaternion Calculus and Fast Animation".
  78753. var fTrace=m[0]+m[4]+m[8];var fRoot;if(fTrace>0.0){// |w| > 1/2, may as well choose w > 1/2
  78754. fRoot=Math.sqrt(fTrace+1.0);// 2w
  78755. out[3]=0.5*fRoot;fRoot=0.5/fRoot;// 1/(4w)
  78756. out[0]=(m[5]-m[7])*fRoot;out[1]=(m[6]-m[2])*fRoot;out[2]=(m[1]-m[3])*fRoot;}else {// |w| <= 1/2
  78757. var i=0;if(m[4]>m[0])i=1;if(m[8]>m[i*3+i])i=2;var j=(i+1)%3;var k=(i+2)%3;fRoot=Math.sqrt(m[i*3+i]-m[j*3+j]-m[k*3+k]+1.0);out[i]=0.5*fRoot;fRoot=0.5/fRoot;out[3]=(m[j*3+k]-m[k*3+j])*fRoot;out[j]=(m[j*3+i]+m[i*3+j])*fRoot;out[k]=(m[k*3+i]+m[i*3+k])*fRoot;}return out;}/**
  78758. * Adds two quat's
  78759. *
  78760. * @param {quat} out the receiving quaternion
  78761. * @param {ReadonlyQuat} a the first operand
  78762. * @param {ReadonlyQuat} b the second operand
  78763. * @returns {quat} out
  78764. * @function
  78765. */var add=add$1;/**
  78766. * Scales a quat by a scalar number
  78767. *
  78768. * @param {quat} out the receiving vector
  78769. * @param {ReadonlyQuat} a the vector to scale
  78770. * @param {Number} b amount to scale the vector by
  78771. * @returns {quat} out
  78772. * @function
  78773. */var scale=scale$1;/**
  78774. * Calculates the dot product of two quat's
  78775. *
  78776. * @param {ReadonlyQuat} a the first operand
  78777. * @param {ReadonlyQuat} b the second operand
  78778. * @returns {Number} dot product of a and b
  78779. * @function
  78780. */var dot=dot$1;/**
  78781. * Performs a linear interpolation between two quat's
  78782. *
  78783. * @param {quat} out the receiving quaternion
  78784. * @param {ReadonlyQuat} a the first operand
  78785. * @param {ReadonlyQuat} b the second operand
  78786. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  78787. * @returns {quat} out
  78788. * @function
  78789. */var lerp$2=lerp$1$1;/**
  78790. * Calculates the length of a quat
  78791. *
  78792. * @param {ReadonlyQuat} a vector to calculate length of
  78793. * @returns {Number} length of a
  78794. */var length=length$1;/**
  78795. * Calculates the squared length of a quat
  78796. *
  78797. * @param {ReadonlyQuat} a vector to calculate squared length of
  78798. * @returns {Number} squared length of a
  78799. * @function
  78800. */var squaredLength=squaredLength$1;/**
  78801. * Normalize a quat
  78802. *
  78803. * @param {quat} out the receiving quaternion
  78804. * @param {ReadonlyQuat} a quaternion to normalize
  78805. * @returns {quat} out
  78806. * @function
  78807. */var normalize=normalize$1;/**
  78808. * Sets a quaternion to represent the shortest rotation from one
  78809. * vector to another.
  78810. *
  78811. * Both vectors are assumed to be unit length.
  78812. *
  78813. * @param {quat} out the receiving quaternion.
  78814. * @param {ReadonlyVec3} a the initial vector
  78815. * @param {ReadonlyVec3} b the destination vector
  78816. * @returns {quat} out
  78817. */var rotationTo=function(){var tmpvec3=create$3();var xUnitVec3=fromValues(1,0,0);var yUnitVec3=fromValues(0,1,0);return function(out,a,b){var dot=dot$2(a,b);if(dot<-0.999999){cross(tmpvec3,xUnitVec3,a);if(len(tmpvec3)<0.000001)cross(tmpvec3,yUnitVec3,a);normalize$2(tmpvec3,tmpvec3);setAxisAngle(out,tmpvec3,Math.PI);return out;}else if(dot>0.999999){out[0]=0;out[1]=0;out[2]=0;out[3]=1;return out;}else {cross(tmpvec3,a,b);out[0]=tmpvec3[0];out[1]=tmpvec3[1];out[2]=tmpvec3[2];out[3]=1+dot;return normalize(out,out);}};}();/**
  78818. * Performs a spherical linear interpolation with two control points
  78819. *
  78820. * @param {quat} out the receiving quaternion
  78821. * @param {ReadonlyQuat} a the first operand
  78822. * @param {ReadonlyQuat} b the second operand
  78823. * @param {ReadonlyQuat} c the third operand
  78824. * @param {ReadonlyQuat} d the fourth operand
  78825. * @param {Number} t interpolation amount, in the range [0-1], between the two inputs
  78826. * @returns {quat} out
  78827. */(function(){var temp1=create();var temp2=create();return function(out,a,b,c,d,t){slerp(temp1,a,d,t);slerp(temp2,b,c,t);slerp(out,temp1,temp2,2*t*(1-t));return out;};})();/**
  78828. * Sets the specified quaternion with values corresponding to the given
  78829. * axes. Each axis is a vec3 and is expected to be unit length and
  78830. * perpendicular to all other specified axes.
  78831. *
  78832. * @param {ReadonlyVec3} view the vector representing the viewing direction
  78833. * @param {ReadonlyVec3} right the vector representing the local "right" direction
  78834. * @param {ReadonlyVec3} up the vector representing the local "up" direction
  78835. * @returns {quat} out
  78836. */(function(){var matr=create$2();return function(out,view,right,up){matr[0]=right[0];matr[3]=right[1];matr[6]=right[2];matr[1]=up[0];matr[4]=up[1];matr[7]=up[2];matr[2]=-view[0];matr[5]=-view[1];matr[8]=-view[2];return normalize(out,fromMat3(out,matr));};})();var IDENTITY_QUATERNION=[0,0,0,1];class Quaternion$1 extends MathArray{constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var w=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;super(-0,-0,-0,-0);if(Array.isArray(x)&&arguments.length===1){this.copy(x);}else {this.set(x,y,z,w);}}copy(array){this[0]=array[0];this[1]=array[1];this[2]=array[2];this[3]=array[3];return this.check();}set(x,y,z,w){this[0]=x;this[1]=y;this[2]=z;this[3]=w;return this.check();}fromMatrix3(m){fromMat3(this,m);return this.check();}identity(){identity(this);return this.check();}fromAxisRotation(axis,rad){setAxisAngle(this,axis,rad);return this.check();}setAxisAngle(axis,rad){return this.fromAxisRotation(axis,rad);}get ELEMENTS(){return 4;}get x(){return this[0];}set x(value){this[0]=checkNumber(value);}get y(){return this[1];}set y(value){this[1]=checkNumber(value);}get z(){return this[2];}set z(value){this[2]=checkNumber(value);}get w(){return this[3];}set w(value){this[3]=checkNumber(value);}len(){return length(this);}lengthSquared(){return squaredLength(this);}dot(a,b){if(b!==undefined){throw new Error('Quaternion.dot only takes one argument');}return dot(this,a);}rotationTo(vectorA,vectorB){rotationTo(this,vectorA,vectorB);return this.check();}add(a,b){if(b!==undefined){throw new Error('Quaternion.add only takes one argument');}add(this,this,a);return this.check();}calculateW(){calculateW(this,this);return this.check();}conjugate(){conjugate(this,this);return this.check();}invert(){invert(this,this);return this.check();}lerp(a,b,t){lerp$2(this,a,b,t);return this.check();}multiplyRight(a,b){assert$4(!b);multiply(this,this,a);return this.check();}multiplyLeft(a,b){assert$4(!b);multiply(this,a,this);return this.check();}normalize(){var length=this.len();var l=length>0?1/length:0;this[0]=this[0]*l;this[1]=this[1]*l;this[2]=this[2]*l;this[3]=this[3]*l;if(length===0){this[3]=1;}return this.check();}rotateX(rad){rotateX(this,this,rad);return this.check();}rotateY(rad){rotateY(this,this,rad);return this.check();}rotateZ(rad){rotateZ(this,this,rad);return this.check();}scale(b){scale(this,this,b);return this.check();}slerp(start,target,ratio){switch(arguments.length){case 1:({start=IDENTITY_QUATERNION,target,ratio}=arguments[0]);break;case 2:[target,ratio]=arguments;start=this;break;}slerp(this,start,target,ratio);return this.check();}transformVector4(vector){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:vector;transformQuat(result,vector,this);return checkVector(result,4);}lengthSq(){return this.lengthSquared();}setFromAxisAngle(axis,rad){return this.setAxisAngle(axis,rad);}premultiply(a,b){return this.multiplyLeft(a,b);}multiply(a,b){return this.multiplyRight(a,b);}}var _MathUtils={EPSILON1:1e-1,EPSILON2:1e-2,EPSILON3:1e-3,EPSILON4:1e-4,EPSILON5:1e-5,EPSILON6:1e-6,EPSILON7:1e-7,EPSILON8:1e-8,EPSILON9:1e-9,EPSILON10:1e-10,EPSILON11:1e-11,EPSILON12:1e-12,EPSILON13:1e-13,EPSILON14:1e-14,EPSILON15:1e-15,EPSILON16:1e-16,EPSILON17:1e-17,EPSILON18:1e-18,EPSILON19:1e-19,EPSILON20:1e-20,PI_OVER_TWO:Math.PI/2,PI_OVER_FOUR:Math.PI/4,PI_OVER_SIX:Math.PI/6,TWO_PI:Math.PI*2};var WGS84_RADIUS_X$1=6378137.0;var WGS84_RADIUS_Y$1=6378137.0;var WGS84_RADIUS_Z$1=6356752.3142451793;var noop$2=x=>x;var scratchVector$6=new Vector3$1();function fromCartographic(cartographic,result){var map=arguments.length>2&&arguments[2]!==undefined?arguments[2]:noop$2;if(isArray(cartographic)){result[0]=map(cartographic[0]);result[1]=map(cartographic[1]);result[2]=cartographic[2];}else if('longitude'in cartographic){result[0]=map(cartographic.longitude);result[1]=map(cartographic.latitude);result[2]=cartographic.height;}else {result[0]=map(cartographic.x);result[1]=map(cartographic.y);result[2]=cartographic.z;}return result;}function fromCartographicToRadians(cartographic){var vector=arguments.length>1&&arguments[1]!==undefined?arguments[1]:scratchVector$6;return fromCartographic(cartographic,vector,config$2._cartographicRadians?noop$2:toRadians);}function toCartographic(vector,cartographic){var map=arguments.length>2&&arguments[2]!==undefined?arguments[2]:noop$2;if(isArray(cartographic)){cartographic[0]=map(vector[0]);cartographic[1]=map(vector[1]);cartographic[2]=vector[2];}else if('longitude'in cartographic){cartographic.longitude=map(vector[0]);cartographic.latitude=map(vector[1]);cartographic.height=vector[2];}else {cartographic.x=map(vector[0]);cartographic.y=map(vector[1]);cartographic.z=vector[2];}return cartographic;}function toCartographicFromRadians(vector,cartographic){return toCartographic(vector,cartographic,config$2._cartographicRadians?noop$2:toDegrees);}var scratchVector$5=new Vector3$1();var scaleToGeodeticSurfaceIntersection=new Vector3$1();var scaleToGeodeticSurfaceGradient=new Vector3$1();function scaleToGeodeticSurface(cartesian,ellipsoid){var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Vector3$1();var{oneOverRadii,oneOverRadiiSquared,centerToleranceSquared}=ellipsoid;scratchVector$5.from(cartesian);var positionX=cartesian.x;var positionY=cartesian.y;var positionZ=cartesian.z;var oneOverRadiiX=oneOverRadii.x;var oneOverRadiiY=oneOverRadii.y;var oneOverRadiiZ=oneOverRadii.z;var x2=positionX*positionX*oneOverRadiiX*oneOverRadiiX;var y2=positionY*positionY*oneOverRadiiY*oneOverRadiiY;var z2=positionZ*positionZ*oneOverRadiiZ*oneOverRadiiZ;var squaredNorm=x2+y2+z2;var ratio=Math.sqrt(1.0/squaredNorm);if(!Number.isFinite(ratio)){return undefined;}var intersection=scaleToGeodeticSurfaceIntersection;intersection.copy(cartesian).scale(ratio);if(squaredNorm<centerToleranceSquared){return intersection.to(result);}var oneOverRadiiSquaredX=oneOverRadiiSquared.x;var oneOverRadiiSquaredY=oneOverRadiiSquared.y;var oneOverRadiiSquaredZ=oneOverRadiiSquared.z;var gradient=scaleToGeodeticSurfaceGradient;gradient.set(intersection.x*oneOverRadiiSquaredX*2.0,intersection.y*oneOverRadiiSquaredY*2.0,intersection.z*oneOverRadiiSquaredZ*2.0);var lambda=(1.0-ratio)*cartesian.len()/(0.5*gradient.len());var correction=0.0;var xMultiplier;var yMultiplier;var zMultiplier;var func;do{lambda-=correction;xMultiplier=1.0/(1.0+lambda*oneOverRadiiSquaredX);yMultiplier=1.0/(1.0+lambda*oneOverRadiiSquaredY);zMultiplier=1.0/(1.0+lambda*oneOverRadiiSquaredZ);var xMultiplier2=xMultiplier*xMultiplier;var yMultiplier2=yMultiplier*yMultiplier;var zMultiplier2=zMultiplier*zMultiplier;var xMultiplier3=xMultiplier2*xMultiplier;var yMultiplier3=yMultiplier2*yMultiplier;var zMultiplier3=zMultiplier2*zMultiplier;func=x2*xMultiplier2+y2*yMultiplier2+z2*zMultiplier2-1.0;var denominator=x2*xMultiplier3*oneOverRadiiSquaredX+y2*yMultiplier3*oneOverRadiiSquaredY+z2*zMultiplier3*oneOverRadiiSquaredZ;var derivative=-2.0*denominator;correction=func/derivative;}while(Math.abs(func)>_MathUtils.EPSILON12);return scratchVector$5.scale([xMultiplier,yMultiplier,zMultiplier]).to(result);}var EPSILON14=1e-14;var scratchOrigin=new Vector3$1();var VECTOR_PRODUCT_LOCAL_FRAME={up:{south:'east',north:'west',west:'south',east:'north'},down:{south:'west',north:'east',west:'north',east:'south'},south:{up:'west',down:'east',west:'down',east:'up'},north:{up:'east',down:'west',west:'up',east:'down'},west:{up:'north',down:'south',north:'down',south:'up'},east:{up:'south',down:'north',north:'up',south:'down'}};var degeneratePositionLocalFrame={north:[-1,0,0],east:[0,1,0],up:[0,0,1],south:[1,0,0],west:[0,-1,0],down:[0,0,-1]};var scratchAxisVectors={east:new Vector3$1(),north:new Vector3$1(),up:new Vector3$1(),west:new Vector3$1(),south:new Vector3$1(),down:new Vector3$1()};var scratchVector1=new Vector3$1();var scratchVector2$1=new Vector3$1();var scratchVector3$1=new Vector3$1();function localFrameToFixedFrame(ellipsoid,firstAxis,secondAxis,thirdAxis,cartesianOrigin,result){var thirdAxisInferred=VECTOR_PRODUCT_LOCAL_FRAME[firstAxis]&&VECTOR_PRODUCT_LOCAL_FRAME[firstAxis][secondAxis];assert$4(thirdAxisInferred&&(!thirdAxis||thirdAxis===thirdAxisInferred));var firstAxisVector;var secondAxisVector;var thirdAxisVector;var origin=scratchOrigin.copy(cartesianOrigin);var atPole=equals$1(origin.x,0.0,EPSILON14)&&equals$1(origin.y,0.0,EPSILON14);if(atPole){var sign=Math.sign(origin.z);firstAxisVector=scratchVector1.fromArray(degeneratePositionLocalFrame[firstAxis]);if(firstAxis!=='east'&&firstAxis!=='west'){firstAxisVector.scale(sign);}secondAxisVector=scratchVector2$1.fromArray(degeneratePositionLocalFrame[secondAxis]);if(secondAxis!=='east'&&secondAxis!=='west'){secondAxisVector.scale(sign);}thirdAxisVector=scratchVector3$1.fromArray(degeneratePositionLocalFrame[thirdAxis]);if(thirdAxis!=='east'&&thirdAxis!=='west'){thirdAxisVector.scale(sign);}}else {var{up,east,north}=scratchAxisVectors;east.set(-origin.y,origin.x,0.0).normalize();ellipsoid.geodeticSurfaceNormal(origin,up);north.copy(up).cross(east);var{down,west,south}=scratchAxisVectors;down.copy(up).scale(-1);west.copy(east).scale(-1);south.copy(north).scale(-1);firstAxisVector=scratchAxisVectors[firstAxis];secondAxisVector=scratchAxisVectors[secondAxis];thirdAxisVector=scratchAxisVectors[thirdAxis];}result[0]=firstAxisVector.x;result[1]=firstAxisVector.y;result[2]=firstAxisVector.z;result[3]=0.0;result[4]=secondAxisVector.x;result[5]=secondAxisVector.y;result[6]=secondAxisVector.z;result[7]=0.0;result[8]=thirdAxisVector.x;result[9]=thirdAxisVector.y;result[10]=thirdAxisVector.z;result[11]=0.0;result[12]=origin.x;result[13]=origin.y;result[14]=origin.z;result[15]=1.0;return result;}var scratchVector$4=new Vector3$1();var scratchNormal$2=new Vector3$1();var scratchK=new Vector3$1();var scratchPosition$2=new Vector3$1();var scratchHeight=new Vector3$1();var scratchCartesian=new Vector3$1();var wgs84;class Ellipsoid{static get WGS84(){wgs84=wgs84||new Ellipsoid(WGS84_RADIUS_X$1,WGS84_RADIUS_Y$1,WGS84_RADIUS_Z$1);return wgs84;}constructor(){var x=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0.0;var y=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;var z=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0.0;assert$4(x>=0.0);assert$4(y>=0.0);assert$4(z>=0.0);this.radii=new Vector3$1(x,y,z);this.radiiSquared=new Vector3$1(x*x,y*y,z*z);this.radiiToTheFourth=new Vector3$1(x*x*x*x,y*y*y*y,z*z*z*z);this.oneOverRadii=new Vector3$1(x===0.0?0.0:1.0/x,y===0.0?0.0:1.0/y,z===0.0?0.0:1.0/z);this.oneOverRadiiSquared=new Vector3$1(x===0.0?0.0:1.0/(x*x),y===0.0?0.0:1.0/(y*y),z===0.0?0.0:1.0/(z*z));this.minimumRadius=Math.min(x,y,z);this.maximumRadius=Math.max(x,y,z);this.centerToleranceSquared=_MathUtils.EPSILON1;if(this.radiiSquared.z!==0){this.squaredXOverSquaredZ=this.radiiSquared.x/this.radiiSquared.z;}Object.freeze(this);}equals(right){return this===right||Boolean(right&&this.radii.equals(right.radii));}toString(){return this.radii.toString();}cartographicToCartesian(cartographic){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var normal=scratchNormal$2;var k=scratchK;var[,,height]=cartographic;this.geodeticSurfaceNormalCartographic(cartographic,normal);k.copy(this.radiiSquared).scale(normal);var gamma=Math.sqrt(normal.dot(k));k.scale(1/gamma);normal.scale(height);k.add(normal);return k.to(result);}cartesianToCartographic(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];scratchCartesian.from(cartesian);var point=this.scaleToGeodeticSurface(scratchCartesian,scratchPosition$2);if(!point){return undefined;}var normal=this.geodeticSurfaceNormal(point,scratchNormal$2);var h=scratchHeight;h.copy(scratchCartesian).subtract(point);var longitude=Math.atan2(normal.y,normal.x);var latitude=Math.asin(normal.z);var height=Math.sign(dot$2(h,scratchCartesian))*length$2(h);return toCartographicFromRadians([longitude,latitude,height],result);}eastNorthUpToFixedFrame(origin){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:new Matrix4$1();return localFrameToFixedFrame(this,'east','north','up',origin,result);}localFrameToFixedFrame(firstAxis,secondAxis,thirdAxis,origin){var result=arguments.length>4&&arguments[4]!==undefined?arguments[4]:new Matrix4$1();return localFrameToFixedFrame(this,firstAxis,secondAxis,thirdAxis,origin,result);}geocentricSurfaceNormal(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchVector$4.from(cartesian).normalize().to(result);}geodeticSurfaceNormalCartographic(cartographic){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var cartographicVectorRadians=fromCartographicToRadians(cartographic);var longitude=cartographicVectorRadians[0];var latitude=cartographicVectorRadians[1];var cosLatitude=Math.cos(latitude);scratchVector$4.set(cosLatitude*Math.cos(longitude),cosLatitude*Math.sin(longitude),Math.sin(latitude)).normalize();return scratchVector$4.to(result);}geodeticSurfaceNormal(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchVector$4.from(cartesian).scale(this.oneOverRadiiSquared).normalize().to(result);}scaleToGeodeticSurface(cartesian,result){return scaleToGeodeticSurface(cartesian,this,result);}scaleToGeocentricSurface(cartesian){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];scratchPosition$2.from(cartesian);var positionX=scratchPosition$2.x;var positionY=scratchPosition$2.y;var positionZ=scratchPosition$2.z;var oneOverRadiiSquared=this.oneOverRadiiSquared;var beta=1.0/Math.sqrt(positionX*positionX*oneOverRadiiSquared.x+positionY*positionY*oneOverRadiiSquared.y+positionZ*positionZ*oneOverRadiiSquared.z);return scratchPosition$2.multiplyScalar(beta).to(result);}transformPositionToScaledSpace(position){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchPosition$2.from(position).scale(this.oneOverRadii).to(result);}transformPositionFromScaledSpace(position){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];return scratchPosition$2.from(position).scale(this.radii).to(result);}getSurfaceNormalIntersectionWithZAxis(position){var buffer=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[0,0,0];assert$4(equals$1(this.radii.x,this.radii.y,_MathUtils.EPSILON15));assert$4(this.radii.z>0);scratchPosition$2.from(position);var z=scratchPosition$2.z*(1-this.squaredXOverSquaredZ);if(Math.abs(z)>=this.radii.z-buffer){return undefined;}return scratchPosition$2.set(0.0,0.0,z).to(result);}}class DoublyLinkedListNode{constructor(item,previous,next){_defineProperty$1(this,"item",void 0);_defineProperty$1(this,"previous",void 0);_defineProperty$1(this,"next",void 0);this.item=item;this.previous=previous;this.next=next;}}class DoublyLinkedList{constructor(){_defineProperty$1(this,"head",null);_defineProperty$1(this,"tail",null);_defineProperty$1(this,"_length",0);}get length(){return this._length;}add(item){var node=new DoublyLinkedListNode(item,this.tail,null);if(this.tail){this.tail.next=node;this.tail=node;}else {this.head=node;this.tail=node;}++this._length;return node;}remove(node){if(!node){return;}if(node.previous&&node.next){node.previous.next=node.next;node.next.previous=node.previous;}else if(node.previous){node.previous.next=null;this.tail=node.previous;}else if(node.next){node.next.previous=null;this.head=node.next;}else {this.head=null;this.tail=null;}node.next=null;node.previous=null;--this._length;}splice(node,nextNode){if(node===nextNode){return;}this.remove(nextNode);this._insert(node,nextNode);}_insert(node,nextNode){var oldNodeNext=node.next;node.next=nextNode;if(this.tail===node){this.tail=nextNode;}else {oldNodeNext.previous=nextNode;}nextNode.next=oldNodeNext;nextNode.previous=node;++this._length;}}function defined$5(x){return x!==undefined&&x!==null;}class TilesetCache{constructor(){_defineProperty$1(this,"_list",void 0);_defineProperty$1(this,"_sentinel",void 0);_defineProperty$1(this,"_trimTiles",void 0);this._list=new DoublyLinkedList();this._sentinel=this._list.add('sentinel');this._trimTiles=false;}reset(){this._list.splice(this._list.tail,this._sentinel);}touch(tile){var node=tile._cacheNode;if(defined$5(node)){this._list.splice(this._sentinel,node);}}add(tileset,tile,addCallback){if(!defined$5(tile._cacheNode)){tile._cacheNode=this._list.add(tile);if(addCallback){addCallback(tileset,tile);}}}unloadTile(tileset,tile,unloadCallback){var node=tile._cacheNode;if(!defined$5(node)){return;}this._list.remove(node);tile._cacheNode=undefined;if(unloadCallback){unloadCallback(tileset,tile);}}unloadTiles(tileset,unloadCallback){var trimTiles=this._trimTiles;this._trimTiles=false;var list=this._list;var maximumMemoryUsageInBytes=(Potree.settings.tiles3DMaxMemory||tileset.maximumMemoryUsage)*1024*1024;var sentinel=this._sentinel;var node=list.head;/* while (node !== sentinel && (tileset.gpuMemoryUsageInBytes > maximumMemoryUsageInBytes || trimTiles)) {
  78837. const tile = node.item;
  78838. node = node.next;
  78839. this.unloadTile(tileset, tile, unloadCallback);
  78840. } */ //改
  78841. while(node!==sentinel&&(getGpuMemoryUsage()>maximumMemoryUsageInBytes||trimTiles)){var tile=node.item;node=node.next;this.unloadTile(tileset,tile,unloadCallback);if(viewer.visiVertexCount>1500000){//add: 针对部分特别精细的很卡如 https://4dkk.4dage.com/scene_view_data/SG-t-WReTBN204dQ/images/3dtiles/tileset.json
  78842. tileset.options.maximumScreenSpaceError*=1.1;tileset.options.maximumScreenSpaceError=Math.min(1000,tileset.options.maximumScreenSpaceError);}}}trim(){this._trimTiles=true;}}function calculateTransformProps(tileHeader,tile){assert$7(tileHeader);assert$7(tile);var{rtcCenter,gltfUpAxis}=tile;var{computedTransform,boundingVolume:{center}}=tileHeader;var modelMatrix=new Matrix4$1(computedTransform);if(rtcCenter){modelMatrix.translate(rtcCenter);}switch(gltfUpAxis){case'Z':break;case'Y':var rotationY=new Matrix4$1().rotateX(Math.PI/2);modelMatrix=modelMatrix.multiplyRight(rotationY);break;case'X':var rotationX=new Matrix4$1().rotateY(-Math.PI/2);modelMatrix=modelMatrix.multiplyRight(rotationX);break;}if(tile.isQuantized){modelMatrix.translate(tile.quantizedVolumeOffset).scale(tile.quantizedVolumeScale);}var cartesianOrigin=new Vector3$1(center);tile.cartesianModelMatrix=modelMatrix;tile.cartesianOrigin=cartesianOrigin;var cartographicOrigin=Ellipsoid.WGS84.cartesianToCartographic(cartesianOrigin,new Vector3$1());var fromFixedFrameMatrix=Ellipsoid.WGS84.eastNorthUpToFixedFrame(cartesianOrigin);var toFixedFrameMatrix=fromFixedFrameMatrix.invert();tile.cartographicModelMatrix=toFixedFrameMatrix.multiplyRight(modelMatrix);tile.cartographicOrigin=cartographicOrigin;if(!tile.coordinateSystem){tile.modelMatrix=tile.cartographicModelMatrix;}}var INTERSECTION=Object.freeze({OUTSIDE:-1,INTERSECTING:0,INSIDE:1});new Vector3$1();new Vector3$1();var scratchVector$3=new Vector3$1();var scratchVector2=new Vector3$1();class BoundingSphere{constructor(){var center=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[0,0,0];var radius=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0.0;this.radius=-0;this.center=new Vector3$1();this.fromCenterRadius(center,radius);}fromCenterRadius(center,radius){this.center.from(center);this.radius=radius;return this;}fromCornerPoints(corner,oppositeCorner){oppositeCorner=scratchVector$3.from(oppositeCorner);this.center=new Vector3$1().from(corner).add(oppositeCorner).scale(0.5);this.radius=this.center.distance(oppositeCorner);return this;}equals(right){return this===right||Boolean(right)&&this.center.equals(right.center)&&this.radius===right.radius;}clone(){return new BoundingSphere(this.center,this.radius);}union(boundingSphere){var leftCenter=this.center;var leftRadius=this.radius;var rightCenter=boundingSphere.center;var rightRadius=boundingSphere.radius;var toRightCenter=scratchVector$3.copy(rightCenter).subtract(leftCenter);var centerSeparation=toRightCenter.magnitude();if(leftRadius>=centerSeparation+rightRadius){return this.clone();}if(rightRadius>=centerSeparation+leftRadius){return boundingSphere.clone();}var halfDistanceBetweenTangentPoints=(leftRadius+centerSeparation+rightRadius)*0.5;scratchVector2.copy(toRightCenter).scale((-leftRadius+halfDistanceBetweenTangentPoints)/centerSeparation).add(leftCenter);this.center.copy(scratchVector2);this.radius=halfDistanceBetweenTangentPoints;return this;}expand(point){point=scratchVector$3.from(point);var radius=point.subtract(this.center).magnitude();if(radius>this.radius){this.radius=radius;}return this;}transform(transform){this.center.transform(transform);var scale=getScaling(scratchVector$3,transform);this.radius=Math.max(scale[0],Math.max(scale[1],scale[2]))*this.radius;return this;}distanceSquaredTo(point){var d=this.distanceTo(point);return d*d;}distanceTo(point){point=scratchVector$3.from(point);var delta=point.subtract(this.center);return Math.max(0,delta.len()-this.radius);}intersectPlane(plane){var center=this.center;var radius=this.radius;var normal=plane.normal;var distanceToPlane=normal.dot(center)+plane.distance;if(distanceToPlane<-radius){return INTERSECTION.OUTSIDE;}if(distanceToPlane<radius){return INTERSECTION.INTERSECTING;}return INTERSECTION.INSIDE;}}var scratchVector3=new Vector3$1();var scratchOffset=new Vector3$1();var scratchVectorU=new Vector3$1();var scratchVectorV=new Vector3$1();var scratchVectorW=new Vector3$1();var scratchCorner=new Vector3$1();var scratchToCenter=new Vector3$1();var MATRIX3={COLUMN0ROW0:0,COLUMN0ROW1:1,COLUMN0ROW2:2,COLUMN1ROW0:3,COLUMN1ROW1:4,COLUMN1ROW2:5,COLUMN2ROW0:6,COLUMN2ROW1:7,COLUMN2ROW2:8};class OrientedBoundingBox{constructor(){var center=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[0,0,0];var halfAxes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0,0,0,0,0,0,0];this.center=new Vector3$1().from(center);this.halfAxes=new Matrix3$1(halfAxes);}get halfSize(){var xAxis=this.halfAxes.getColumn(0);var yAxis=this.halfAxes.getColumn(1);var zAxis=this.halfAxes.getColumn(2);return [new Vector3$1(xAxis).len(),new Vector3$1(yAxis).len(),new Vector3$1(zAxis).len()];}get quaternion(){var xAxis=this.halfAxes.getColumn(0);var yAxis=this.halfAxes.getColumn(1);var zAxis=this.halfAxes.getColumn(2);var normXAxis=new Vector3$1(xAxis).normalize();var normYAxis=new Vector3$1(yAxis).normalize();var normZAxis=new Vector3$1(zAxis).normalize();return new Quaternion$1().fromMatrix3(new Matrix3$1([...normXAxis,...normYAxis,...normZAxis]));}fromCenterHalfSizeQuaternion(center,halfSize,quaternion){var quaternionObject=new Quaternion$1(quaternion);var directionsMatrix=new Matrix3$1().fromQuaternion(quaternionObject);directionsMatrix[0]=directionsMatrix[0]*halfSize[0];directionsMatrix[1]=directionsMatrix[1]*halfSize[0];directionsMatrix[2]=directionsMatrix[2]*halfSize[0];directionsMatrix[3]=directionsMatrix[3]*halfSize[1];directionsMatrix[4]=directionsMatrix[4]*halfSize[1];directionsMatrix[5]=directionsMatrix[5]*halfSize[1];directionsMatrix[6]=directionsMatrix[6]*halfSize[2];directionsMatrix[7]=directionsMatrix[7]*halfSize[2];directionsMatrix[8]=directionsMatrix[8]*halfSize[2];this.center=new Vector3$1().from(center);this.halfAxes=directionsMatrix;return this;}clone(){return new OrientedBoundingBox(this.center,this.halfAxes);}equals(right){return this===right||Boolean(right)&&this.center.equals(right.center)&&this.halfAxes.equals(right.halfAxes);}getBoundingSphere(){var result=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new BoundingSphere();var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);//前三个
  78843. var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var cornerVector=scratchVector3.copy(u).add(v).add(w);result.center.copy(this.center);result.radius=cornerVector.magnitude();return result;}intersectPlane(plane){var center=this.center;var normal=plane.normal;var halfAxes=this.halfAxes;var normalX=normal.x;var normalY=normal.y;var normalZ=normal.z;var radEffective=Math.abs(normalX*halfAxes[MATRIX3.COLUMN0ROW0]+normalY*halfAxes[MATRIX3.COLUMN0ROW1]+normalZ*halfAxes[MATRIX3.COLUMN0ROW2])+Math.abs(normalX*halfAxes[MATRIX3.COLUMN1ROW0]+normalY*halfAxes[MATRIX3.COLUMN1ROW1]+normalZ*halfAxes[MATRIX3.COLUMN1ROW2])+Math.abs(normalX*halfAxes[MATRIX3.COLUMN2ROW0]+normalY*halfAxes[MATRIX3.COLUMN2ROW1]+normalZ*halfAxes[MATRIX3.COLUMN2ROW2]);var distanceToPlane=normal.dot(center)+plane.distance;if(distanceToPlane<=-radEffective){return INTERSECTION.OUTSIDE;}else if(distanceToPlane>=radEffective){return INTERSECTION.INSIDE;}return INTERSECTION.INTERSECTING;//在相机frustum内
  78844. }distanceTo(point){return Math.sqrt(this.distanceSquaredTo(point));}/* distanceSquaredTo(point) {//相机到bound外壳的距离平方
  78845. let center = this.center.clone()
  78846. center.z *= -1
  78847. const offset = scratchOffset.from(point).subtract(center);
  78848. const halfAxes = this.halfAxes;
  78849. const u = halfAxes.getColumn(0, scratchVectorU);
  78850. const v = halfAxes.getColumn(1, scratchVectorV);
  78851. const w = halfAxes.getColumn(2, scratchVectorW);
  78852. u.z *= -1
  78853. v.z *= -1
  78854. w.z *= -1
  78855. const uHalf = u.magnitude();
  78856. const vHalf = v.magnitude();
  78857. const wHalf = w.magnitude();
  78858. u.normalize();
  78859. v.normalize();
  78860. w.normalize();
  78861. let distanceSquared = 0.0;
  78862. let d;
  78863. d = Math.abs(offset.dot(u)) - uHalf;
  78864. if (d > 0) {
  78865. distanceSquared += d * d;
  78866. }
  78867. d = Math.abs(offset.dot(v)) - vHalf;
  78868. if (d > 0) {
  78869. distanceSquared += d * d;
  78870. }
  78871. d = Math.abs(offset.dot(w)) - wHalf;
  78872. if (d > 0) {
  78873. distanceSquared += d * d;
  78874. }
  78875. return distanceSquared;
  78876. } */distanceSquaredTo(point){//相机到bound外壳的距离平方
  78877. var offset=scratchOffset.from(point).subtract(this.center);var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var uHalf=u.magnitude();var vHalf=v.magnitude();var wHalf=w.magnitude();u.normalize();v.normalize();w.normalize();var distanceSquared=0.0;var d;d=Math.abs(offset.dot(u))-uHalf;if(d>0){distanceSquared+=d*d;}d=Math.abs(offset.dot(v))-vHalf;if(d>0){distanceSquared+=d*d;}d=Math.abs(offset.dot(w))-wHalf;if(d>0){distanceSquared+=d*d;}return distanceSquared;}computePlaneDistances(position,direction){var result=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[-0,-0];var minDist=Number.POSITIVE_INFINITY;var maxDist=Number.NEGATIVE_INFINITY;var center=this.center;var halfAxes=this.halfAxes;var u=halfAxes.getColumn(0,scratchVectorU);var v=halfAxes.getColumn(1,scratchVectorV);var w=halfAxes.getColumn(2,scratchVectorW);var corner=scratchCorner.copy(u).add(v).add(w).add(center);var toCenter=scratchToCenter.copy(corner).subtract(position);var mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).add(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).subtract(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);corner.copy(center).add(u).subtract(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).add(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).add(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).subtract(v).add(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);center.copy(corner).subtract(u).subtract(v).subtract(w);toCenter.copy(corner).subtract(position);mag=direction.dot(toCenter);minDist=Math.min(mag,minDist);maxDist=Math.max(mag,maxDist);result[0]=minDist;result[1]=maxDist;return result;}transform(transformation){this.center.transformAsPoint(transformation);var xAxis=this.halfAxes.getColumn(0,scratchVectorU);xAxis.transformAsPoint(transformation);var yAxis=this.halfAxes.getColumn(1,scratchVectorV);yAxis.transformAsPoint(transformation);var zAxis=this.halfAxes.getColumn(2,scratchVectorW);zAxis.transformAsPoint(transformation);this.halfAxes=new Matrix3$1([...xAxis,...yAxis,...zAxis]);return this;}getTransform(){throw new Error('not implemented');}}var scratchPosition$1=new Vector3$1();var scratchNormal$1=new Vector3$1();class Plane$1{constructor(){var normal=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[0,0,1];var distance=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;this.normal=new Vector3$1();this.distance=-0;this.fromNormalDistance(normal,distance);}fromNormalDistance(normal,distance){assert$4(Number.isFinite(distance));this.normal.from(normal).normalize();this.distance=distance;return this;}fromPointNormal(point,normal){point=scratchPosition$1.from(point);this.normal.from(normal).normalize();var distance=-this.normal.dot(point);this.distance=distance;return this;}fromCoefficients(a,b,c,d){this.normal.set(a,b,c);assert$4(equals$1(this.normal.len(),1));this.distance=d;return this;}clone(plane){return new Plane$1(this.normal,this.distance);}equals(right){return equals$1(this.distance,right.distance)&&equals$1(this.normal,right.normal);}getPointDistance(point){return this.normal.dot(point)+this.distance;}transform(matrix4){var normal=scratchNormal$1.copy(this.normal).transformAsVector(matrix4).normalize();var point=this.normal.scale(-this.distance).transform(matrix4);return this.fromPointNormal(point,normal);}projectPointOntoPlane(point){var result=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];point=scratchPosition$1.from(point);var pointDistance=this.getPointDistance(point);var scaledNormal=scratchNormal$1.copy(this.normal).scale(pointDistance);return point.subtract(scaledNormal).to(result);}}var faces=[new Vector3$1([1,0,0]),new Vector3$1([0,1,0]),new Vector3$1([0,0,1])];var scratchPlaneCenter=new Vector3$1();var scratchPlaneNormal$1=new Vector3$1();new Plane$1(new Vector3$1(1.0,0.0,0.0),0.0);class CullingVolume{static get MASK_OUTSIDE(){return 0xffffffff;}static get MASK_INSIDE(){return 0x00000000;}static get MASK_INDETERMINATE(){return 0x7fffffff;}constructor(){var planes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];this.planes=planes;assert$4(this.planes.every(plane=>plane instanceof Plane$1));}fromBoundingSphere(boundingSphere){this.planes.length=2*faces.length;var center=boundingSphere.center;var radius=boundingSphere.radius;var planeIndex=0;for(var faceNormal of faces){var plane0=this.planes[planeIndex];var plane1=this.planes[planeIndex+1];if(!plane0){plane0=this.planes[planeIndex]=new Plane$1();}if(!plane1){plane1=this.planes[planeIndex+1]=new Plane$1();}var plane0Center=scratchPlaneCenter.copy(faceNormal).scale(-radius).add(center);-faceNormal.dot(plane0Center);plane0.fromPointNormal(plane0Center,faceNormal);var plane1Center=scratchPlaneCenter.copy(faceNormal).scale(radius).add(center);var negatedFaceNormal=scratchPlaneNormal$1.copy(faceNormal).negate();-negatedFaceNormal.dot(plane1Center);plane1.fromPointNormal(plane1Center,negatedFaceNormal);planeIndex+=2;}return this;}computeVisibility(boundingVolume){assert$4(boundingVolume);var intersect=INTERSECTION.INSIDE;for(var plane of this.planes){var result=boundingVolume.intersectPlane(plane);switch(result){case INTERSECTION.OUTSIDE:return INTERSECTION.OUTSIDE;case INTERSECTION.INTERSECTING:intersect=INTERSECTION.INTERSECTING;break;}}return intersect;}computeVisibilityWithPlaneMask(boundingVolume,parentPlaneMask){assert$4(boundingVolume,'boundingVolume is required.');assert$4(Number.isFinite(parentPlaneMask),'parentPlaneMask is required.');if(parentPlaneMask===CullingVolume.MASK_OUTSIDE||parentPlaneMask===CullingVolume.MASK_INSIDE){return parentPlaneMask;}var mask=CullingVolume.MASK_INSIDE;var planes=this.planes;for(var k=0;k<this.planes.length;++k){var flag=k<31?1<<k:0;if(k<31&&(parentPlaneMask&flag)===0){continue;}var plane=planes[k];var result=boundingVolume.intersectPlane(plane);if(result===INTERSECTION.OUTSIDE){return CullingVolume.MASK_OUTSIDE;}else if(result===INTERSECTION.INTERSECTING){mask|=flag;}}return mask;}}var scratchPlaneUpVector=new Vector3$1();var scratchPlaneRightVector=new Vector3$1();var scratchPlaneNearCenter=new Vector3$1();var scratchPlaneFarCenter=new Vector3$1();var scratchPlaneNormal=new Vector3$1();class PerspectiveOffCenterFrustum{constructor(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};options=_objectSpread2({near:1.0,far:500000000.0},options);this.left=options.left;this._left=undefined;this.right=options.right;this._right=undefined;this.top=options.top;this._top=undefined;this.bottom=options.bottom;this._bottom=undefined;this.near=options.near;this._near=this.near;this.far=options.far;this._far=this.far;this._cullingVolume=new CullingVolume([new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1()]);this._perspectiveMatrix=new Matrix4$1();this._infinitePerspective=new Matrix4$1();}clone(){return new PerspectiveOffCenterFrustum({right:this.right,left:this.left,top:this.top,bottom:this.bottom,near:this.near,far:this.far});}equals(other){return other&&other instanceof PerspectiveOffCenterFrustum&&this.right===other.right&&this.left===other.left&&this.top===other.top&&this.bottom===other.bottom&&this.near===other.near&&this.far===other.far;}get projectionMatrix(){update$1(this);return this._perspectiveMatrix;}get infiniteProjectionMatrix(){update$1(this);return this._infinitePerspective;}computeCullingVolume(position,direction,up){assert$4(position,'position is required.');assert$4(direction,'direction is required.');assert$4(up,'up is required.');var planes=this._cullingVolume.planes;up=scratchPlaneUpVector.copy(up).normalize();var right=scratchPlaneRightVector.copy(direction).cross(up).normalize();var nearCenter=scratchPlaneNearCenter.copy(direction).multiplyByScalar(this.near).add(position);var farCenter=scratchPlaneFarCenter.copy(direction).multiplyByScalar(this.far).add(position);var normal=scratchPlaneNormal;normal.copy(right).multiplyByScalar(this.left).add(nearCenter).subtract(position).cross(up);planes[0].fromPointNormal(position,normal);normal.copy(right).multiplyByScalar(this.right).add(nearCenter).subtract(position).cross(up).negate();planes[1].fromPointNormal(position,normal);normal.copy(up).multiplyByScalar(this.bottom).add(nearCenter).subtract(position).cross(right).negate();planes[2].fromPointNormal(position,normal);normal.copy(up).multiplyByScalar(this.top).add(nearCenter).subtract(position).cross(right);planes[3].fromPointNormal(position,normal);normal=new Vector3$1().copy(direction);planes[4].fromPointNormal(nearCenter,normal);normal.negate();planes[5].fromPointNormal(farCenter,normal);return this._cullingVolume;}getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result){update$1(this);assert$4(Number.isFinite(drawingBufferWidth)&&Number.isFinite(drawingBufferHeight));assert$4(drawingBufferWidth>0);assert$4(drawingBufferHeight>0);assert$4(distance>0);assert$4(result);var inverseNear=1.0/this.near;var tanTheta=this.top*inverseNear;var pixelHeight=2.0*distance*tanTheta/drawingBufferHeight;tanTheta=this.right*inverseNear;var pixelWidth=2.0*distance*tanTheta/drawingBufferWidth;result.x=pixelWidth;result.y=pixelHeight;return result;}}function update$1(frustum){assert$4(Number.isFinite(frustum.right)&&Number.isFinite(frustum.left)&&Number.isFinite(frustum.top)&&Number.isFinite(frustum.bottom)&&Number.isFinite(frustum.near)&&Number.isFinite(frustum.far));var{top,bottom,right,left,near,far}=frustum;if(top!==frustum._top||bottom!==frustum._bottom||left!==frustum._left||right!==frustum._right||near!==frustum._near||far!==frustum._far){assert$4(frustum.near>0&&frustum.near<frustum.far,'near must be greater than zero and less than far.');frustum._left=left;frustum._right=right;frustum._top=top;frustum._bottom=bottom;frustum._near=near;frustum._far=far;frustum._perspectiveMatrix=new Matrix4$1().frustum({left,right,bottom,top,near,far});frustum._infinitePerspective=new Matrix4$1().frustum({left,right,bottom,top,near,far:Infinity});}}var defined$4=val=>val!==null&&typeof val!=='undefined';class PerspectiveFrustum{constructor(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};options=_objectSpread2({near:1.0,far:500000000.0,xOffset:0.0,yOffset:0.0},options);this._offCenterFrustum=new PerspectiveOffCenterFrustum();this.fov=options.fov;this._fov=undefined;this._fovy=undefined;this._sseDenominator=undefined;this.aspectRatio=options.aspectRatio;this._aspectRatio=undefined;this.near=options.near;this._near=this.near;this.far=options.far;this._far=this.far;this.xOffset=options.xOffset;this._xOffset=this.xOffset;this.yOffset=options.yOffset;this._yOffset=this.yOffset;}clone(){return new PerspectiveFrustum({aspectRatio:this.aspectRatio,fov:this.fov,near:this.near,far:this.far});}equals(other){if(!defined$4(other)||!(other instanceof PerspectiveFrustum)){return false;}update(this);update(other);return this.fov===other.fov&&this.aspectRatio===other.aspectRatio&&this.near===other.near&&this.far===other.far&&this._offCenterFrustum.equals(other._offCenterFrustum);}get projectionMatrix(){update(this);return this._offCenterFrustum.projectionMatrix;}get infiniteProjectionMatrix(){update(this);return this._offCenterFrustum.infiniteProjectionMatrix;}get fovy(){update(this);return this._fovy;}get sseDenominator(){update(this);return this._sseDenominator;}computeCullingVolume(position,direction,up){update(this);return this._offCenterFrustum.computeCullingVolume(position,direction,up);}getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result){update(this);return this._offCenterFrustum.getPixelDimensions(drawingBufferWidth,drawingBufferHeight,distance,result);}}function update(frustum){assert$4(Number.isFinite(frustum.fov)&&Number.isFinite(frustum.aspectRatio)&&Number.isFinite(frustum.near)&&Number.isFinite(frustum.far));var f=frustum._offCenterFrustum;if(frustum.fov!==frustum._fov||frustum.aspectRatio!==frustum._aspectRatio||frustum.near!==frustum._near||frustum.far!==frustum._far||frustum.xOffset!==frustum._xOffset||frustum.yOffset!==frustum._yOffset){assert$4(frustum.fov>=0&&frustum.fov<Math.PI);//assert$4(frustum.aspectRatio > 0);
  78878. if(frustum.aspectRatio==0){console.log(1);}assert$4(frustum.near>=0&&frustum.near<frustum.far);frustum._aspectRatio=Math.max(0.001,frustum.aspectRatio);frustum._fov=frustum.fov;frustum._fovy=frustum._aspectRatio<=1?frustum.fov:Math.atan(Math.tan(frustum.fov*0.5)/frustum._aspectRatio)*2.0;frustum._near=frustum.near;frustum._far=frustum.far;frustum._sseDenominator=2.0*Math.tan(0.5*frustum._fovy);frustum._xOffset=frustum.xOffset;frustum._yOffset=frustum.yOffset;f.top=frustum.near*Math.tan(0.5*frustum._fovy);f.bottom=-f.top;f.right=frustum._aspectRatio*f.top;f.left=-f.right;f.near=frustum.near;f.far=frustum.far;f.right+=frustum.xOffset;f.left+=frustum.xOffset;f.top+=frustum.yOffset;f.bottom+=frustum.yOffset;}}new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Matrix3$1();new Matrix3$1();new Matrix3$1();new Matrix3$1();new Matrix3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();new Matrix3$1();({diagonal:new Matrix3$1(),unitary:new Matrix3$1()});var scratchVector$2=new Vector3$1();var scratchPosition=new Vector3$1();var cullingVolume=new CullingVolume([new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1(),new Plane$1()]);function getFrameState(viewport,frameNumber){var{cameraDirection,cameraUp,height}=viewport;var{metersPerUnit}=viewport.distanceScales;var viewportCenterCartographic=viewport.unprojectPosition(viewport.center);var viewportCenterCartesian=Ellipsoid.WGS84.cartographicToCartesian(viewportCenterCartographic,new Vector3$1());var enuToFixedTransform=Ellipsoid.WGS84.eastNorthUpToFixedFrame(viewportCenterCartesian);var cameraPositionCartographic=viewport.unprojectPosition(viewport.cameraPosition);var cameraPositionCartesian=Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic,new Vector3$1());var cameraDirectionCartesian=new Vector3$1(enuToFixedTransform.transformAsVector(new Vector3$1(cameraDirection).scale(metersPerUnit))).normalize();var cameraUpCartesian=new Vector3$1(enuToFixedTransform.transformAsVector(new Vector3$1(cameraUp).scale(metersPerUnit))).normalize();commonSpacePlanesToWGS84(viewport,viewportCenterCartesian);return {camera:{position:cameraPositionCartesian,direction:cameraDirectionCartesian,up:cameraUpCartesian},viewport,height,cullingVolume,frameNumber,sseDenominator:1.15};}function commonSpacePlanesToWGS84(viewport,viewportCenterCartesian){var frustumPlanes=viewport.getFrustumPlanes();var i=0;for(var dir in frustumPlanes){var plane=frustumPlanes[dir];var distanceToCenter=plane.normal.dot(viewport.center);scratchPosition.copy(plane.normal).scale(plane.distance-distanceToCenter).add(viewport.center);var cartographicPos=viewport.unprojectPosition(scratchPosition);var cartesianPos=Ellipsoid.WGS84.cartographicToCartesian(cartographicPos,new Vector3$1());cullingVolume.planes[i++].fromPointNormal(cartesianPos,scratchVector$2.copy(viewportCenterCartesian).subtract(cartesianPos));}}var WGS84_RADIUS_X=6378137.0;var WGS84_RADIUS_Y=6378137.0;var WGS84_RADIUS_Z=6356752.3142451793;var scratchVector$1=new Vector3$1();function getZoomFromBoundingVolume(boundingVolume){var{halfAxes,radius,width,height}=boundingVolume;if(halfAxes){var obbSize=getObbSize(halfAxes);return Math.log2(WGS84_RADIUS_Z/obbSize);}else if(radius){return Math.log2(WGS84_RADIUS_Z/radius);}else if(height&&width){var zoomX=Math.log2(WGS84_RADIUS_X/width);var zoomY=Math.log2(WGS84_RADIUS_Y/height);return (zoomX+zoomY)/2;}return 1;}function getObbSize(halfAxes){halfAxes.getColumn(0,scratchVector$1);var axeY=halfAxes.getColumn(1);var axeZ=halfAxes.getColumn(2);var farthestVertex=scratchVector$1.add(axeY).add(axeZ);var size=farthestVertex.len();return size;}var TILE_CONTENT_STATE={UNLOADED:0,LOADING:1,PROCESSING:2,READY:3,EXPIRED:4,FAILED:5};var TILE_REFINEMENT={ADD:1,REPLACE:2};var TILE_TYPE={EMPTY:'empty',SCENEGRAPH:'scenegraph',POINTCLOUD:'pointcloud',MESH:'mesh'};var TILESET_TYPE={I3S:'I3S',TILES3D:'TILES3D'};var LOD_METRIC_TYPE={GEOMETRIC_ERROR:'geometricError',MAX_SCREEN_THRESHOLD:'maxScreenThreshold'};var TILE3D_OPTIMIZATION_HINT={NOT_COMPUTED:-1,USE_OPTIMIZATION:1,SKIP_OPTIMIZATION:0};function defined$3(x){return x!==undefined&&x!==null;}var scratchScale=new Vector3$1();var scratchNorthWest=new Vector3$1();var scratchSouthEast=new Vector3$1();function createBoundingVolume(boundingVolumeHeader,transform,result){assert$7(boundingVolumeHeader,'3D Tile: boundingVolume must be defined');if(boundingVolumeHeader.box){return createBox(boundingVolumeHeader.box,transform,result);}if(boundingVolumeHeader.region){var[west,south,east,north,minHeight,maxHeight]=boundingVolumeHeader.region;var northWest=Ellipsoid.WGS84.cartographicToCartesian([degrees(west),degrees(north),minHeight],scratchNorthWest);var southEast=Ellipsoid.WGS84.cartographicToCartesian([degrees(east),degrees(south),maxHeight],scratchSouthEast);var centerInCartesian=new Vector3$1().addVectors(northWest,southEast).multiplyScalar(0.5);var radius=new Vector3$1().subVectors(northWest,southEast).len()/2.0;return createSphere([centerInCartesian[0],centerInCartesian[1],centerInCartesian[2],radius],new Matrix4$1());}if(boundingVolumeHeader.sphere){return createSphere(boundingVolumeHeader.sphere,transform,result);}throw new Error('3D Tile: boundingVolume must contain a sphere, region, or box');}function createBox(box,transform,result){var center=new Vector3$1(box[0],box[1],box[2]);result&&(result.oriCenter=center);//add
  78879. transform.transform(center,center);var origin=[];if(box.length===10){var halfSize=box.slice(3,6);var quaternion=new Quaternion$1();quaternion.fromArray(box,6);var x=new Vector3$1([1,0,0]);var y=new Vector3$1([0,1,0]);var z=new Vector3$1([0,0,1]);x.transformByQuaternion(quaternion);x.scale(halfSize[0]);y.transformByQuaternion(quaternion);y.scale(halfSize[1]);z.transformByQuaternion(quaternion);z.scale(halfSize[2]);origin=[...x.toArray(),...y.toArray(),...z.toArray()];}else {origin=[...box.slice(3,6),...box.slice(6,9),...box.slice(9,12)];}var xAxis=transform.transformAsVector(origin.slice(0,3));var yAxis=transform.transformAsVector(origin.slice(3,6));var zAxis=transform.transformAsVector(origin.slice(6,9));var halfAxes=new Matrix3$1([xAxis[0],xAxis[1],xAxis[2],yAxis[0],yAxis[1],yAxis[2],zAxis[0],zAxis[1],zAxis[2]]);//const halfAxes = new Matrix3([xAxis[0], xAxis[1], -xAxis[2], yAxis[0], yAxis[1], -yAxis[2], zAxis[0], zAxis[1], -zAxis[2]]);//改
  78880. //center.z *= -1//add
  78881. if(defined$3(result)){result.center=center;result.halfAxes=halfAxes;return result;}return new OrientedBoundingBox(center,halfAxes);}function createSphere(sphere,transform,result){var center=new Vector3$1(sphere[0],sphere[1],sphere[2]);transform.transform(center,center);var scale=transform.getScale(scratchScale);var uniformScale=Math.max(Math.max(scale[0],scale[1]),scale[2]);var radius=sphere[3]*uniformScale;if(defined$3(result)){result.center=center;result.radius=radius;return result;}return new BoundingSphere(center,radius);}new Vector3$1();new Vector3$1();new Matrix4$1();new Vector3$1();new Vector3$1();new Vector3$1();function fog(distanceToCamera,density){var scalar=distanceToCamera*density;return 1.0-Math.exp(-(scalar*scalar));}function getDynamicScreenSpaceError(tileset,distanceToCamera){if(tileset.dynamicScreenSpaceError&&tileset.dynamicScreenSpaceErrorComputedDensity){var density=tileset.dynamicScreenSpaceErrorComputedDensity;var factor=tileset.dynamicScreenSpaceErrorFactor;var dynamicError=fog(distanceToCamera,density)*factor;return dynamicError;}return 0;}function getTiles3DScreenSpaceError(tile,frameState,useParentLodMetric){var tileset=tile.tileset;var parentLodMetricValue=tile.parent&&tile.parent.lodMetricValue||tile.lodMetricValue;var lodMetricValue=useParentLodMetric?parentLodMetricValue:tile.lodMetricValue;if(lodMetricValue===0.0){return 0.0;}var distance=Math.max(tile._distanceToCamera,1e-7);var{height,sseDenominator}=frameState;var{viewDistanceScale}=tileset.options;var error=lodMetricValue*height*(viewDistanceScale||1.0)/(distance*sseDenominator);error-=getDynamicScreenSpaceError(tileset,distance);return error;}function getLodStatus(tile,frameState){if(tile.lodMetricValue===0||isNaN(tile.lodMetricValue)){return 'DIG';}var screenSize=2*getProjectedRadius(tile,frameState);if(screenSize<2){return 'OUT';}if(!tile.header.children||screenSize<=tile.lodMetricValue){return 'DRAW';}else if(tile.header.children){return 'DIG';}return 'OUT';}function getProjectedRadius(tile,frameState){var originalViewport=frameState.viewport;var ViewportClass=originalViewport.constructor;var{longitude,latitude,height,width,bearing,zoom}=originalViewport;var viewport=new ViewportClass({longitude,latitude,height,width,bearing,zoom,pitch:0});var mbsLat=tile.header.mbs[1];var mbsLon=tile.header.mbs[0];var mbsZ=tile.header.mbs[2];var mbsR=tile.header.mbs[3];var mbsCenterCartesian=[...tile.boundingVolume.center];var cameraPositionCartographic=viewport.unprojectPosition(viewport.cameraPosition);var cameraPositionCartesian=Ellipsoid.WGS84.cartographicToCartesian(cameraPositionCartographic,new Vector3$1());var toEye=new Vector3$1(cameraPositionCartesian).subtract(mbsCenterCartesian).normalize();var enuToCartesianMatrix=new Matrix4$1();Ellipsoid.WGS84.eastNorthUpToFixedFrame(mbsCenterCartesian,enuToCartesianMatrix);var cartesianToEnuMatrix=new Matrix4$1(enuToCartesianMatrix).invert();var cameraPositionEnu=new Vector3$1(cameraPositionCartesian).transform(cartesianToEnuMatrix);var projection=Math.sqrt(cameraPositionEnu[0]*cameraPositionEnu[0]+cameraPositionEnu[1]*cameraPositionEnu[1]);var extraZ=projection*projection/cameraPositionEnu[2];var extraVertexEnu=new Vector3$1([cameraPositionEnu[0],cameraPositionEnu[1],extraZ]);var extraVertexCartesian=extraVertexEnu.transform(enuToCartesianMatrix);var extraVectorCartesian=new Vector3$1(extraVertexCartesian).subtract(mbsCenterCartesian).normalize();var radiusVector=toEye.cross(extraVectorCartesian).normalize().scale(mbsR);var sphereMbsBorderVertexCartesian=new Vector3$1(mbsCenterCartesian).add(radiusVector);var sphereMbsBorderVertexCartographic=Ellipsoid.WGS84.cartesianToCartographic(sphereMbsBorderVertexCartesian);var projectedOrigin=viewport.project([mbsLon,mbsLat,mbsZ]);var projectedMbsBorderVertex=viewport.project(sphereMbsBorderVertexCartographic);var projectedRadius=new Vector3$1(projectedOrigin).subtract(projectedMbsBorderVertex).magnitude();return projectedRadius;}function get3dTilesOptions(tileset){return {assetGltfUpAxis:tileset.asset&&tileset.asset.gltfUpAxis||'Y'};}class ManagedArray{constructor(){var length=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;_defineProperty$1(this,"_map",new Map());_defineProperty$1(this,"_array",void 0);_defineProperty$1(this,"_length",void 0);this._array=new Array(length);this._length=length;}get length(){return this._length;}set length(length){this._length=length;if(length>this._array.length){this._array.length=length;}}get values(){return this._array;}get(index){assert$7(index<this._array.length);return this._array[index];}set(index,element){assert$7(index>=0);if(index>=this.length){this.length=index+1;}if(this._map.has(this._array[index])){this._map.delete(this._array[index]);}this._array[index]=element;this._map.set(element,index);}delete(element){var index=this._map.get(element);if(index>=0){this._array.splice(index,1);this._map.delete(element);this.length--;}}peek(){return this._array[this._length-1];}push(element){if(!this._map.has(element)){var index=this.length++;this._array[index]=element;this._map.set(element,index);}}pop(){var element=this._array[--this.length];this._map.delete(element);return element;}reserve(length){assert$7(length>=0);if(length>this._array.length){this._array.length=length;}}resize(length){assert$7(length>=0);this.length=length;}trim(length){if(length===null||length===undefined){length=this.length;}this._array.length=length;}reset(){this._array=[];this._map=new Map();this._length=0;}find(target){return this._map.has(target);}}var DEFAULT_PROPS$1={loadSiblings:false,skipLevelOfDetail:false,maximumScreenSpaceError:2,updateTransforms:true,onTraversalEnd:()=>{},viewportTraversersMap:{},basePath:''};class TilesetTraverser{constructor(options){_defineProperty$1(this,"options",void 0);_defineProperty$1(this,"root",void 0);_defineProperty$1(this,"requestedTiles",void 0);_defineProperty$1(this,"selectedTiles",void 0);_defineProperty$1(this,"emptyTiles",void 0);_defineProperty$1(this,"_traversalStack",void 0);_defineProperty$1(this,"_emptyTraversalStack",void 0);_defineProperty$1(this,"_frameNumber",void 0);this.options=_objectSpread2(_objectSpread2({},DEFAULT_PROPS$1),options);this._traversalStack=new ManagedArray();this._emptyTraversalStack=new ManagedArray();this._frameNumber=null;this.root=null;this.selectedTiles={};this.requestedTiles={};this.emptyTiles={};}traverse(root,frameState,options){this.root=root;this.options=_objectSpread2(_objectSpread2({},this.options),options);this.reset();this.updateTile(root,frameState);this._frameNumber=frameState.frameNumber;this.executeTraversal(root,frameState);}reset(){this.requestedTiles={};this.selectedTiles={};this.emptyTiles={};this._traversalStack.reset();this._emptyTraversalStack.reset();}executeTraversal(root,frameState){// 遍历root
  78882. var stack=this._traversalStack;root._selectionDepth=1;stack.push(root);while(stack.length>0){var tile=stack.pop();var shouldRefine=false;// !zeg改 循环遍历子tile, maxDepth用来限制可加载的最大深度
  78883. if(this.canTraverse(tile,frameState)&&(tile.depth</* this.options. */maxDepth||tile.type!='scenegraph')){//add maxDepth 是否继续遍历子集
  78884. this.updateChildTiles(tile,frameState);shouldRefine=this.updateAndPushChildren(tile,frameState,stack,tile.hasRenderContent?tile._selectionDepth+1:tile._selectionDepth);}var parent=tile.parent;var parentRefines=Boolean(!parent||parent._shouldRefine);var stoppedRefining=!shouldRefine;if(!tile.hasRenderContent){this.emptyTiles[tile.id]=tile;this.loadTile(tile,frameState);if(stoppedRefining){this.selectTile(tile,frameState);}}else if(tile.refine===TILE_REFINEMENT.ADD){this.loadTile(tile,frameState);this.selectTile(tile,frameState);}else if(tile.refine===TILE_REFINEMENT.REPLACE){this.loadTile(tile,frameState);if(stoppedRefining){this.selectTile(tile,frameState);}}this.touchTile(tile,frameState);tile._shouldRefine=shouldRefine&&parentRefines;}this.options.onTraversalEnd(frameState);}updateChildTiles(tile,frameState){var children=tile.children;for(var child of children){this.updateTile(child,frameState);}return true;}updateAndPushChildren(tile,frameState,stack,depth){var{loadSiblings,skipLevelOfDetail}=this.options;var children=tile.children;children.sort(this.compareDistanceToCamera.bind(this));var checkRefines=tile.refine===TILE_REFINEMENT.REPLACE&&tile.hasRenderContent&&!skipLevelOfDetail;var hasVisibleChild=false;var refines=true;for(var child of children){child._selectionDepth=depth;if(child.isVisibleAndInRequestVolume){if(stack.find(child)){stack.delete(child);}stack.push(child);hasVisibleChild=true;}else if(checkRefines||loadSiblings){this.loadTile(child,frameState);this.touchTile(child,frameState);}if(checkRefines){var childRefines=void 0;if(!child._inRequestVolume){childRefines=false;}else if(!child.hasRenderContent){childRefines=this.executeEmptyTraversal(child,frameState);}else {childRefines=child.contentAvailable;}refines=refines&&childRefines;if(!refines){return false;}}}if(!hasVisibleChild){refines=false;}return refines;}updateTile(tile,frameState){this.updateTileVisibility(tile,frameState);}selectTile(tile,frameState){if(this.shouldSelectTile(tile)){tile._selectedFrame=frameState.frameNumber;this.selectedTiles[tile.id]=tile;}}loadTile(tile,frameState){if(this.shouldLoadTile(tile)){tile._requestedFrame=frameState.frameNumber;tile._priority=tile._getPriority();this.requestedTiles[tile.id]=tile;}}touchTile(tile,frameState){tile.tileset._cache.touch(tile);tile._touchedFrame=frameState.frameNumber;}canTraverse(tile,frameState){var useParentMetric=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var ignoreVisibility=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;if(!tile.hasChildren){return false;}if(tile.hasTilesetContent){return !tile.contentExpired;}if(!ignoreVisibility&&!tile.isVisibleAndInRequestVolume){return false;}return this.shouldRefine(tile,frameState,useParentMetric);}shouldLoadTile(tile){return tile.hasUnloadedContent||tile.contentExpired;}shouldSelectTile(tile){return tile.contentAvailable&&!this.options.skipLevelOfDetail;}shouldRefine(tile,frameState,useParentMetric){var screenSpaceError=tile._screenSpaceError;if(useParentMetric){screenSpaceError=tile.getScreenSpaceError(frameState,true);}return screenSpaceError>this.options.maximumScreenSpaceError;}updateTileVisibility(tile,frameState){var viewportIds=[];if(this.options.viewportTraversersMap){for(var key in this.options.viewportTraversersMap){var value=this.options.viewportTraversersMap[key];if(value===frameState.viewport.id){viewportIds.push(key);}}}else {viewportIds.push(frameState.viewport.id);}tile.updateVisibility(frameState,viewportIds);}compareDistanceToCamera(b,a){return b._distanceToCamera-a._distanceToCamera;}anyChildrenVisible(tile,frameState){var anyVisible=false;for(var child of tile.children){child.updateVisibility(frameState);anyVisible=anyVisible||child.isVisibleAndInRequestVolume;}return anyVisible;}executeEmptyTraversal(root,frameState){var allDescendantsLoaded=true;var stack=this._emptyTraversalStack;stack.push(root);while(stack.length>0&&allDescendantsLoaded){var tile=stack.pop();this.updateTile(tile,frameState);if(!tile.isVisibleAndInRequestVolume){this.loadTile(tile,frameState);}this.touchTile(tile,frameState);var traverse=!tile.hasRenderContent&&this.canTraverse(tile,frameState,false,true);if(traverse){var children=tile.children;for(var child of children){if(stack.find(child)){stack.delete(child);}stack.push(child);}}else if(!tile.contentAvailable){allDescendantsLoaded=false;}}return allDescendantsLoaded;}}var scratchVector=new Vector3$1();function defined$2(x){return x!==undefined&&x!==null;}class TileHeader{constructor(tileset,header,parentHeader){var extendedId=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'';_defineProperty$1(this,"tileset",void 0);_defineProperty$1(this,"header",void 0);_defineProperty$1(this,"id",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"parent",void 0);_defineProperty$1(this,"refine",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"contentUrl",void 0);_defineProperty$1(this,"lodMetricType",void 0);_defineProperty$1(this,"lodMetricValue",void 0);_defineProperty$1(this,"boundingVolume",void 0);_defineProperty$1(this,"content",void 0);_defineProperty$1(this,"contentState",void 0);_defineProperty$1(this,"gpuMemoryUsageInBytes",void 0);_defineProperty$1(this,"children",void 0);_defineProperty$1(this,"depth",void 0);_defineProperty$1(this,"viewportIds",void 0);_defineProperty$1(this,"transform",void 0);_defineProperty$1(this,"extensions",void 0);_defineProperty$1(this,"userData",void 0);_defineProperty$1(this,"computedTransform",void 0);_defineProperty$1(this,"hasEmptyContent",void 0);_defineProperty$1(this,"hasTilesetContent",void 0);_defineProperty$1(this,"traverser",void 0);_defineProperty$1(this,"_cacheNode",void 0);_defineProperty$1(this,"_frameNumber",void 0);_defineProperty$1(this,"_lodJudge",void 0);_defineProperty$1(this,"_expireDate",void 0);_defineProperty$1(this,"_expiredContent",void 0);_defineProperty$1(this,"_shouldRefine",void 0);_defineProperty$1(this,"_distanceToCamera",void 0);_defineProperty$1(this,"_centerZDepth",void 0);_defineProperty$1(this,"_screenSpaceError",void 0);_defineProperty$1(this,"_visibilityPlaneMask",void 0);_defineProperty$1(this,"_visible",void 0);_defineProperty$1(this,"_inRequestVolume",void 0);_defineProperty$1(this,"_stackLength",void 0);_defineProperty$1(this,"_selectionDepth",void 0);_defineProperty$1(this,"_touchedFrame",void 0);_defineProperty$1(this,"_visitedFrame",void 0);_defineProperty$1(this,"_selectedFrame",void 0);_defineProperty$1(this,"_requestedFrame",void 0);_defineProperty$1(this,"_priority",void 0);_defineProperty$1(this,"_contentBoundingVolume",void 0);_defineProperty$1(this,"_viewerRequestVolume",void 0);_defineProperty$1(this,"_initialTransform",void 0);_defineProperty$1(this,"tilesetMatrix",void 0);//add
  78885. _defineProperty$1(this,"tileContent",void 0);//add
  78886. _defineProperty$1(this,"contentTransform",void 0);//add
  78887. _defineProperty$1(this,"volumeBox",void 0);//add
  78888. _defineProperty$1(this,"boundUntransformed",void 0);//add
  78889. _defineProperty$1(this,"rtcCenterState",rtcCenterGlobal);//add 初始时的状态,当mesh加载完检查下
  78890. this.header=header;this.tileset=tileset;this.id=extendedId||header.id;this.url=header.url;this.parent=parentHeader;this.refine=this._getRefine(header.refine);this.type=header.type;this.contentUrl=header.contentUrl;this.lodMetricType='geometricError';this.lodMetricValue=0;this.boundingVolume=null;this.content=null;this.contentState=TILE_CONTENT_STATE.UNLOADED;this.gpuMemoryUsageInBytes=0;this.children=[];this.hasEmptyContent=false;this.hasTilesetContent=false;this.depth=0;this.viewportIds=[];this.userData={};this.extensions=null;this._priority=0;this._touchedFrame=0;this._visitedFrame=0;this._selectedFrame=0;this._requestedFrame=0;this._screenSpaceError=0;this._cacheNode=null;this._frameNumber=null;this._cacheNode=null;this.traverser=new TilesetTraverser({});this._shouldRefine=false;this._distanceToCamera=0;this._centerZDepth=0;this._visible=undefined;this._inRequestVolume=false;this._stackLength=0;this._selectionDepth=0;this._initialTransform=new Matrix4$1();this.transform=new Matrix4$1();this._initializeLodMetric(header);this._initializeTransforms(header);this._initializeBoundingVolumes(header);this._initializeContent(header);this._initializeRenderingState(header);this._lodJudge=null;this._expireDate=null;this._expiredContent=null;Object.seal(this);}destroy(){this.header=null;}isDestroyed(){return this.header===null;}get selected(){return this._selectedFrame===this.tileset._frameNumber;}get isVisible(){return this._visible;}get isVisibleAndInRequestVolume(){var v=/* this._visible && */this.tileset.visible&&this._inRequestVolume;//用_updateBoundingVolume这个算的在相机靠近时不准确,容易缺块
  78891. if(window.tileVisi2)v=this._visible&&v;return v;}get hasRenderContent(){return !this.hasEmptyContent&&!this.hasTilesetContent;}get hasChildren(){return this.children.length>0||this.header.children&&this.header.children.length>0;}get contentReady(){return this.contentState===TILE_CONTENT_STATE.READY||this.hasEmptyContent;}get contentAvailable(){return Boolean(this.contentReady&&this.hasRenderContent||this._expiredContent&&!this.contentFailed);}get hasUnloadedContent(){return this.hasRenderContent&&this.contentUnloaded;}get contentUnloaded(){return this.contentState===TILE_CONTENT_STATE.UNLOADED;}get contentExpired(){return this.contentState===TILE_CONTENT_STATE.EXPIRED;}get contentFailed(){return this.contentState===TILE_CONTENT_STATE.FAILED;}getScreenSpaceError(frameState,useParentLodMetric){switch(this.tileset.type){case TILESET_TYPE.I3S:return getProjectedRadius(this,frameState);case TILESET_TYPE.TILES3D:return getTiles3DScreenSpaceError(this,frameState,useParentLodMetric);default:throw new Error('Unsupported tileset type');}}_getPriority(){var traverser=this.tileset._traverser;var{skipLevelOfDetail}=traverser.options;var maySkipTile=this.refine===TILE_REFINEMENT.ADD||skipLevelOfDetail;if(maySkipTile&&!this.isVisible&&this._visible!==undefined){return -1;}if(this.tileset._frameNumber-this._touchedFrame>=1){return -1;}if(this.contentState===TILE_CONTENT_STATE.UNLOADED){return -1;}var parent=this.parent;var useParentScreenSpaceError=parent&&(!maySkipTile||this._screenSpaceError===0.0||parent.hasTilesetContent);var screenSpaceError=useParentScreenSpaceError?parent._screenSpaceError:this._screenSpaceError;var rootScreenSpaceError=traverser.root?traverser.root._screenSpaceError:0.0;var v=Math.max(rootScreenSpaceError-screenSpaceError,0);if(!this._visible){v=THREE.Math.clamp(v*0.1,-0.9,100);//xzw add 因为this._visible我也令其显示所以这里降低这些的优先级
  78892. }return v;}loadContent(){var _this3=this;return _asyncToGenerator(function*(){if(_this3.hasEmptyContent){return false;}if(_this3.content){return true;}var expired=_this3.contentExpired;if(expired){_this3._expireDate=null;}_this3.contentState=TILE_CONTENT_STATE.LOADING;var requestToken=yield _this3.tileset._requestScheduler.scheduleRequest(_this3.id,_this3._getPriority.bind(_this3));if(!requestToken){_this3.contentState=TILE_CONTENT_STATE.UNLOADED;return false;}try{var contentUrl=_this3.tileset.getTileUrl(_this3.contentUrl)+"?_=".concat(_this3.tileset.options.updateTime);// !zeg改 添加version后缀 原:imageVersion
  78893. var loader=_this3.tileset.loader;var options=_objectSpread2(_objectSpread2({},_this3.tileset.loadOptions),{},{[loader.id]:_objectSpread2(_objectSpread2({},_this3.tileset.loadOptions[loader.id]),{},{isTileset:_this3.type==='json'},_this3._getLoaderSpecificOptions(loader.id))});_this3.content=yield load(contentUrl,loader,options);// !zeg改
  78894. if(/* this.tileset.options. */maxDepth<_this3.depth&&_this3.type=='scenegraph'){//有的场景depth为1的不是mesh,只是json,即实际最低depth>1
  78895. _this3.unloadContent();return false;}if(_this3.tileset.options.contentLoader){yield _this3.tileset.options.contentLoader(_this3);}if(_this3._isTileset()){_this3.tileset._initializeTileHeaders(_this3.content,_this3);}_this3.contentState=TILE_CONTENT_STATE.READY;_this3._onContentLoaded();return true;}catch(error){_this3.contentState=TILE_CONTENT_STATE.FAILED;throw error;}finally{requestToken.done();}})();}unloadContent(){if(this.content&&this.content.destroy){this.content.destroy();}this.content=null;if(this.header.content&&this.header.content.destroy){this.header.content.destroy();}this.header.content=null;this.contentState=TILE_CONTENT_STATE.UNLOADED;return true;}updateVisibility(frameState,viewportIds){if(this._frameNumber===frameState.frameNumber){return;}var parent=this.parent;var parentVisibilityPlaneMask=parent?parent._visibilityPlaneMask:CullingVolume.MASK_INDETERMINATE;if(this.tileset._traverser.options.updateTransforms){var parentTransform=parent?parent.computedTransform:new Matrix4$1().elements;//this.tileset.modelMatrix; 改:去掉左乘modelMatrix
  78896. this._updateTransform(parentTransform);}this._distanceToCamera=this.distanceToTile(frameState);this._screenSpaceError=this.getScreenSpaceError(frameState,false);this._visibilityPlaneMask=this.visibility(frameState,parentVisibilityPlaneMask);this._visible=this._visibilityPlaneMask!==CullingVolume.MASK_OUTSIDE;this._inRequestVolume=this.insideViewerRequestVolume(frameState);this._frameNumber=frameState.frameNumber;this.viewportIds=viewportIds;}visibility(frameState,parentVisibilityPlaneMask){var{cullingVolume}=frameState;var{boundingVolume}=this;return cullingVolume.computeVisibilityWithPlaneMask(boundingVolume,parentVisibilityPlaneMask);}contentVisibility(){return true;}distanceToTile(frameState){var boundingVolume=this.boundingVolume;return Math.sqrt(Math.max(boundingVolume.distanceSquaredTo(frameState.camera.position),0));}cameraSpaceZDepth(_ref11){var{camera}=_ref11;var boundingVolume=this.boundingVolume;scratchVector.subVectors(boundingVolume.center,camera.position);return camera.direction.dot(scratchVector);}insideViewerRequestVolume(frameState){var viewerRequestVolume=this._viewerRequestVolume;return !viewerRequestVolume||viewerRequestVolume.distanceSquaredTo(frameState.camera.position)<=0;}updateExpiration(){if(defined$2(this._expireDate)&&this.contentReady&&!this.hasEmptyContent){var now=Date.now();if(Date.lessThan(this._expireDate,now)){this.contentState=TILE_CONTENT_STATE.EXPIRED;this._expiredContent=this.content;}}}get extras(){return this.header.extras;}_initializeLodMetric(header){if('lodMetricType'in header){this.lodMetricType=header.lodMetricType;}else {this.lodMetricType=this.parent&&this.parent.lodMetricType||this.tileset.lodMetricType;console.warn("3D Tile: Required prop lodMetricType is undefined. Using parent lodMetricType");}if('lodMetricValue'in header){this.lodMetricValue=header.lodMetricValue;}else {this.lodMetricValue=this.parent&&this.parent.lodMetricValue||this.tileset.lodMetricValue;console.warn('3D Tile: Required prop lodMetricValue is undefined. Using parent lodMetricValue');}}_initializeTransforms(tileHeader){this.transform=tileHeader.transform?new Matrix4$1(tileHeader.transform):new Matrix4$1();var parent=this.parent;var tileset=this.tileset;var parentTransform=parent&&parent.computedTransform?parent.computedTransform.clone():new Matrix4$1().elements;// tileset.modelMatrix.clone(); 改:去掉左乘modelMatrix
  78897. this.computedTransform=new Matrix4$1(parentTransform).multiplyRight(this.transform);var parentInitialTransform=parent&&parent._initialTransform?parent._initialTransform.clone():new Matrix4$1();this._initialTransform=new Matrix4$1(parentInitialTransform).multiplyRight(this.transform);}_initializeBoundingVolumes(tileHeader){this._contentBoundingVolume=null;this._viewerRequestVolume=null;this._updateBoundingVolume(tileHeader);}_initializeContent(tileHeader){this.content={_tileset:this.tileset,_tile:this};this.hasEmptyContent=true;this.contentState=TILE_CONTENT_STATE.UNLOADED;this.hasTilesetContent=false;if(tileHeader.contentUrl){this.content=null;this.hasEmptyContent=false;}}_initializeRenderingState(header){this.depth=header.level||(this.parent?this.parent.depth+1:0);this._shouldRefine=false;this._distanceToCamera=0;this._centerZDepth=0;this._screenSpaceError=0;this._visibilityPlaneMask=CullingVolume.MASK_INDETERMINATE;this._visible=undefined;this._inRequestVolume=false;this._stackLength=0;this._selectionDepth=0;this._frameNumber=0;this._touchedFrame=0;this._visitedFrame=0;this._selectedFrame=0;this._requestedFrame=0;this._priority=0.0;}_getRefine(refine){return refine||this.parent&&this.parent.refine||TILE_REFINEMENT.REPLACE;}_isTileset(){return this.contentUrl.indexOf('.json')!==-1;}_onContentLoaded(){switch(this.content&&this.content.type){case'vctr':case'geom':this.tileset._traverser.disableSkipLevelOfDetail=true;break;}if(this._isTileset()){this.hasTilesetContent=true;}}_updateBoundingVolume(header){var computedTransform;if(header.id=='root_0'||!header.id){console.log('root_0');}if(!this.tileset.lastRootTransform){//没事过后会因_updateTransform重算
  78898. computedTransform=new Matrix4$1(this.tileset.modelMatrix).multiplyRight(this.computedTransform);//add
  78899. }else {computedTransform=new Matrix4$1(new Matrix4().multiplyMatrices(this.tileset.lastRootTransform,this.getContentTransform()).elements);}this.boundingVolume=createBoundingVolume(header.boundingVolume,computedTransform/* this.computedTransform */,this.boundingVolume);var content=header.content;if(!content){return;}if(content.boundingVolume){this._contentBoundingVolume=createBoundingVolume(content.boundingVolume,computedTransform,this._contentBoundingVolume);}if(header.viewerRequestVolume){this._viewerRequestVolume=createBoundingVolume(header.viewerRequestVolume,computedTransform,this._viewerRequestVolume);}}getBoundUntransformed(){//add 这个会在mesh加载好后才会执行
  78900. if(!this.contentTransform){console.error('?');}this.getContentTransform();var computedTransform2=new Matrix4$1(this.contentTransform.elements);this.boundUntransformed=createBoundingVolume(this.header.boundingVolume,computedTransform2,this.boundUntransformed);//add
  78901. return this.boundUntransformed;}getContentTransform(force){//add 获取该tile在创建boundingVolume时需要的matrix,不包含最外层对整体模型的变换.
  78902. var rtcCenter,contentTransform;if(this.contentTransform&&!force){//无需更新
  78903. return this.contentTransform.clone();}if(!this.tileset.tileTransInvert){this.tileset.tileTransInvert=new Matrix4$1();}this.contentTransform=new Matrix4().fromArray(this.computedTransform).premultiply(new Matrix4().fromArray(this.tileset.tileTransInvert));if(this.tileContent){rtcCenter=this.content.rtcCenter;}else {rtcCenter=this.rtcCenterState;}if(!rtcCenter){var tranM=new Matrix4();tranM.makeScale(1,1,-1);//大部分是这种情况. 就是因为这个变换才加的这个函数,之前bounding没考虑这个不准。不知道为什么原生的代码不用scaleZ
  78904. this.contentTransform.premultiply(tranM);}//如果有rtcCenter的话一开始boundingVolume不准?会不会有显示问题?
  78905. return this.contentTransform.clone();}_updateTransform(){var parentTransform=arguments.length>0&&arguments[0]!==undefined?arguments[0]:new Matrix4$1();var computedTransform=parentTransform.clone().multiplyRight(this.transform);var didTransformChange=!computedTransform.equals(this.computedTransform)||!this.tilesetMatrix||!this.tilesetMatrix.equals(this.tileset.modelMatrix);//改 后面加了两个判断,为了在模型移动后更新_updateBoundingVolume
  78906. if(!didTransformChange){return;}this.tileset.modelMatrix;this.computedTransform=computedTransform;this.tilesetMatrix=this.tileset.modelMatrix;//add 标记
  78907. this._updateBoundingVolume(this.header);}_getLoaderSpecificOptions(loaderId){switch(loaderId){case'i3s':return _objectSpread2(_objectSpread2({},this.tileset.options.i3s),{},{tile:this.header,tileset:this.tileset.tileset,isTileHeader:false});case'3d-tiles':case'cesium-ion':default:return get3dTilesOptions(this.tileset.tileset);}}}class Tileset3DTraverser extends TilesetTraverser{compareDistanceToCamera(a,b){return b._distanceToCamera===0&&a._distanceToCamera===0?b._centerZDepth-a._centerZDepth:b._distanceToCamera-a._distanceToCamera;}updateTileVisibility(tile,frameState){super.updateTileVisibility(tile,frameState);if(!tile.isVisibleAndInRequestVolume){return;}var hasChildren=tile.children.length>0;if(tile.hasTilesetContent&&hasChildren){var firstChild=tile.children[0];this.updateTileVisibility(firstChild,frameState);tile._visible=firstChild._visible;return;}if(this.meetsScreenSpaceErrorEarly(tile,frameState)){tile._visible=false;return;}var replace=tile.refine===TILE_REFINEMENT.REPLACE;var useOptimization=tile._optimChildrenWithinParent===TILE3D_OPTIMIZATION_HINT.USE_OPTIMIZATION;if(replace&&useOptimization&&hasChildren){if(!this.anyChildrenVisible(tile,frameState)){tile._visible=false;return;}}}meetsScreenSpaceErrorEarly(tile,frameState){var{parent}=tile;if(!parent||parent.hasTilesetContent||parent.refine!==TILE_REFINEMENT.ADD){return false;}return !this.shouldRefine(tile,frameState,true);}}var STATUS={REQUESTED:'REQUESTED',COMPLETED:'COMPLETED',ERROR:'ERROR'};class I3STileManager{constructor(){_defineProperty$1(this,"_statusMap",void 0);this._statusMap={};}add(request,key,callback,frameState){if(!this._statusMap[key]){this._statusMap[key]={request,callback,key,frameState,status:STATUS.REQUESTED};request().then(data=>{this._statusMap[key].status=STATUS.COMPLETED;this._statusMap[key].callback(data,frameState);}).catch(error=>{this._statusMap[key].status=STATUS.ERROR;callback(error);});}}update(key,frameState){if(this._statusMap[key]){this._statusMap[key].frameState=frameState;}}find(key){return this._statusMap[key];}}class I3STilesetTraverser extends TilesetTraverser{constructor(options){super(options);_defineProperty$1(this,"_tileManager",void 0);this._tileManager=new I3STileManager();}shouldRefine(tile,frameState){tile._lodJudge=getLodStatus(tile,frameState);return tile._lodJudge==='DIG';}updateChildTiles(tile,frameState){var _this4=this;var children=tile.header.children||[];var childTiles=tile.children;var tileset=tile.tileset;var _loop2=function _loop2(child){var extendedId="".concat(child.id,"-").concat(frameState.viewport.id);var childTile=childTiles&&childTiles.find(t=>t.id===extendedId);if(!childTile){var request=()=>_this4._loadTile(child.id,tileset);var cachedRequest=_this4._tileManager.find(extendedId);if(!cachedRequest){if(tileset.tileset.nodePages){request=()=>tileset.tileset.nodePagesTile.formTileFromNodePages(child.id);}_this4._tileManager.add(request,extendedId,header=>_this4._onTileLoad(header,tile,extendedId),frameState);}else {_this4._tileManager.update(extendedId,frameState);}}else if(childTile){_this4.updateTile(childTile,frameState);}};for(var child of children){_loop2(child);}return false;}_loadTile(nodeId,tileset){return _asyncToGenerator(function*(){var{loader}=tileset;var nodeUrl=tileset.getTileUrl("".concat(tileset.url,"/nodes/").concat(nodeId));var options=_objectSpread2(_objectSpread2({},tileset.loadOptions),{},{i3s:_objectSpread2(_objectSpread2({},tileset.loadOptions.i3s),{},{isTileHeader:true,loadContent:false})});return yield load(nodeUrl,loader,options);})();}_onTileLoad(header,tile,extendedId){var childTile=new TileHeader(tile.tileset,header,tile,extendedId);tile.children.push(childTile);var frameState=this._tileManager.find(childTile.id).frameState;this.updateTile(childTile,frameState);if(this._frameNumber===frameState.frameNumber){this.executeTraversal(childTile,frameState);}}}var DEFAULT_PROPS={description:'',ellipsoid:Ellipsoid.WGS84,modelMatrix:new Matrix4$1(),throttleRequests:true,maxRequests:64,maximumMemoryUsage:32,onTileLoad:()=>{},onTileUnload:()=>{},onTileError:()=>{},onTraversalComplete:selectedTiles=>selectedTiles,contentLoader:undefined,viewDistanceScale:1.0,maximumScreenSpaceError:8,loadTiles:true,updateTransforms:true,viewportTraversersMap:null,loadOptions:{fetch:{}},attributions:[],basePath:'',i3s:{}};var TILES_TOTAL='Tiles In Tileset(s)';var TILES_IN_MEMORY='Tiles In Memory';var TILES_IN_VIEW='Tiles In View';var TILES_RENDERABLE='Tiles To Render';var TILES_LOADED='Tiles Loaded';var TILES_LOADING='Tiles Loading';var TILES_UNLOADED='Tiles Unloaded';var TILES_LOAD_FAILED='Failed Tile Loads';var POINTS_COUNT='Points';var TILES_GPU_MEMORY='Tile Memory Use';var tilesetSid=0;//add
  78908. class Tileset3D extends EventDispatcher{//xzw add EventDispatcher
  78909. constructor(json,options){super();viewer.visiVertexCount=viewer.visiVertexCount||0;_defineProperty$1(this,"options",void 0);_defineProperty$1(this,"loadOptions",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"tileset",void 0);_defineProperty$1(this,"loader",void 0);_defineProperty$1(this,"url",void 0);_defineProperty$1(this,"basePath",void 0);_defineProperty$1(this,"modelMatrix",void 0);_defineProperty$1(this,"ellipsoid",void 0);_defineProperty$1(this,"lodMetricType",void 0);_defineProperty$1(this,"lodMetricValue",void 0);_defineProperty$1(this,"refine",void 0);_defineProperty$1(this,"root",void 0);_defineProperty$1(this,"roots",void 0);_defineProperty$1(this,"asset",void 0);_defineProperty$1(this,"description",void 0);_defineProperty$1(this,"properties",void 0);_defineProperty$1(this,"extras",void 0);_defineProperty$1(this,"attributions",void 0);_defineProperty$1(this,"credits",void 0);_defineProperty$1(this,"stats",void 0);_defineProperty$1(this,"traverseCounter",void 0);_defineProperty$1(this,"geometricError",void 0);_defineProperty$1(this,"selectedTiles",void 0);_defineProperty$1(this,"cartographicCenter",void 0);_defineProperty$1(this,"cartesianCenter",void 0);_defineProperty$1(this,"zoom",void 0);_defineProperty$1(this,"boundingVolume",void 0);_defineProperty$1(this,"gpuMemoryUsageInBytes",void 0);_defineProperty$1(this,"dynamicScreenSpaceErrorComputedDensity",void 0);_defineProperty$1(this,"_traverser",void 0);_defineProperty$1(this,"_cache",void 0);_defineProperty$1(this,"_requestScheduler",void 0);_defineProperty$1(this,"_frameNumber",void 0);_defineProperty$1(this,"_queryParamsString",void 0);_defineProperty$1(this,"_queryParams",void 0);_defineProperty$1(this,"_extensionsUsed",void 0);_defineProperty$1(this,"_tiles",void 0);_defineProperty$1(this,"_pendingCount",void 0);_defineProperty$1(this,"lastUpdatedVieports",void 0);_defineProperty$1(this,"_requestedTiles",void 0);_defineProperty$1(this,"_emptyTiles",void 0);_defineProperty$1(this,"frameStateData",void 0);_defineProperty$1(this,"maximumMemoryUsage",void 0);_defineProperty$1(this,"visible",true);//add
  78910. assert$7(json);this.options=_objectSpread2(_objectSpread2({},DEFAULT_PROPS),options);this.tileset=json;this.loader=json.loader;this.type=json.type;this.url=json.url;this.basePath=json.basePath||dirname(this.url);this.modelMatrix=this.options.modelMatrix;this.ellipsoid=this.options.ellipsoid;this.lodMetricType=json.lodMetricType;this.lodMetricValue=json.lodMetricValue;this.refine=json.root.refine;this.loadOptions=this.options.loadOptions||{};this.root=null;this.roots={};this.cartographicCenter=null;this.cartesianCenter=null;this.zoom=1;this.boundingVolume=null;this.traverseCounter=0;this.geometricError=0;this._traverser=this._initializeTraverser();this._cache=new TilesetCache();this._requestScheduler=new RequestScheduler({throttleRequests:this.options.throttleRequests,maxRequests:this.options.maxRequests});this._frameNumber=0;this._pendingCount=0;this._tiles={};this.selectedTiles=[];this._emptyTiles=[];this._requestedTiles=[];this.frameStateData={};this.lastUpdatedVieports=null;this._queryParams={};this._queryParamsString='';this.maximumMemoryUsage=this.options.maximumMemoryUsage||32;this.gpuMemoryUsageInBytes=0;this.stats=new Stats$1({id:this.url});this._initializeStats();this._extensionsUsed=undefined;this.dynamicScreenSpaceErrorComputedDensity=0.0;this.extras=null;this.asset={};this.credits={};this.description=this.options.description||'';this._initializeTileSet(json);}destroy(){this._destroy();}isLoaded(){return this._pendingCount===0&&this._frameNumber!==0;}get tiles(){return Object.values(this._tiles);}get frameNumber(){return this._frameNumber;}get queryParams(){if(!this._queryParamsString){this._queryParamsString=getQueryParamString(this._queryParams);}return this._queryParamsString;}setProps(props){this.options=_objectSpread2(_objectSpread2({},this.options),props);}setOptions(options){this.options=_objectSpread2(_objectSpread2({},this.options),options);}getTileUrl(tilePath){var isDataUrl=tilePath.startsWith('data:');tilePath=Potree.Common.dealURL(tilePath);//add 去除'+'
  78911. if(isDataUrl){return tilePath;}return "".concat(tilePath).concat(this.queryParams);}hasExtension(extensionName){return Boolean(this._extensionsUsed&&this._extensionsUsed.indexOf(extensionName)>-1);}update(viewports){if('loadTiles'in this.options&&!this.options.loadTiles){return;}if(this.traverseCounter>0){return;}if(!viewports&&this.lastUpdatedVieports){viewports=this.lastUpdatedVieports;}else {this.lastUpdatedVieports=viewports;}if(!(viewports instanceof Array)){viewports=[viewports];}this._cache.reset();this._frameNumber++;this.traverseCounter=viewports.length;var viewportsToTraverse=[];for(var viewport of viewports){var id=viewport.id;if(this._needTraverse(id)){viewportsToTraverse.push(id);}else {this.traverseCounter--;}}for(var _viewport of viewports){var _id=_viewport.id;if(!this.roots[_id]){this.roots[_id]=this._initializeTileHeaders(this.tileset,null);}if(!viewportsToTraverse.includes(_id)){continue;}var frameState=getFrameState(_viewport,this._frameNumber);this._traverser.traverse(this.roots[_id],frameState,this.options);}}_needTraverse(viewportId){var traverserId=viewportId;if(this.options.viewportTraversersMap){traverserId=this.options.viewportTraversersMap[viewportId];}if(traverserId!==viewportId){return false;}return true;}_onTraversalEnd(frameState){var id=frameState.viewport.id;if(!this.frameStateData[id]){this.frameStateData[id]={selectedTiles:[],_requestedTiles:[],_emptyTiles:[]};}var currentFrameStateData=this.frameStateData[id];var selectedTiles=Object.values(this._traverser.selectedTiles);currentFrameStateData.selectedTiles=selectedTiles;currentFrameStateData._requestedTiles=Object.values(this._traverser.requestedTiles);currentFrameStateData._emptyTiles=Object.values(this._traverser.emptyTiles);this.traverseCounter--;if(this.traverseCounter>0){return;}this._updateTiles();}_updateTiles(){this.selectedTiles=[];this._requestedTiles=[];this._emptyTiles=[];for(var frameStateKey in this.frameStateData){var frameStateDataValue=this.frameStateData[frameStateKey];this.selectedTiles=this.selectedTiles.concat(frameStateDataValue.selectedTiles);this._requestedTiles=this._requestedTiles.concat(frameStateDataValue._requestedTiles);this._emptyTiles=this._emptyTiles.concat(frameStateDataValue._emptyTiles);}this.selectedTiles=this.options.onTraversalComplete(this.selectedTiles);for(var tile of this.selectedTiles){this._tiles[tile.id]=tile;}this._loadTiles();this._unloadTiles();this._updateStats();}_tilesChanged(oldSelectedTiles,selectedTiles){if(oldSelectedTiles.length!==selectedTiles.length){return true;}var set1=new Set(oldSelectedTiles.map(t=>t.id));var set2=new Set(selectedTiles.map(t=>t.id));var changed=oldSelectedTiles.filter(x=>!set2.has(x.id)).length>0;changed=changed||selectedTiles.filter(x=>!set1.has(x.id)).length>0;return changed;}_loadTiles(){for(var tile of this._requestedTiles){if(tile.contentUnloaded){this._loadTile(tile);}}}_unloadTiles(){this._cache.unloadTiles(this,(tileset,tile)=>tileset._unloadTile(tile));}_updateStats(){var tilesRenderable=0;var pointsRenderable=0;for(var tile of this.selectedTiles){if(tile.contentAvailable&&tile.content){tilesRenderable++;if(tile.content.pointCount){pointsRenderable+=tile.content.pointCount;}}}this.stats.get(TILES_IN_VIEW).count=this.selectedTiles.length;this.stats.get(TILES_RENDERABLE).count=tilesRenderable;this.stats.get(POINTS_COUNT).count=pointsRenderable;}_initializeTileSet(tilesetJson){this.root=this._initializeTileHeaders(tilesetJson,null);if(this.type===TILESET_TYPE.TILES3D){this._initializeCesiumTileset(tilesetJson);}if(this.type===TILESET_TYPE.I3S){this._initializeI3STileset();}this._calculateViewProps();}_calculateViewProps(){var root=this.root;assert$7(root);var{center}=root.boundingVolume;if(!center){console.warn('center was not pre-calculated for the root tile');this.cartographicCenter=new Vector3$1();this.zoom=1;return;}this.cartographicCenter=Ellipsoid.WGS84.cartesianToCartographic(center,new Vector3$1());this.cartesianCenter=center;this.zoom=getZoomFromBoundingVolume(root.boundingVolume);}_initializeStats(){this.stats.get(TILES_TOTAL);this.stats.get(TILES_LOADING);this.stats.get(TILES_IN_MEMORY);this.stats.get(TILES_IN_VIEW);this.stats.get(TILES_RENDERABLE);this.stats.get(TILES_LOADED);this.stats.get(TILES_UNLOADED);this.stats.get(TILES_LOAD_FAILED);this.stats.get(POINTS_COUNT,'memory');this.stats.get(TILES_GPU_MEMORY,'memory');}_initializeTileHeaders(tilesetJson,parentTileHeader){var rootTile=new TileHeader(this,tilesetJson.root,parentTileHeader,parentTileHeader==void 0&&'root_'+tilesetSid++);if(parentTileHeader){parentTileHeader.children.push(rootTile);rootTile.depth=parentTileHeader.depth+1;}if(this.type===TILESET_TYPE.TILES3D){var _stack=[];_stack.push(rootTile);while(_stack.length>0){var tile=_stack.pop();this.stats.get(TILES_TOTAL).incrementCount();var children=tile.header.children||[];// !zeg改
  78912. if(tile.depth</* this.options. */maxDepth){for(var childHeader of children){var childTile=new TileHeader(this,childHeader,tile);tile.children.push(childTile);childTile.depth=tile.depth+1;_stack.push(childTile);}}window.maxTileDepth=Math.max(window.maxTileDepth||0,tile.depth);}}return rootTile;}_initializeTraverser(){var TraverserClass;var type=this.type;switch(type){case TILESET_TYPE.TILES3D:TraverserClass=Tileset3DTraverser;break;case TILESET_TYPE.I3S:TraverserClass=I3STilesetTraverser;break;default:TraverserClass=TilesetTraverser;}return new TraverserClass({basePath:this.basePath,onTraversalEnd:this._onTraversalEnd.bind(this)});}_destroyTileHeaders(parentTile){this._destroySubtree(parentTile);}_loadTile(tile){var _this5=this;return _asyncToGenerator(function*(){var loaded;try{_this5._onStartTileLoading();loaded=yield tile.loadContent();}catch(error){_this5._onTileLoadError(tile,error);}finally{_this5._onEndTileLoading(tile);//
  78913. _this5._onTileLoad(tile,loaded);}})();}_onTileLoadError(tile,error){this.stats.get(TILES_LOAD_FAILED).incrementCount();var message=error.message||error.toString();var url=tile.url;console.error("A 3D tile failed to load: ".concat(tile.url," ").concat(message));this.options.onTileError(tile,message,url);}_onTileLoad(tile,loaded){if(!loaded){return;}if(tile&&tile.content){calculateTransformProps(tile,tile.content);}this._addTileToCache(tile);this.options.onTileLoad(tile);}_onStartTileLoading(){this._pendingCount++;this.stats.get(TILES_LOADING).incrementCount();}_onEndTileLoading(tile){this._pendingCount--;this.stats.get(TILES_LOADING).decrementCount();this.dispatchEvent({type:'endTileLoading',tile,loadingCount:this._pendingCount});// !zeg改
  78914. }_addTileToCache(tile){this._cache.add(this,tile,tileset=>tileset._updateCacheStats(tile));}_updateCacheStats(tile){this.stats.get(TILES_LOADED).incrementCount();this.stats.get(TILES_IN_MEMORY).incrementCount();this.gpuMemoryUsageInBytes+=tile.content.byteLength||0;this.stats.get(TILES_GPU_MEMORY).count=this.gpuMemoryUsageInBytes;}_unloadTile(tile){this.gpuMemoryUsageInBytes-=tile.content&&tile.content.byteLength||0;this.stats.get(TILES_IN_MEMORY).decrementCount();this.stats.get(TILES_UNLOADED).incrementCount();this.stats.get(TILES_GPU_MEMORY).count=this.gpuMemoryUsageInBytes;this.options.onTileUnload(tile);tile.unloadContent();}_destroy(){var stack=[];if(this.root){stack.push(this.root);}while(stack.length>0){var tile=stack.pop();for(var child of tile.children){stack.push(child);}this._destroyTile(tile);}this.root=null;}_destroySubtree(tile){var root=tile;var stack=[];stack.push(root);while(stack.length>0){tile=stack.pop();for(var child of tile.children){stack.push(child);}if(tile!==root){this._destroyTile(tile);}}root.children=[];}_destroyTile(tile){this._cache.unloadTile(this,tile);this._unloadTile(tile);tile.destroy();}_initializeCesiumTileset(tilesetJson){this.asset=tilesetJson.asset;if(!this.asset){throw new Error('Tileset must have an asset property.');}if(this.asset.version!=='0.0'&&this.asset.version!=='1.0'){throw new Error('The tileset must be 3D Tiles version 0.0 or 1.0.');}if('tilesetVersion'in this.asset){this._queryParams.v=this.asset.tilesetVersion;}this.credits={attributions:this.options.attributions||[]};this.description=this.options.description||'';this.properties=tilesetJson.properties;this.geometricError=tilesetJson.geometricError;this._extensionsUsed=tilesetJson.extensionsUsed;this.extras=tilesetJson.extras;}_initializeI3STileset(){if(this.loadOptions.i3s&&'token'in this.loadOptions.i3s){this._queryParams.token=this.loadOptions.i3s.token;}}}function getQueryParamString(queryParams){var queryParamStrings=[];for(var key of Object.keys(queryParams)){queryParamStrings.push("".concat(key,"=").concat(queryParams[key]));}switch(queryParamStrings.length){case 0:return '';case 1:return "?".concat(queryParamStrings[0]);default:return "?".concat(queryParamStrings.join('&'));}}var VERSION$5="3.1.4";var TILE3D_TYPE={COMPOSITE:'cmpt',POINT_CLOUD:'pnts',BATCHED_3D_MODEL:'b3dm',INSTANCED_3D_MODEL:'i3dm',GEOMETRY:'geom',VECTOR:'vect',GLTF:'glTF'};function getStringFromArrayBuffer(arrayBuffer,byteOffset,byteLength){assert$7(arrayBuffer instanceof ArrayBuffer);var textDecoder=new TextDecoder('utf8');var typedArray=new Uint8Array(arrayBuffer,byteOffset,byteLength);var string=textDecoder.decode(typedArray);return string;}function getMagicString$1(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var dataView=new DataView(arrayBuffer);return "".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}var VERSION$4="3.1.4";var DEFAULT_DRACO_OPTIONS={draco:{decoderType:typeof WebAssembly==='object'?'wasm':'js',libraryPath:'libs/',extraAttributes:{},attributeNameEntry:undefined}};var DracoLoader$1={name:'Draco',id:'draco',module:'draco',shapes:['mesh'],version:VERSION$4,worker:true,extensions:['drc'],mimeTypes:['application/octet-stream'],binary:true,tests:['DRACO'],options:DEFAULT_DRACO_OPTIONS};function getMeshBoundingBox(attributes){var minX=Infinity;var minY=Infinity;var minZ=Infinity;var maxX=-Infinity;var maxY=-Infinity;var maxZ=-Infinity;var positions=attributes.POSITION?attributes.POSITION.value:[];var len=positions&&positions.length;for(var _i37=0;_i37<len;_i37+=3){var x=positions[_i37];var y=positions[_i37+1];var z=positions[_i37+2];minX=x<minX?x:minX;minY=y<minY?y:minY;minZ=z<minZ?z:minZ;maxX=x>maxX?x:maxX;maxY=y>maxY?y:maxY;maxZ=z>maxZ?z:maxZ;}return [[minX,minY,minZ],[maxX,maxY,maxZ]];}function assert$3(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}class Schema{constructor(fields,metadata){_defineProperty$1(this,"fields",void 0);_defineProperty$1(this,"metadata",void 0);assert$3(Array.isArray(fields));checkNames(fields);this.fields=fields;this.metadata=metadata||new Map();}compareTo(other){if(this.metadata!==other.metadata){return false;}if(this.fields.length!==other.fields.length){return false;}for(var _i38=0;_i38<this.fields.length;++_i38){if(!this.fields[_i38].compareTo(other.fields[_i38])){return false;}}return true;}select(){var nameMap=Object.create(null);for(var _len11=arguments.length,columnNames=new Array(_len11),_key11=0;_key11<_len11;_key11++){columnNames[_key11]=arguments[_key11];}for(var _name2 of columnNames){nameMap[_name2]=true;}var selectedFields=this.fields.filter(field=>nameMap[field.name]);return new Schema(selectedFields,this.metadata);}selectAt(){for(var _len12=arguments.length,columnIndices=new Array(_len12),_key12=0;_key12<_len12;_key12++){columnIndices[_key12]=arguments[_key12];}var selectedFields=columnIndices.map(index=>this.fields[index]).filter(Boolean);return new Schema(selectedFields,this.metadata);}assign(schemaOrFields){var fields;var metadata=this.metadata;if(schemaOrFields instanceof Schema){var otherSchema=schemaOrFields;fields=otherSchema.fields;metadata=mergeMaps(mergeMaps(new Map(),this.metadata),otherSchema.metadata);}else {fields=schemaOrFields;}var fieldMap=Object.create(null);for(var field of this.fields){fieldMap[field.name]=field;}for(var _field of fields){fieldMap[_field.name]=_field;}var mergedFields=Object.values(fieldMap);return new Schema(mergedFields,metadata);}}function checkNames(fields){var usedNames={};for(var field of fields){if(usedNames[field.name]){console.warn('Schema: duplicated field name',field.name,field);}usedNames[field.name]=true;}}function mergeMaps(m1,m2){return new Map([...(m1||new Map()),...(m2||new Map())]);}class Field{constructor(name,type){var nullable=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var metadata=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Map();_defineProperty$1(this,"name",void 0);_defineProperty$1(this,"type",void 0);_defineProperty$1(this,"nullable",void 0);_defineProperty$1(this,"metadata",void 0);this.name=name;this.type=type;this.nullable=nullable;this.metadata=metadata;}get typeId(){return this.type&&this.type.typeId;}clone(){return new Field(this.name,this.type,this.nullable,this.metadata);}compareTo(other){return this.name===other.name&&this.type===other.type&&this.nullable===other.nullable&&this.metadata===other.metadata;}toString(){return "".concat(this.type).concat(this.nullable?', nullable':'').concat(this.metadata?", metadata: ".concat(this.metadata):'');}}var Type$1;(function(Type){Type[Type["NONE"]=0]="NONE";Type[Type["Null"]=1]="Null";Type[Type["Int"]=2]="Int";Type[Type["Float"]=3]="Float";Type[Type["Binary"]=4]="Binary";Type[Type["Utf8"]=5]="Utf8";Type[Type["Bool"]=6]="Bool";Type[Type["Decimal"]=7]="Decimal";Type[Type["Date"]=8]="Date";Type[Type["Time"]=9]="Time";Type[Type["Timestamp"]=10]="Timestamp";Type[Type["Interval"]=11]="Interval";Type[Type["List"]=12]="List";Type[Type["Struct"]=13]="Struct";Type[Type["Union"]=14]="Union";Type[Type["FixedSizeBinary"]=15]="FixedSizeBinary";Type[Type["FixedSizeList"]=16]="FixedSizeList";Type[Type["Map"]=17]="Map";Type[Type["Dictionary"]=-1]="Dictionary";Type[Type["Int8"]=-2]="Int8";Type[Type["Int16"]=-3]="Int16";Type[Type["Int32"]=-4]="Int32";Type[Type["Int64"]=-5]="Int64";Type[Type["Uint8"]=-6]="Uint8";Type[Type["Uint16"]=-7]="Uint16";Type[Type["Uint32"]=-8]="Uint32";Type[Type["Uint64"]=-9]="Uint64";Type[Type["Float16"]=-10]="Float16";Type[Type["Float32"]=-11]="Float32";Type[Type["Float64"]=-12]="Float64";Type[Type["DateDay"]=-13]="DateDay";Type[Type["DateMillisecond"]=-14]="DateMillisecond";Type[Type["TimestampSecond"]=-15]="TimestampSecond";Type[Type["TimestampMillisecond"]=-16]="TimestampMillisecond";Type[Type["TimestampMicrosecond"]=-17]="TimestampMicrosecond";Type[Type["TimestampNanosecond"]=-18]="TimestampNanosecond";Type[Type["TimeSecond"]=-19]="TimeSecond";Type[Type["TimeMillisecond"]=-20]="TimeMillisecond";Type[Type["TimeMicrosecond"]=-21]="TimeMicrosecond";Type[Type["TimeNanosecond"]=-22]="TimeNanosecond";Type[Type["DenseUnion"]=-23]="DenseUnion";Type[Type["SparseUnion"]=-24]="SparseUnion";Type[Type["IntervalDayTime"]=-25]="IntervalDayTime";Type[Type["IntervalYearMonth"]=-26]="IntervalYearMonth";})(Type$1||(Type$1={}));var _Symbol$toStringTag,_Symbol$toStringTag2,_Symbol$toStringTag7;class DataType{static isNull(x){return x&&x.typeId===Type$1.Null;}static isInt(x){return x&&x.typeId===Type$1.Int;}static isFloat(x){return x&&x.typeId===Type$1.Float;}static isBinary(x){return x&&x.typeId===Type$1.Binary;}static isUtf8(x){return x&&x.typeId===Type$1.Utf8;}static isBool(x){return x&&x.typeId===Type$1.Bool;}static isDecimal(x){return x&&x.typeId===Type$1.Decimal;}static isDate(x){return x&&x.typeId===Type$1.Date;}static isTime(x){return x&&x.typeId===Type$1.Time;}static isTimestamp(x){return x&&x.typeId===Type$1.Timestamp;}static isInterval(x){return x&&x.typeId===Type$1.Interval;}static isList(x){return x&&x.typeId===Type$1.List;}static isStruct(x){return x&&x.typeId===Type$1.Struct;}static isUnion(x){return x&&x.typeId===Type$1.Union;}static isFixedSizeBinary(x){return x&&x.typeId===Type$1.FixedSizeBinary;}static isFixedSizeList(x){return x&&x.typeId===Type$1.FixedSizeList;}static isMap(x){return x&&x.typeId===Type$1.Map;}static isDictionary(x){return x&&x.typeId===Type$1.Dictionary;}get typeId(){return Type$1.NONE;}compareTo(other){return this===other;}}_Symbol$toStringTag=Symbol.toStringTag;class Int extends DataType{constructor(isSigned,bitWidth){super();_defineProperty$1(this,"isSigned",void 0);_defineProperty$1(this,"bitWidth",void 0);this.isSigned=isSigned;this.bitWidth=bitWidth;}get typeId(){return Type$1.Int;}get[_Symbol$toStringTag](){return 'Int';}toString(){return "".concat(this.isSigned?'I':'Ui',"nt").concat(this.bitWidth);}}class Int8 extends Int{constructor(){super(true,8);}}class Int16 extends Int{constructor(){super(true,16);}}class Int32 extends Int{constructor(){super(true,32);}}class Uint8 extends Int{constructor(){super(false,8);}}class Uint16 extends Int{constructor(){super(false,16);}}class Uint32 extends Int{constructor(){super(false,32);}}var Precision={HALF:16,SINGLE:32,DOUBLE:64};_Symbol$toStringTag2=Symbol.toStringTag;class Float extends DataType{constructor(precision){super();_defineProperty$1(this,"precision",void 0);this.precision=precision;}get typeId(){return Type$1.Float;}get[_Symbol$toStringTag2](){return 'Float';}toString(){return "Float".concat(this.precision);}}class Float32 extends Float{constructor(){super(Precision.SINGLE);}}class Float64 extends Float{constructor(){super(Precision.DOUBLE);}}_Symbol$toStringTag7=Symbol.toStringTag;class FixedSizeList extends DataType{constructor(listSize,child){super();_defineProperty$1(this,"listSize",void 0);_defineProperty$1(this,"children",void 0);this.listSize=listSize;this.children=[child];}get typeId(){return Type$1.FixedSizeList;}get valueType(){return this.children[0].type;}get valueField(){return this.children[0];}get[_Symbol$toStringTag7](){return 'FixedSizeList';}toString(){return "FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">");}}function getArrowTypeFromTypedArray(array){switch(array.constructor){case Int8Array:return new Int8();case Uint8Array:return new Uint8();case Int16Array:return new Int16();case Uint16Array:return new Uint16();case Int32Array:return new Int32();case Uint32Array:return new Uint32();case Float32Array:return new Float32();case Float64Array:return new Float64();default:throw new Error('array type not supported');}}function deduceMeshField(attributeName,attribute,optionalMetadata){var type=getArrowTypeFromTypedArray(attribute.value);var metadata=optionalMetadata?optionalMetadata:makeMeshAttributeMetadata(attribute);var field=new Field(attributeName,new FixedSizeList(attribute.size,new Field('value',type)),false,metadata);return field;}function makeMeshAttributeMetadata(attribute){var result=new Map();if('byteOffset'in attribute){result.set('byteOffset',attribute.byteOffset.toString(10));}if('byteStride'in attribute){result.set('byteStride',attribute.byteStride.toString(10));}if('normalized'in attribute){result.set('normalized',attribute.normalized.toString());}return result;}function getDracoSchema(attributes,loaderData,indices){var metadataMap=makeMetadata(loaderData.metadata);var fields=[];var namedLoaderDataAttributes=transformAttributesLoaderData(loaderData.attributes);for(var attributeName in attributes){var attribute=attributes[attributeName];var field=getArrowFieldFromAttribute(attributeName,attribute,namedLoaderDataAttributes[attributeName]);fields.push(field);}if(indices){var indicesField=getArrowFieldFromAttribute('indices',indices);fields.push(indicesField);}return new Schema(fields,metadataMap);}function transformAttributesLoaderData(loaderData){var result={};for(var key in loaderData){var dracoAttribute=loaderData[key];result[dracoAttribute.name||'undefined']=dracoAttribute;}return result;}function getArrowFieldFromAttribute(attributeName,attribute,loaderData){var metadataMap=loaderData?makeMetadata(loaderData.metadata):undefined;var field=deduceMeshField(attributeName,attribute,metadataMap);return field;}function makeMetadata(metadata){var metadataMap=new Map();for(var key in metadata){metadataMap.set("".concat(key,".string"),JSON.stringify(metadata[key]));}return metadataMap;}var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP={POSITION:'POSITION',NORMAL:'NORMAL',COLOR:'COLOR_0',TEX_COORD:'TEXCOORD_0'};var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};var INDEX_ITEM_SIZE=4;class DracoParser{constructor(draco){_defineProperty$1(this,"draco",void 0);_defineProperty$1(this,"decoder",void 0);_defineProperty$1(this,"metadataQuerier",void 0);this.draco=draco;this.decoder=new this.draco.Decoder();this.metadataQuerier=new this.draco.MetadataQuerier();}destroy(){this.draco.destroy(this.decoder);this.draco.destroy(this.metadataQuerier);}parseSync(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var buffer=new this.draco.DecoderBuffer();buffer.Init(new Int8Array(arrayBuffer),arrayBuffer.byteLength);this._disableAttributeTransforms(options);var geometry_type=this.decoder.GetEncodedGeometryType(buffer);var dracoGeometry=geometry_type===this.draco.TRIANGULAR_MESH?new this.draco.Mesh():new this.draco.PointCloud();try{var dracoStatus;switch(geometry_type){case this.draco.TRIANGULAR_MESH:dracoStatus=this.decoder.DecodeBufferToMesh(buffer,dracoGeometry);break;case this.draco.POINT_CLOUD:dracoStatus=this.decoder.DecodeBufferToPointCloud(buffer,dracoGeometry);break;default:throw new Error('DRACO: Unknown geometry type.');}if(!dracoStatus.ok()||!dracoGeometry.ptr){var message="DRACO decompression failed: ".concat(dracoStatus.error_msg());throw new Error(message);}var loaderData=this._getDracoLoaderData(dracoGeometry,geometry_type,options);var geometry=this._getMeshData(dracoGeometry,loaderData,options);var boundingBox=getMeshBoundingBox(geometry.attributes);var schema=getDracoSchema(geometry.attributes,loaderData,geometry.indices);var data=_objectSpread2(_objectSpread2({loader:'draco',loaderData,header:{vertexCount:dracoGeometry.num_points(),boundingBox}},geometry),{},{schema});return data;}finally{this.draco.destroy(buffer);if(dracoGeometry){this.draco.destroy(dracoGeometry);}}}_getDracoLoaderData(dracoGeometry,geometry_type,options){var metadata=this._getTopLevelMetadata(dracoGeometry);var attributes=this._getDracoAttributes(dracoGeometry,options);return {geometry_type,num_attributes:dracoGeometry.num_attributes(),num_points:dracoGeometry.num_points(),num_faces:dracoGeometry instanceof this.draco.Mesh?dracoGeometry.num_faces():0,metadata,attributes};}_getDracoAttributes(dracoGeometry,options){var dracoAttributes={};for(var attributeId=0;attributeId<dracoGeometry.num_attributes();attributeId++){var dracoAttribute=this.decoder.GetAttribute(dracoGeometry,attributeId);var metadata=this._getAttributeMetadata(dracoGeometry,attributeId);dracoAttributes[dracoAttribute.unique_id()]={unique_id:dracoAttribute.unique_id(),attribute_type:dracoAttribute.attribute_type(),data_type:dracoAttribute.data_type(),num_components:dracoAttribute.num_components(),byte_offset:dracoAttribute.byte_offset(),byte_stride:dracoAttribute.byte_stride(),normalized:dracoAttribute.normalized(),attribute_index:attributeId,metadata};var quantization=this._getQuantizationTransform(dracoAttribute,options);if(quantization){dracoAttributes[dracoAttribute.unique_id()].quantization_transform=quantization;}var octahedron=this._getOctahedronTransform(dracoAttribute,options);if(octahedron){dracoAttributes[dracoAttribute.unique_id()].octahedron_transform=octahedron;}}return dracoAttributes;}_getMeshData(dracoGeometry,loaderData,options){var attributes=this._getMeshAttributes(loaderData,dracoGeometry,options);var positionAttribute=attributes.POSITION;if(!positionAttribute){throw new Error('DRACO: No position attribute found.');}if(dracoGeometry instanceof this.draco.Mesh){switch(options.topology){case'triangle-strip':return {topology:'triangle-strip',mode:4,attributes,indices:{value:this._getTriangleStripIndices(dracoGeometry),size:1}};case'triangle-list':default:return {topology:'triangle-list',mode:5,attributes,indices:{value:this._getTriangleListIndices(dracoGeometry),size:1}};}}return {topology:'point-list',mode:0,attributes};}_getMeshAttributes(loaderData,dracoGeometry,options){var attributes={};for(var loaderAttribute of Object.values(loaderData.attributes)){var attributeName=this._deduceAttributeName(loaderAttribute,options);loaderAttribute.name=attributeName;var{value,size}=this._getAttributeValues(dracoGeometry,loaderAttribute);attributes[attributeName]={value,size,byteOffset:loaderAttribute.byte_offset,byteStride:loaderAttribute.byte_stride,normalized:loaderAttribute.normalized};}return attributes;}_getTriangleListIndices(dracoGeometry){var numFaces=dracoGeometry.num_faces();var numIndices=numFaces*3;var byteLength=numIndices*INDEX_ITEM_SIZE;var ptr=this.draco._malloc(byteLength);try{this.decoder.GetTrianglesUInt32Array(dracoGeometry,byteLength,ptr);return new Uint32Array(this.draco.HEAPF32.buffer,ptr,numIndices).slice();}finally{this.draco._free(ptr);}}_getTriangleStripIndices(dracoGeometry){var dracoArray=new this.draco.DracoInt32Array();try{this.decoder.GetTriangleStripsFromMesh(dracoGeometry,dracoArray);return getUint32Array(dracoArray);}finally{this.draco.destroy(dracoArray);}}_getAttributeValues(dracoGeometry,attribute){var TypedArrayCtor=DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP[attribute.data_type];var numComponents=attribute.num_components;var numPoints=dracoGeometry.num_points();var numValues=numPoints*numComponents;var byteLength=numValues*TypedArrayCtor.BYTES_PER_ELEMENT;var dataType=getDracoDataType(this.draco,TypedArrayCtor);var value;var ptr=this.draco._malloc(byteLength);try{var dracoAttribute=this.decoder.GetAttribute(dracoGeometry,attribute.attribute_index);this.decoder.GetAttributeDataArrayForAllPoints(dracoGeometry,dracoAttribute,dataType,byteLength,ptr);value=new TypedArrayCtor(this.draco.HEAPF32.buffer,ptr,numValues).slice();}finally{this.draco._free(ptr);}return {value,size:numComponents};}_deduceAttributeName(attribute,options){var uniqueId=attribute.unique_id;for(var[attributeName,attributeUniqueId]of Object.entries(options.extraAttributes||{})){if(attributeUniqueId===uniqueId){return attributeName;}}var thisAttributeType=attribute.attribute_type;for(var dracoAttributeConstant in DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP){var attributeType=this.draco[dracoAttributeConstant];if(attributeType===thisAttributeType){return DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP[dracoAttributeConstant];}}var entryName=options.attributeNameEntry||'name';if(attribute.metadata[entryName]){return attribute.metadata[entryName].string;}return "CUSTOM_ATTRIBUTE_".concat(uniqueId);}_getTopLevelMetadata(dracoGeometry){var dracoMetadata=this.decoder.GetMetadata(dracoGeometry);return this._getDracoMetadata(dracoMetadata);}_getAttributeMetadata(dracoGeometry,attributeId){var dracoMetadata=this.decoder.GetAttributeMetadata(dracoGeometry,attributeId);return this._getDracoMetadata(dracoMetadata);}_getDracoMetadata(dracoMetadata){if(!dracoMetadata||!dracoMetadata.ptr){return {};}var result={};var numEntries=this.metadataQuerier.NumEntries(dracoMetadata);for(var entryIndex=0;entryIndex<numEntries;entryIndex++){var entryName=this.metadataQuerier.GetEntryName(dracoMetadata,entryIndex);result[entryName]=this._getDracoMetadataField(dracoMetadata,entryName);}return result;}_getDracoMetadataField(dracoMetadata,entryName){var dracoArray=new this.draco.DracoInt32Array();try{this.metadataQuerier.GetIntEntryArray(dracoMetadata,entryName,dracoArray);var intArray=getInt32Array(dracoArray);return {int:this.metadataQuerier.GetIntEntry(dracoMetadata,entryName),string:this.metadataQuerier.GetStringEntry(dracoMetadata,entryName),double:this.metadataQuerier.GetDoubleEntry(dracoMetadata,entryName),intArray};}finally{this.draco.destroy(dracoArray);}}_disableAttributeTransforms(options){var{quantizedAttributes=[],octahedronAttributes=[]}=options;var skipAttributes=[...quantizedAttributes,...octahedronAttributes];for(var dracoAttributeName of skipAttributes){this.decoder.SkipAttributeTransform(this.draco[dracoAttributeName]);}}_getQuantizationTransform(dracoAttribute,options){var{quantizedAttributes=[]}=options;var attribute_type=dracoAttribute.attribute_type();var skip=quantizedAttributes.map(type=>this.decoder[type]).includes(attribute_type);if(skip){var transform=new this.draco.AttributeQuantizationTransform();try{if(transform.InitFromAttribute(dracoAttribute)){return {quantization_bits:transform.quantization_bits(),range:transform.range(),min_values:new Float32Array([1,2,3]).map(i=>transform.min_value(i))};}}finally{this.draco.destroy(transform);}}return null;}_getOctahedronTransform(dracoAttribute,options){var{octahedronAttributes=[]}=options;var attribute_type=dracoAttribute.attribute_type();var octahedron=octahedronAttributes.map(type=>this.decoder[type]).includes(attribute_type);if(octahedron){var transform=new this.draco.AttributeQuantizationTransform();try{if(transform.InitFromAttribute(dracoAttribute)){return {quantization_bits:transform.quantization_bits()};}}finally{this.draco.destroy(transform);}}return null;}}function getDracoDataType(draco,attributeType){switch(attributeType){case Float32Array:return draco.DT_FLOAT32;case Int8Array:return draco.DT_INT8;case Int16Array:return draco.DT_INT16;case Int32Array:return draco.DT_INT32;case Uint8Array:return draco.DT_UINT8;case Uint16Array:return draco.DT_UINT16;case Uint32Array:return draco.DT_UINT32;default:return draco.DT_INVALID;}}function getInt32Array(dracoArray){var numValues=dracoArray.size();var intArray=new Int32Array(numValues);for(var _i39=0;_i39<numValues;_i39++){intArray[_i39]=dracoArray.GetValue(_i39);}return intArray;}function getUint32Array(dracoArray){var numValues=dracoArray.size();var intArray=new Int32Array(numValues);for(var _i40=0;_i40<numValues;_i40++){intArray[_i40]=dracoArray.GetValue(_i40);}return intArray;}var DRACO_VERSION='1.4.1';var DRACO_JS_DECODER_URL="https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION,"/draco_decoder.js");var DRACO_WASM_WRAPPER_URL="https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION,"/draco_wasm_wrapper.js");var DRACO_WASM_DECODER_URL="https://www.gstatic.com/draco/versioned/decoders/".concat(DRACO_VERSION,"/draco_decoder.wasm");var loadDecoderPromise;function loadDracoDecoderModule(_x41){return _loadDracoDecoderModule.apply(this,arguments);}function _loadDracoDecoderModule(){_loadDracoDecoderModule=_asyncToGenerator(function*(options){var modules=options.modules||{};if(modules.draco3d){loadDecoderPromise=loadDecoderPromise||modules.draco3d.createDecoderModule({}).then(draco=>{return {draco};});}else {loadDecoderPromise=loadDecoderPromise||loadDracoDecoder(options);}return yield loadDecoderPromise;});return _loadDracoDecoderModule.apply(this,arguments);}function loadDracoDecoder(_x42){return _loadDracoDecoder.apply(this,arguments);}function _loadDracoDecoder(){_loadDracoDecoder=_asyncToGenerator(function*(options){var DracoDecoderModule;var wasmBinary;switch(options.draco&&options.draco.decoderType){case'js':DracoDecoderModule=yield loadLibrary(DRACO_JS_DECODER_URL,'draco',options);break;case'wasm':default:[DracoDecoderModule,wasmBinary]=yield Promise.all([yield loadLibrary(DRACO_WASM_WRAPPER_URL,'draco',options),yield loadLibrary(DRACO_WASM_DECODER_URL,'draco',options)]);}DracoDecoderModule=DracoDecoderModule||globalThis.DracoDecoderModule;return yield initializeDracoDecoder(DracoDecoderModule,wasmBinary);});return _loadDracoDecoder.apply(this,arguments);}function initializeDracoDecoder(DracoDecoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(resolve=>{DracoDecoderModule(_objectSpread2(_objectSpread2({},options),{},{onModuleLoaded:draco=>resolve({draco})}));});}var DracoLoader=_objectSpread2(_objectSpread2({},DracoLoader$1),{},{parse:parse$2});function parse$2(_x43,_x44){return _parse$2.apply(this,arguments);}function _parse$2(){_parse$2=_asyncToGenerator(function*(arrayBuffer,options){var{draco}=yield loadDracoDecoderModule(options);var dracoParser=new DracoParser(draco);try{return dracoParser.parseSync(arrayBuffer,options===null||options===void 0?void 0:options.draco);}finally{dracoParser.destroy();}});return _parse$2.apply(this,arguments);}var GL_PRIMITIVE_MODE={POINTS:0x0000,LINES:0x0001,LINE_LOOP:0x0002,LINE_STRIP:0x0003,TRIANGLES:0x0004,TRIANGLE_STRIP:0x0005,TRIANGLE_FAN:0x0006};var GL_TYPE={BYTE:5120,UNSIGNED_BYTE:5121,SHORT:5122,UNSIGNED_SHORT:5123,INT:5124,UNSIGNED_INT:5125,FLOAT:5126,DOUBLE:5130};var GL$1=_objectSpread2(_objectSpread2({},GL_PRIMITIVE_MODE),GL_TYPE);var GL_TYPE_TO_ARRAY_TYPE={[GL_TYPE.DOUBLE]:Float64Array,[GL_TYPE.FLOAT]:Float32Array,[GL_TYPE.UNSIGNED_SHORT]:Uint16Array,[GL_TYPE.UNSIGNED_INT]:Uint32Array,[GL_TYPE.UNSIGNED_BYTE]:Uint8Array,[GL_TYPE.BYTE]:Int8Array,[GL_TYPE.SHORT]:Int16Array,[GL_TYPE.INT]:Int32Array};var NAME_TO_GL_TYPE={DOUBLE:GL_TYPE.DOUBLE,FLOAT:GL_TYPE.FLOAT,UNSIGNED_SHORT:GL_TYPE.UNSIGNED_SHORT,UNSIGNED_INT:GL_TYPE.UNSIGNED_INT,UNSIGNED_BYTE:GL_TYPE.UNSIGNED_BYTE,BYTE:GL_TYPE.BYTE,SHORT:GL_TYPE.SHORT,INT:GL_TYPE.INT};var ERR_TYPE_CONVERSION='Failed to convert GL type';class GLType{static fromTypedArray(arrayOrType){arrayOrType=ArrayBuffer.isView(arrayOrType)?arrayOrType.constructor:arrayOrType;for(var glType in GL_TYPE_TO_ARRAY_TYPE){var ArrayType=GL_TYPE_TO_ARRAY_TYPE[glType];if(ArrayType===arrayOrType){return glType;}}throw new Error(ERR_TYPE_CONVERSION);}static fromName(name){var glType=NAME_TO_GL_TYPE[name];if(!glType){throw new Error(ERR_TYPE_CONVERSION);}return glType;}static getArrayType(glType){switch(glType){case GL_TYPE.UNSIGNED_SHORT_5_6_5:case GL_TYPE.UNSIGNED_SHORT_4_4_4_4:case GL_TYPE.UNSIGNED_SHORT_5_5_5_1:return Uint16Array;default:var ArrayType=GL_TYPE_TO_ARRAY_TYPE[glType];if(!ArrayType){throw new Error(ERR_TYPE_CONVERSION);}return ArrayType;}}static getByteSize(glType){var ArrayType=GLType.getArrayType(glType);return ArrayType.BYTES_PER_ELEMENT;}static validate(glType){return Boolean(GLType.getArrayType(glType));}static createTypedArray(glType,buffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var length=arguments.length>3?arguments[3]:undefined;if(length===undefined){length=(buffer.byteLength-byteOffset)/GLType.getByteSize(glType);}var ArrayType=GLType.getArrayType(glType);return new ArrayType(buffer,byteOffset,length);}}function assert$2(condition,message){if(!condition){throw new Error("math.gl assertion failed. ".concat(message));}}function decodeRGB565(rgb565){var target=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[0,0,0];var r5=rgb565>>11&31;var g6=rgb565>>5&63;var b5=rgb565&31;target[0]=r5<<3;target[1]=g6<<2;target[2]=b5<<3;return target;}new Vector2$1();new Vector3$1();new Vector2$1();new Vector2$1();function fromSNorm(value){var rangeMaximum=arguments.length>1&&arguments[1]!==undefined?arguments[1]:255;return clamp$1(value,0.0,rangeMaximum)/rangeMaximum*2.0-1.0;}function signNotZero(value){return value<0.0?-1.0:1.0;}function octDecodeInRange(x,y,rangeMax,result){assert$2(result);if(x<0||x>rangeMax||y<0||y>rangeMax){throw new Error("x and y must be unsigned normalized integers between 0 and ".concat(rangeMax));}result.x=fromSNorm(x,rangeMax);result.y=fromSNorm(y,rangeMax);result.z=1.0-(Math.abs(result.x)+Math.abs(result.y));if(result.z<0.0){var oldVX=result.x;result.x=(1.0-Math.abs(result.y))*signNotZero(oldVX);result.y=(1.0-Math.abs(oldVX))*signNotZero(result.y);}return result.normalize();}function octDecode(x,y,result){return octDecodeInRange(x,y,255,result);}class Tile3DFeatureTable{constructor(featureTableJson,featureTableBinary){_defineProperty$1(this,"json",void 0);_defineProperty$1(this,"buffer",void 0);_defineProperty$1(this,"featuresLength",0);_defineProperty$1(this,"_cachedTypedArrays",{});this.json=featureTableJson;this.buffer=featureTableBinary;}getExtension(extensionName){return this.json.extensions&&this.json.extensions[extensionName];}hasProperty(propertyName){return Boolean(this.json[propertyName]);}getGlobalProperty(propertyName){var componentType=arguments.length>1&&arguments[1]!==undefined?arguments[1]:GL$1.UNSIGNED_INT;var componentLength=arguments.length>2&&arguments[2]!==undefined?arguments[2]:1;var jsonValue=this.json[propertyName];if(jsonValue&&Number.isFinite(jsonValue.byteOffset)){return this._getTypedArrayFromBinary(propertyName,componentType,componentLength,1,jsonValue.byteOffset);}return jsonValue;}getPropertyArray(propertyName,componentType,componentLength){var jsonValue=this.json[propertyName];if(jsonValue&&Number.isFinite(jsonValue.byteOffset)){if('componentType'in jsonValue){componentType=GLType.fromName(jsonValue.componentType);}return this._getTypedArrayFromBinary(propertyName,componentType,componentLength,this.featuresLength,jsonValue.byteOffset);}return this._getTypedArrayFromArray(propertyName,componentType,jsonValue);}getProperty(propertyName,componentType,componentLength,featureId,result){var jsonValue=this.json[propertyName];if(!jsonValue){return jsonValue;}var typedArray=this.getPropertyArray(propertyName,componentType,componentLength);if(componentLength===1){return typedArray[featureId];}for(var _i41=0;_i41<componentLength;++_i41){result[_i41]=typedArray[componentLength*featureId+_i41];}return result;}_getTypedArrayFromBinary(propertyName,componentType,componentLength,count,byteOffset){var cachedTypedArrays=this._cachedTypedArrays;var typedArray=cachedTypedArrays[propertyName];if(!typedArray){typedArray=GLType.createTypedArray(componentType,this.buffer.buffer,this.buffer.byteOffset+byteOffset,count*componentLength);cachedTypedArrays[propertyName]=typedArray;}return typedArray;}_getTypedArrayFromArray(propertyName,componentType,array){var cachedTypedArrays=this._cachedTypedArrays;var typedArray=cachedTypedArrays[propertyName];if(!typedArray){typedArray=GLType.createTypedArray(componentType,array);cachedTypedArrays[propertyName]=typedArray;}return typedArray;}}var COMPONENTS_PER_ATTRIBUTE={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var UNPACKER={SCALAR:(values,i)=>values[i],VEC2:(values,i)=>[values[2*i+0],values[2*i+1]],VEC3:(values,i)=>[values[3*i+0],values[3*i+1],values[3*i+2]],VEC4:(values,i)=>[values[4*i+0],values[4*i+1],values[4*i+2],values[4*i+3]],MAT2:(values,i)=>[values[4*i+0],values[4*i+1],values[4*i+2],values[4*i+3]],MAT3:(values,i)=>[values[9*i+0],values[9*i+1],values[9*i+2],values[9*i+3],values[9*i+4],values[9*i+5],values[9*i+6],values[9*i+7],values[9*i+8]],MAT4:(values,i)=>[values[16*i+0],values[16*i+1],values[16*i+2],values[16*i+3],values[16*i+4],values[16*i+5],values[16*i+6],values[16*i+7],values[16*i+8],values[16*i+9],values[16*i+10],values[16*i+11],values[16*i+12],values[16*i+13],values[16*i+14],values[16*i+15]]};var PACKER={SCALAR:(x,values,i)=>{values[i]=x;},VEC2:(x,values,i)=>{values[2*i+0]=x[0];values[2*i+1]=x[1];},VEC3:(x,values,i)=>{values[3*i+0]=x[0];values[3*i+1]=x[1];values[3*i+2]=x[2];},VEC4:(x,values,i)=>{values[4*i+0]=x[0];values[4*i+1]=x[1];values[4*i+2]=x[2];values[4*i+3]=x[3];},MAT2:(x,values,i)=>{values[4*i+0]=x[0];values[4*i+1]=x[1];values[4*i+2]=x[2];values[4*i+3]=x[3];},MAT3:(x,values,i)=>{values[9*i+0]=x[0];values[9*i+1]=x[1];values[9*i+2]=x[2];values[9*i+3]=x[3];values[9*i+4]=x[4];values[9*i+5]=x[5];values[9*i+6]=x[6];values[9*i+7]=x[7];values[9*i+8]=x[8];values[9*i+9]=x[9];},MAT4:(x,values,i)=>{values[16*i+0]=x[0];values[16*i+1]=x[1];values[16*i+2]=x[2];values[16*i+3]=x[3];values[16*i+4]=x[4];values[16*i+5]=x[5];values[16*i+6]=x[6];values[16*i+7]=x[7];values[16*i+8]=x[8];values[16*i+9]=x[9];values[16*i+10]=x[10];values[16*i+11]=x[11];values[16*i+12]=x[12];values[16*i+13]=x[13];values[16*i+14]=x[14];values[16*i+15]=x[15];}};function createTypedArrayFromAccessor(tile3DAccessor,buffer,byteOffset,length){var{componentType}=tile3DAccessor;assert$7(tile3DAccessor.componentType);var type=typeof componentType==='string'?GLType.fromName(componentType):componentType;var size=COMPONENTS_PER_ATTRIBUTE[tile3DAccessor.type];var unpacker=UNPACKER[tile3DAccessor.type];var packer=PACKER[tile3DAccessor.type];byteOffset+=tile3DAccessor.byteOffset;var values=GLType.createTypedArray(type,buffer,byteOffset,size*length);return {values,type,size,unpacker,packer};}var defined$1=x=>x!==undefined;function initializeHierarchy(batchTable,jsonHeader,binaryBody){if(!jsonHeader){return null;}var hierarchy=batchTable.getExtension('3DTILES_batch_table_hierarchy');var legacyHierarchy=jsonHeader.HIERARCHY;if(legacyHierarchy){console.warn('3D Tile Parser: HIERARCHY is deprecated. Use 3DTILES_batch_table_hierarchy.');jsonHeader.extensions=jsonHeader.extensions||{};jsonHeader.extensions['3DTILES_batch_table_hierarchy']=legacyHierarchy;hierarchy=legacyHierarchy;}if(!hierarchy){return null;}return initializeHierarchyValues(hierarchy,binaryBody);}function initializeHierarchyValues(hierarchyJson,binaryBody){var i;var classId;var binaryAccessor;var instancesLength=hierarchyJson.instancesLength;var classes=hierarchyJson.classes;var classIds=hierarchyJson.classIds;var parentCounts=hierarchyJson.parentCounts;var parentIds=hierarchyJson.parentIds;var parentIdsLength=instancesLength;if(defined$1(classIds.byteOffset)){classIds.componentType=defaultValue(classIds.componentType,GL.UNSIGNED_SHORT);classIds.type=AttributeType.SCALAR;binaryAccessor=getBinaryAccessor(classIds);classIds=binaryAccessor.createArrayBufferView(binaryBody.buffer,binaryBody.byteOffset+classIds.byteOffset,instancesLength);}var parentIndexes;if(defined$1(parentCounts)){if(defined$1(parentCounts.byteOffset)){parentCounts.componentType=defaultValue(parentCounts.componentType,GL.UNSIGNED_SHORT);parentCounts.type=AttributeType.SCALAR;binaryAccessor=getBinaryAccessor(parentCounts);parentCounts=binaryAccessor.createArrayBufferView(binaryBody.buffer,binaryBody.byteOffset+parentCounts.byteOffset,instancesLength);}parentIndexes=new Uint16Array(instancesLength);parentIdsLength=0;for(i=0;i<instancesLength;++i){parentIndexes[i]=parentIdsLength;parentIdsLength+=parentCounts[i];}}if(defined$1(parentIds)&&defined$1(parentIds.byteOffset)){parentIds.componentType=defaultValue(parentIds.componentType,GL.UNSIGNED_SHORT);parentIds.type=AttributeType.SCALAR;binaryAccessor=getBinaryAccessor(parentIds);parentIds=binaryAccessor.createArrayBufferView(binaryBody.buffer,binaryBody.byteOffset+parentIds.byteOffset,parentIdsLength);}var classesLength=classes.length;for(i=0;i<classesLength;++i){var classInstancesLength=classes[i].length;var properties=classes[i].instances;var binaryProperties=getBinaryProperties(classInstancesLength,properties,binaryBody);classes[i].instances=combine(binaryProperties,properties);}var classCounts=new Array(classesLength).fill(0);var classIndexes=new Uint16Array(instancesLength);for(i=0;i<instancesLength;++i){classId=classIds[i];classIndexes[i]=classCounts[classId];++classCounts[classId];}var hierarchy={classes,classIds,classIndexes,parentCounts,parentIndexes,parentIds};validateHierarchy(hierarchy);return hierarchy;}function traverseHierarchy(hierarchy,instanceIndex,endConditionCallback){if(!hierarchy){return;}var parentCounts=hierarchy.parentCounts;var parentIds=hierarchy.parentIds;if(parentIds){return endConditionCallback(hierarchy,instanceIndex);}if(parentCounts>0){return traverseHierarchyMultipleParents(hierarchy,instanceIndex,endConditionCallback);}return traverseHierarchySingleParent(hierarchy,instanceIndex,endConditionCallback);}function traverseHierarchyMultipleParents(hierarchy,instanceIndex,endConditionCallback){var classIds=hierarchy.classIds;var parentCounts=hierarchy.parentCounts;var parentIds=hierarchy.parentIds;var parentIndexes=hierarchy.parentIndexes;var instancesLength=classIds.length;var visited=scratchVisited;visited.length=Math.max(visited.length,instancesLength);var visitedMarker=++marker;var stack=scratchStack;stack.length=0;stack.push(instanceIndex);while(stack.length>0){instanceIndex=stack.pop();if(visited[instanceIndex]===visitedMarker){continue;}visited[instanceIndex]=visitedMarker;var result=endConditionCallback(hierarchy,instanceIndex);if(defined$1(result)){return result;}var parentCount=parentCounts[instanceIndex];var parentIndex=parentIndexes[instanceIndex];for(var _i42=0;_i42<parentCount;++_i42){var parentId=parentIds[parentIndex+_i42];if(parentId!==instanceIndex){stack.push(parentId);}}}return null;}function traverseHierarchySingleParent(hierarchy,instanceIndex,endConditionCallback){var hasParent=true;while(hasParent){var result=endConditionCallback(hierarchy,instanceIndex);if(defined$1(result)){return result;}var parentId=hierarchy.parentIds[instanceIndex];hasParent=parentId!==instanceIndex;instanceIndex=parentId;}throw new Error('traverseHierarchySingleParent');}function validateHierarchy(hierarchy){var classIds=hierarchy.classIds;var instancesLength=classIds.length;for(var _i43=0;_i43<instancesLength;++_i43){validateInstance(hierarchy,_i43,stack);}}function validateInstance(hierarchy,instanceIndex,stack){var parentCounts=hierarchy.parentCounts;var parentIds=hierarchy.parentIds;var parentIndexes=hierarchy.parentIndexes;var classIds=hierarchy.classIds;var instancesLength=classIds.length;if(!defined$1(parentIds)){return;}assert(instanceIndex<instancesLength,"Parent index ".concat(instanceIndex," exceeds the total number of instances: ").concat(instancesLength));assert(stack.indexOf(instanceIndex)===-1,'Circular dependency detected in the batch table hierarchy.');stack.push(instanceIndex);var parentCount=defined$1(parentCounts)?parentCounts[instanceIndex]:1;var parentIndex=defined$1(parentCounts)?parentIndexes[instanceIndex]:instanceIndex;for(var _i44=0;_i44<parentCount;++_i44){var parentId=parentIds[parentIndex+_i44];if(parentId!==instanceIndex){validateInstance(hierarchy,parentId,stack);}}stack.pop(instanceIndex);}function defined(x){return x!==undefined&&x!==null;}var clone=(x,y)=>x;var IGNORED_PROPERTY_FIELDS={HIERARCHY:true,extensions:true,extras:true};class Tile3DBatchTableParser{constructor(json,binary,featureCount){var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var _this$json;_defineProperty$1(this,"json",void 0);_defineProperty$1(this,"binary",void 0);_defineProperty$1(this,"featureCount",void 0);_defineProperty$1(this,"_extensions",void 0);_defineProperty$1(this,"_properties",void 0);_defineProperty$1(this,"_binaryProperties",void 0);_defineProperty$1(this,"_hierarchy",void 0);assert$7(featureCount>=0);this.json=json||{};this.binary=binary;this.featureCount=featureCount;this._extensions=((_this$json=this.json)===null||_this$json===void 0?void 0:_this$json.extensions)||{};this._properties={};for(var propertyName in this.json){if(!IGNORED_PROPERTY_FIELDS[propertyName]){this._properties[propertyName]=this.json[propertyName];}}this._binaryProperties=this._initializeBinaryProperties();if(options['3DTILES_batch_table_hierarchy']){this._hierarchy=initializeHierarchy(this,this.json,this.binary);}}getExtension(extensionName){return this.json&&this.json.extensions&&this.json.extensions[extensionName];}memorySizeInBytes(){return 0;}isClass(batchId,className){this._checkBatchId(batchId);assert$7(typeof className==='string',className);if(this._hierarchy){var result=traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];return instanceClass.name===className;});return defined(result);}return false;}isExactClass(batchId,className){assert$7(typeof className==='string',className);return this.getExactClassName(batchId)===className;}getExactClassName(batchId){this._checkBatchId(batchId);if(this._hierarchy){var classId=this._hierarchy.classIds[batchId];var instanceClass=this._hierarchy.classes[classId];return instanceClass.name;}return undefined;}hasProperty(batchId,name){this._checkBatchId(batchId);assert$7(typeof name==='string',name);return defined(this._properties[name])||this._hasPropertyInHierarchy(batchId,name);}getPropertyNames(batchId,results){this._checkBatchId(batchId);results=defined(results)?results:[];results.length=0;var propertyNames=Object.keys(this._properties);results.push(...propertyNames);if(this._hierarchy){this._getPropertyNamesInHierarchy(batchId,results);}return results;}getProperty(batchId,name){this._checkBatchId(batchId);assert$7(typeof name==='string',name);if(this._binaryProperties){var binaryProperty=this._binaryProperties[name];if(defined(binaryProperty)){return this._getBinaryProperty(binaryProperty,batchId);}}var propertyValues=this._properties[name];if(defined(propertyValues)){return clone(propertyValues[batchId]);}if(this._hierarchy){var hierarchyProperty=this._getHierarchyProperty(batchId,name);if(defined(hierarchyProperty)){return hierarchyProperty;}}return undefined;}setProperty(batchId,name,value){var featureCount=this.featureCount;this._checkBatchId(batchId);assert$7(typeof name==='string',name);if(this._binaryProperties){var binaryProperty=this._binaryProperties[name];if(binaryProperty){this._setBinaryProperty(binaryProperty,batchId,value);return;}}if(this._hierarchy){if(this._setHierarchyProperty(this,batchId,name,value)){return;}}var propertyValues=this._properties[name];if(!defined(propertyValues)){this._properties[name]=new Array(featureCount);propertyValues=this._properties[name];}propertyValues[batchId]=clone(value);}_checkBatchId(batchId){var valid=batchId>=0&&batchId<this.featureCount;if(!valid){throw new Error('batchId not in range [0, featureCount - 1].');}}_getBinaryProperty(binaryProperty,index){return binaryProperty.unpack(binaryProperty.typedArray,index);}_setBinaryProperty(binaryProperty,index,value){binaryProperty.pack(value,binaryProperty.typedArray,index);}_initializeBinaryProperties(){var binaryProperties=null;for(var _name3 in this._properties){var property=this._properties[_name3];var binaryProperty=this._initializeBinaryProperty(_name3,property);if(binaryProperty){binaryProperties=binaryProperties||{};binaryProperties[_name3]=binaryProperty;}}return binaryProperties;}_initializeBinaryProperty(name,property){if('byteOffset'in property){var tile3DAccessor=property;assert$7(this.binary,"Property ".concat(name," requires a batch table binary."));assert$7(tile3DAccessor.type,"Property ".concat(name," requires a type."));var accessor=createTypedArrayFromAccessor(tile3DAccessor,this.binary.buffer,this.binary.byteOffset|0,this.featureCount);return {typedArray:accessor.values,componentCount:accessor.size,unpack:accessor.unpacker,pack:accessor.packer};}return null;}_hasPropertyInHierarchy(batchId,name){if(!this._hierarchy){return false;}var result=traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instances=hierarchy.classes[classId].instances;return defined(instances[name]);});return defined(result);}_getPropertyNamesInHierarchy(batchId,results){traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instances=hierarchy.classes[classId].instances;for(var _name4 in instances){if(instances.hasOwnProperty(_name4)){if(results.indexOf(_name4)===-1){results.push(_name4);}}}});}_getHierarchyProperty(batchId,name){return traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];var indexInClass=hierarchy.classIndexes[instanceIndex];var propertyValues=instanceClass.instances[name];if(defined(propertyValues)){if(defined(propertyValues.typedArray)){return this._getBinaryProperty(propertyValues,indexInClass);}return clone(propertyValues[indexInClass]);}return null;});}_setHierarchyProperty(batchTable,batchId,name,value){var result=traverseHierarchy(this._hierarchy,batchId,(hierarchy,instanceIndex)=>{var classId=hierarchy.classIds[instanceIndex];var instanceClass=hierarchy.classes[classId];var indexInClass=hierarchy.classIndexes[instanceIndex];var propertyValues=instanceClass.instances[name];if(defined(propertyValues)){assert$7(instanceIndex===batchId,"Inherited property \"".concat(name,"\" is read-only."));if(defined(propertyValues.typedArray)){this._setBinaryProperty(propertyValues,indexInClass,value);}else {propertyValues[indexInClass]=clone(value);}return true;}return false;});return defined(result);}}var SIZEOF_UINT32$1=4;function parse3DTileHeaderSync(tile,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var view=new DataView(arrayBuffer);tile.magic=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;tile.version=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;tile.byteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32$1;if(tile.version!==1){throw new Error("3D Tile Version ".concat(tile.version," not supported"));}return byteOffset;}var SIZEOF_UINT32=4;var DEPRECATION_WARNING='b3dm tile in legacy format.';function parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset){var view=new DataView(arrayBuffer);var batchLength;tile.header=tile.header||{};var featureTableJsonByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var featureTableBinaryByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var batchTableJsonByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;var batchTableBinaryByteLength=view.getUint32(byteOffset,true);byteOffset+=SIZEOF_UINT32;if(batchTableJsonByteLength>=570425344){byteOffset-=SIZEOF_UINT32*2;batchLength=featureTableJsonByteLength;batchTableJsonByteLength=featureTableBinaryByteLength;batchTableBinaryByteLength=0;featureTableJsonByteLength=0;featureTableBinaryByteLength=0;console.warn(DEPRECATION_WARNING);}else if(batchTableBinaryByteLength>=570425344){byteOffset-=SIZEOF_UINT32;batchLength=batchTableJsonByteLength;batchTableJsonByteLength=featureTableJsonByteLength;batchTableBinaryByteLength=featureTableBinaryByteLength;featureTableJsonByteLength=0;featureTableBinaryByteLength=0;console.warn(DEPRECATION_WARNING);}tile.header.featureTableJsonByteLength=featureTableJsonByteLength;tile.header.featureTableBinaryByteLength=featureTableBinaryByteLength;tile.header.batchTableJsonByteLength=batchTableJsonByteLength;tile.header.batchTableBinaryByteLength=batchTableBinaryByteLength;tile.header.batchLength=batchLength;return byteOffset;}function parse3DTileTablesSync(tile,arrayBuffer,byteOffset,options){byteOffset=parse3DTileFeatureTable(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileBatchTable(tile,arrayBuffer,byteOffset);return byteOffset;}function parse3DTileFeatureTable(tile,arrayBuffer,byteOffset,options){var{featureTableJsonByteLength,featureTableBinaryByteLength,batchLength}=tile.header;tile.featureTableJson={BATCH_LENGTH:batchLength||0};if(featureTableJsonByteLength>0){var featureTableString=getStringFromArrayBuffer(arrayBuffer,byteOffset,featureTableJsonByteLength);tile.featureTableJson=JSON.parse(featureTableString);}byteOffset+=featureTableJsonByteLength;tile.featureTableBinary=new Uint8Array(arrayBuffer,byteOffset,featureTableBinaryByteLength);byteOffset+=featureTableBinaryByteLength;return byteOffset;}function parse3DTileBatchTable(tile,arrayBuffer,byteOffset,options){var{batchTableJsonByteLength,batchTableBinaryByteLength}=tile.header;if(batchTableJsonByteLength>0){var batchTableString=getStringFromArrayBuffer(arrayBuffer,byteOffset,batchTableJsonByteLength);tile.batchTableJson=JSON.parse(batchTableString);byteOffset+=batchTableJsonByteLength;if(batchTableBinaryByteLength>0){tile.batchTableBinary=new Uint8Array(arrayBuffer,byteOffset,batchTableBinaryByteLength);tile.batchTableBinary=new Uint8Array(tile.batchTableBinary);byteOffset+=batchTableBinaryByteLength;}}return byteOffset;}function normalize3DTileColorAttribute(tile,colors,batchTable){if(!colors&&(!tile||!tile.batchIds||!batchTable)){return null;}var{batchIds,isRGB565,pointCount}=tile;if(batchIds&&batchTable){var colorArray=new Uint8ClampedArray(pointCount*3);for(var _i45=0;_i45<pointCount;_i45++){var batchId=batchIds[_i45];var dimensions=batchTable.getProperty(batchId,'dimensions');var color=dimensions.map(d=>d*255);colorArray[_i45*3]=color[0];colorArray[_i45*3+1]=color[1];colorArray[_i45*3+2]=color[2];}return {type:GL$1.UNSIGNED_BYTE,value:colorArray,size:3,normalized:true};}if(isRGB565){var _colorArray=new Uint8ClampedArray(pointCount*3);for(var _i46=0;_i46<pointCount;_i46++){var _color=decodeRGB565(colors[_i46]);_colorArray[_i46*3]=_color[0];_colorArray[_i46*3+1]=_color[1];_colorArray[_i46*3+2]=_color[2];}return {type:GL$1.UNSIGNED_BYTE,value:_colorArray,size:3,normalized:true};}if(colors&&colors.length===pointCount*3){return {type:GL$1.UNSIGNED_BYTE,value:colors,size:3,normalized:true};}return {type:GL$1.UNSIGNED_BYTE,value:colors,size:4,normalized:true};}var scratchNormal=new Vector3$1();function normalize3DTileNormalAttribute(tile,normals){if(!normals){return null;}if(tile.isOctEncoded16P){var decodedArray=new Float32Array(tile.pointsLength*3);for(var _i47=0;_i47<tile.pointsLength;_i47++){octDecode(normals[_i47*2],normals[_i47*2+1],scratchNormal);scratchNormal.toArray(decodedArray,_i47*3);}return {type:GL$1.FLOAT,size:2,value:decodedArray};}return {type:GL$1.FLOAT,size:2,value:normals};}function normalize3DTilePositionAttribute(tile,positions,options){if(!tile.isQuantized){return positions;}if(options['3d-tiles']&&options['3d-tiles'].decodeQuantizedPositions){tile.isQuantized=false;return decodeQuantizedPositions(tile,positions);}return {type:GL$1.UNSIGNED_SHORT,value:positions,size:3,normalized:true};}function decodeQuantizedPositions(tile,positions){var scratchPosition=new Vector3$1();var decodedArray=new Float32Array(tile.pointCount*3);for(var _i48=0;_i48<tile.pointCount;_i48++){scratchPosition.set(positions[_i48*3],positions[_i48*3+1],positions[_i48*3+2]).scale(1/tile.quantizedRange).multiply(tile.quantizedVolumeScale).add(tile.quantizedVolumeOffset).toArray(decodedArray,_i48*3);}return decodedArray;}function parsePointCloud3DTile(_x45,_x46,_x47,_x48,_x49){return _parsePointCloud3DTile.apply(this,arguments);}function _parsePointCloud3DTile(){_parsePointCloud3DTile=_asyncToGenerator(function*(tile,arrayBuffer,byteOffset,options,context){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesSync(tile,arrayBuffer,byteOffset);initializeTile(tile);var{featureTable,batchTable}=parsePointCloudTables(tile);yield parseDraco(tile,featureTable,batchTable,options,context);parsePositions(tile,featureTable,options);parseColors(tile,featureTable,batchTable);parseNormals(tile,featureTable);return byteOffset;});return _parsePointCloud3DTile.apply(this,arguments);}function initializeTile(tile){tile.attributes={positions:null,colors:null,normals:null,batchIds:null};tile.isQuantized=false;tile.isTranslucent=false;tile.isRGB565=false;tile.isOctEncoded16P=false;}function parsePointCloudTables(tile){var featureTable=new Tile3DFeatureTable(tile.featureTableJson,tile.featureTableBinary);var pointsLength=featureTable.getGlobalProperty('POINTS_LENGTH');if(!Number.isFinite(pointsLength)){throw new Error('POINTS_LENGTH must be defined');}featureTable.featuresLength=pointsLength;tile.featuresLength=pointsLength;tile.pointsLength=pointsLength;tile.pointCount=pointsLength;tile.rtcCenter=featureTable.getGlobalProperty('RTC_CENTER',GL$1.FLOAT,3);var batchTable=parseBatchIds(tile,featureTable);return {featureTable,batchTable};}function parsePositions(tile,featureTable,options){if(!tile.attributes.positions){if(featureTable.hasProperty('POSITION')){tile.attributes.positions=featureTable.getPropertyArray('POSITION',GL$1.FLOAT,3);}else if(featureTable.hasProperty('POSITION_QUANTIZED')){var positions=featureTable.getPropertyArray('POSITION_QUANTIZED',GL$1.UNSIGNED_SHORT,3);tile.isQuantized=true;tile.quantizedRange=(1<<16)-1;tile.quantizedVolumeScale=featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE',GL$1.FLOAT,3);if(!tile.quantizedVolumeScale){throw new Error('QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');}tile.quantizedVolumeOffset=featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET',GL$1.FLOAT,3);if(!tile.quantizedVolumeOffset){throw new Error('QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');}tile.attributes.positions=normalize3DTilePositionAttribute(tile,positions,options);}}if(!tile.attributes.positions){throw new Error('Either POSITION or POSITION_QUANTIZED must be defined.');}}function parseColors(tile,featureTable,batchTable){if(!tile.attributes.colors){var colors=null;if(featureTable.hasProperty('RGBA')){colors=featureTable.getPropertyArray('RGBA',GL$1.UNSIGNED_BYTE,4);tile.isTranslucent=true;}else if(featureTable.hasProperty('RGB')){colors=featureTable.getPropertyArray('RGB',GL$1.UNSIGNED_BYTE,3);}else if(featureTable.hasProperty('RGB565')){colors=featureTable.getPropertyArray('RGB565',GL$1.UNSIGNED_SHORT,1);tile.isRGB565=true;}tile.attributes.colors=normalize3DTileColorAttribute(tile,colors,batchTable);}if(featureTable.hasProperty('CONSTANT_RGBA')){tile.constantRGBA=featureTable.getGlobalProperty('CONSTANT_RGBA',GL$1.UNSIGNED_BYTE,4);}}function parseNormals(tile,featureTable){if(!tile.attributes.normals){var normals=null;if(featureTable.hasProperty('NORMAL')){normals=featureTable.getPropertyArray('NORMAL',GL$1.FLOAT,3);}else if(featureTable.hasProperty('NORMAL_OCT16P')){normals=featureTable.getPropertyArray('NORMAL_OCT16P',GL$1.UNSIGNED_BYTE,2);tile.isOctEncoded16P=true;}tile.attributes.normals=normalize3DTileNormalAttribute(tile,normals);}}function parseBatchIds(tile,featureTable){var batchTable=null;if(!tile.batchIds&&featureTable.hasProperty('BATCH_ID')){tile.batchIds=featureTable.getPropertyArray('BATCH_ID',GL$1.UNSIGNED_SHORT,1);if(tile.batchIds){var batchFeatureLength=featureTable.getGlobalProperty('BATCH_LENGTH');if(!batchFeatureLength){throw new Error('Global property: BATCH_LENGTH must be defined when BATCH_ID is defined.');}var{batchTableJson,batchTableBinary}=tile;batchTable=new Tile3DBatchTableParser(batchTableJson,batchTableBinary,batchFeatureLength);}}return batchTable;}function parseDraco(_x50,_x51,_x52,_x53,_x54){return _parseDraco.apply(this,arguments);}function _parseDraco(){_parseDraco=_asyncToGenerator(function*(tile,featureTable,batchTable,options,context){var dracoBuffer;var dracoFeatureTableProperties;var dracoBatchTableProperties;var batchTableDraco=tile.batchTableJson&&tile.batchTableJson.extensions&&tile.batchTableJson.extensions['3DTILES_draco_point_compression'];if(batchTableDraco){dracoBatchTableProperties=batchTableDraco.properties;}var featureTableDraco=featureTable.getExtension('3DTILES_draco_point_compression');if(featureTableDraco){dracoFeatureTableProperties=featureTableDraco.properties;var dracoByteOffset=featureTableDraco.byteOffset;var dracoByteLength=featureTableDraco.byteLength;if(!dracoFeatureTableProperties||!Number.isFinite(dracoByteOffset)||!dracoByteLength){throw new Error('Draco properties, byteOffset, and byteLength must be defined');}dracoBuffer=tile.featureTableBinary.slice(dracoByteOffset,dracoByteOffset+dracoByteLength);tile.hasPositions=Number.isFinite(dracoFeatureTableProperties.POSITION);tile.hasColors=Number.isFinite(dracoFeatureTableProperties.RGB)||Number.isFinite(dracoFeatureTableProperties.RGBA);tile.hasNormals=Number.isFinite(dracoFeatureTableProperties.NORMAL);tile.hasBatchIds=Number.isFinite(dracoFeatureTableProperties.BATCH_ID);tile.isTranslucent=Number.isFinite(dracoFeatureTableProperties.RGBA);}if(!dracoBuffer){return true;}var dracoData={buffer:dracoBuffer,properties:_objectSpread2(_objectSpread2({},dracoFeatureTableProperties),dracoBatchTableProperties),featureTableProperties:dracoFeatureTableProperties,batchTableProperties:dracoBatchTableProperties,dequantizeInShader:false};return yield loadDraco(tile,dracoData,options,context);});return _parseDraco.apply(this,arguments);}function loadDraco(_x55,_x56,_x57,_x58){return _loadDraco.apply(this,arguments);}function _loadDraco(){_loadDraco=_asyncToGenerator(function*(tile,dracoData,options,context){var{parse}=context;var dracoOptions=_objectSpread2(_objectSpread2({},options),{},{draco:_objectSpread2(_objectSpread2({},options.draco),{},{extraAttributes:dracoData.batchTableProperties||{}})});delete dracoOptions['3d-tiles'];var data=yield parse(dracoData.buffer,DracoLoader,dracoOptions);var decodedPositions=data.attributes.POSITION&&data.attributes.POSITION.value;var decodedColors=data.attributes.COLOR_0&&data.attributes.COLOR_0.value;var decodedNormals=data.attributes.NORMAL&&data.attributes.NORMAL.value;var decodedBatchIds=data.attributes.BATCH_ID&&data.attributes.BATCH_ID.value;var isQuantizedDraco=decodedPositions&&data.attributes.POSITION.value.quantization;var isOctEncodedDraco=decodedNormals&&data.attributes.NORMAL.value.quantization;if(isQuantizedDraco){var quantization=data.POSITION.data.quantization;var range=quantization.range;tile.quantizedVolumeScale=new Vector3$1(range,range,range);tile.quantizedVolumeOffset=new Vector3$1(quantization.minValues);tile.quantizedRange=(1<<quantization.quantizationBits)-1.0;tile.isQuantizedDraco=true;}if(isOctEncodedDraco){tile.octEncodedRange=(1<<data.NORMAL.data.quantization.quantizationBits)-1.0;tile.isOctEncodedDraco=true;}var batchTableAttributes={};if(dracoData.batchTableProperties){for(var attributeName of Object.keys(dracoData.batchTableProperties)){if(data.attributes[attributeName]&&data.attributes[attributeName].value){batchTableAttributes[attributeName.toLowerCase()]=data.attributes[attributeName].value;}}}tile.attributes=_objectSpread2({positions:decodedPositions,colors:normalize3DTileColorAttribute(tile,decodedColors,undefined),normals:decodedNormals,batchIds:decodedBatchIds},batchTableAttributes);});return _loadDraco.apply(this,arguments);}var VERSION$3="3.1.4";var VERSION$2="3.1.4";var VERSION$1="3.1.4";var BASIS_CDN_ENCODER_WASM="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1,"/dist/libs/basis_encoder.wasm");var BASIS_CDN_ENCODER_JS="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$1,"/dist/libs/basis_encoder.js");var loadBasisTranscoderPromise;function loadBasisTrascoderModule(_x59){return _loadBasisTrascoderModule.apply(this,arguments);}function _loadBasisTrascoderModule(){_loadBasisTrascoderModule=_asyncToGenerator(function*(options){var modules=options.modules||{};if(modules.basis){return modules.basis;}loadBasisTranscoderPromise=loadBasisTranscoderPromise||loadBasisTrascoder(options);return yield loadBasisTranscoderPromise;});return _loadBasisTrascoderModule.apply(this,arguments);}function loadBasisTrascoder(_x60){return _loadBasisTrascoder.apply(this,arguments);}function _loadBasisTrascoder(){_loadBasisTrascoder=_asyncToGenerator(function*(options){var BASIS=null;var wasmBinary=null;[BASIS,wasmBinary]=yield Promise.all([yield loadLibrary('basis_transcoder.js','textures',options),yield loadLibrary('basis_transcoder.wasm','textures',options)]);BASIS=BASIS||globalThis.BASIS;return yield initializeBasisTrascoderModule(BASIS,wasmBinary);});return _loadBasisTrascoder.apply(this,arguments);}function initializeBasisTrascoderModule(BasisModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(resolve=>{BasisModule(options).then(module=>{var{BasisFile,initializeBasis}=module;initializeBasis();resolve({BasisFile});});});}var loadBasisEncoderPromise;function loadBasisEncoderModule(_x61){return _loadBasisEncoderModule.apply(this,arguments);}function _loadBasisEncoderModule(){_loadBasisEncoderModule=_asyncToGenerator(function*(options){var modules=options.modules||{};if(modules.basisEncoder){return modules.basisEncoder;}loadBasisEncoderPromise=loadBasisEncoderPromise||loadBasisEncoder(options);return yield loadBasisEncoderPromise;});return _loadBasisEncoderModule.apply(this,arguments);}function loadBasisEncoder(_x62){return _loadBasisEncoder.apply(this,arguments);}function _loadBasisEncoder(){_loadBasisEncoder=_asyncToGenerator(function*(options){var BASIS_ENCODER=null;var wasmBinary=null;[BASIS_ENCODER,wasmBinary]=yield Promise.all([yield loadLibrary(BASIS_CDN_ENCODER_JS,'textures',options),yield loadLibrary(BASIS_CDN_ENCODER_WASM,'textures',options)]);BASIS_ENCODER=BASIS_ENCODER||globalThis.BASIS;return yield initializeBasisEncoderModule(BASIS_ENCODER,wasmBinary);});return _loadBasisEncoder.apply(this,arguments);}function initializeBasisEncoderModule(BasisEncoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(resolve=>{BasisEncoderModule(options).then(module=>{var{BasisFile,KTX2File,initializeBasis,BasisEncoder}=module;initializeBasis();resolve({BasisFile,KTX2File,BasisEncoder});});});}var GL_EXTENSIONS_CONSTANTS={COMPRESSED_RGB_S3TC_DXT1_EXT:0x83f0,COMPRESSED_RGBA_S3TC_DXT1_EXT:0x83f1,COMPRESSED_RGBA_S3TC_DXT3_EXT:0x83f2,COMPRESSED_RGBA_S3TC_DXT5_EXT:0x83f3,COMPRESSED_R11_EAC:0x9270,COMPRESSED_SIGNED_R11_EAC:0x9271,COMPRESSED_RG11_EAC:0x9272,COMPRESSED_SIGNED_RG11_EAC:0x9273,COMPRESSED_RGB8_ETC2:0x9274,COMPRESSED_RGBA8_ETC2_EAC:0x9275,COMPRESSED_SRGB8_ETC2:0x9276,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:0x9277,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9278,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9279,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:0x8c00,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:0x8c02,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:0x8c01,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:0x8c03,COMPRESSED_RGB_ETC1_WEBGL:0x8d64,COMPRESSED_RGB_ATC_WEBGL:0x8c92,COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:0x8c93,COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:0x87ee,COMPRESSED_RGBA_ASTC_4X4_KHR:0x93b0,COMPRESSED_RGBA_ASTC_5X4_KHR:0x93b1,COMPRESSED_RGBA_ASTC_5X5_KHR:0x93b2,COMPRESSED_RGBA_ASTC_6X5_KHR:0x93b3,COMPRESSED_RGBA_ASTC_6X6_KHR:0x93b4,COMPRESSED_RGBA_ASTC_8X5_KHR:0x93b5,COMPRESSED_RGBA_ASTC_8X6_KHR:0x93b6,COMPRESSED_RGBA_ASTC_8X8_KHR:0x93b7,COMPRESSED_RGBA_ASTC_10X5_KHR:0x93b8,COMPRESSED_RGBA_ASTC_10X6_KHR:0x93b9,COMPRESSED_RGBA_ASTC_10X8_KHR:0x93ba,COMPRESSED_RGBA_ASTC_10X10_KHR:0x93bb,COMPRESSED_RGBA_ASTC_12X10_KHR:0x93bc,COMPRESSED_RGBA_ASTC_12X12_KHR:0x93bd,COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR:0x93d0,COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR:0x93d1,COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR:0x93d2,COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR:0x93d3,COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR:0x93d4,COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR:0x93d5,COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR:0x93d6,COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR:0x93d7,COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR:0x93d8,COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR:0x93d9,COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR:0x93da,COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR:0x93db,COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR:0x93dc,COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR:0x93dd,COMPRESSED_RED_RGTC1_EXT:0x8dbb,COMPRESSED_SIGNED_RED_RGTC1_EXT:0x8dbc,COMPRESSED_RED_GREEN_RGTC2_EXT:0x8dbd,COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:0x8dbe,COMPRESSED_SRGB_S3TC_DXT1_EXT:0x8c4c,COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:0x8c4d,COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:0x8c4e,COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:0x8c4f};var BROWSER_PREFIXES=['','WEBKIT_','MOZ_'];var WEBGL_EXTENSIONS={WEBGL_compressed_texture_s3tc:'dxt',WEBGL_compressed_texture_s3tc_srgb:'dxt-srgb',WEBGL_compressed_texture_etc1:'etc1',WEBGL_compressed_texture_etc:'etc2',WEBGL_compressed_texture_pvrtc:'pvrtc',WEBGL_compressed_texture_atc:'atc',WEBGL_compressed_texture_astc:'astc',EXT_texture_compression_rgtc:'rgtc'};var formats=null;function getSupportedGPUTextureFormats(gl){if(!formats){gl=gl||getWebGLContext()||undefined;formats=new Set();for(var prefix of BROWSER_PREFIXES){for(var extension in WEBGL_EXTENSIONS){if(gl&&gl.getExtension("".concat(prefix).concat(extension))){var gpuTextureFormat=WEBGL_EXTENSIONS[extension];formats.add(gpuTextureFormat);}}}}return formats;}function getWebGLContext(){try{var canvas=document.createElement('canvas');return canvas.getContext('webgl');}catch(error){return null;}}var n$2,i$3,s$1,a$2,r$1,o$2,l$2,f$1;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n$2||(n$2={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i$3||(i$3={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s$1||(s$1={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a$2||(a$2={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r$1||(r$1={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o$2||(o$2={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l$2||(l$2={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f$1||(f$1={}));var KTX2_ID=[0xab,0x4b,0x54,0x58,0x20,0x32,0x30,0xbb,0x0d,0x0a,0x1a,0x0a];function isKTX(data){var id=new Uint8Array(data);var notKTX=id.byteLength<KTX2_ID.length||id[0]!==KTX2_ID[0]||id[1]!==KTX2_ID[1]||id[2]!==KTX2_ID[2]||id[3]!==KTX2_ID[3]||id[4]!==KTX2_ID[4]||id[5]!==KTX2_ID[5]||id[6]!==KTX2_ID[6]||id[7]!==KTX2_ID[7]||id[8]!==KTX2_ID[8]||id[9]!==KTX2_ID[9]||id[10]!==KTX2_ID[10]||id[11]!==KTX2_ID[11];return !notKTX;}var OutputFormat={etc1:{basisFormat:0,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_ETC1_WEBGL},etc2:{basisFormat:1,compressed:true},bc1:{basisFormat:2,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_S3TC_DXT1_EXT},bc3:{basisFormat:3,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_S3TC_DXT5_EXT},bc4:{basisFormat:4,compressed:true},bc5:{basisFormat:5,compressed:true},'bc7-m6-opaque-only':{basisFormat:6,compressed:true},'bc7-m5':{basisFormat:7,compressed:true},'pvrtc1-4-rgb':{basisFormat:8,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG},'pvrtc1-4-rgba':{basisFormat:9,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG},'astc-4x4':{basisFormat:10,compressed:true,format:GL_EXTENSIONS_CONSTANTS.COMPRESSED_RGBA_ASTC_4X4_KHR},'atc-rgb':{basisFormat:11,compressed:true},'atc-rgba-interpolated-alpha':{basisFormat:12,compressed:true},rgba32:{basisFormat:13,compressed:false},rgb565:{basisFormat:14,compressed:false},bgr565:{basisFormat:15,compressed:false},rgba4444:{basisFormat:16,compressed:false}};function parseBasis(_x63,_x64){return _parseBasis.apply(this,arguments);}function _parseBasis(){_parseBasis=_asyncToGenerator(function*(data,options){if(options.basis.containerFormat==='auto'){if(isKTX(data)){var fileConstructors=yield loadBasisEncoderModule(options);return parseKTX2File(fileConstructors.KTX2File,data,options);}var{BasisFile}=yield loadBasisTrascoderModule(options);return parseBasisFile(BasisFile,data,options);}switch(options.basis.module){case'encoder':var _fileConstructors=yield loadBasisEncoderModule(options);switch(options.basis.containerFormat){case'ktx2':return parseKTX2File(_fileConstructors.KTX2File,data,options);case'basis':default:return parseBasisFile(_fileConstructors.BasisFile,data,options);}case'transcoder':default:var{BasisFile:_BasisFile}=yield loadBasisTrascoderModule(options);return parseBasisFile(_BasisFile,data,options);}});return _parseBasis.apply(this,arguments);}function parseBasisFile(BasisFile,data,options){var basisFile=new BasisFile(new Uint8Array(data));try{if(!basisFile.startTranscoding()){return null;}var imageCount=basisFile.getNumImages();var images=[];for(var imageIndex=0;imageIndex<imageCount;imageIndex++){var levelsCount=basisFile.getNumLevels(imageIndex);var levels=[];for(var levelIndex=0;levelIndex<levelsCount;levelIndex++){levels.push(transcodeImage(basisFile,imageIndex,levelIndex,options));}images.push(levels);}return images;}finally{basisFile.close();basisFile.delete();}}function transcodeImage(basisFile,imageIndex,levelIndex,options){var width=basisFile.getImageWidth(imageIndex,levelIndex);var height=basisFile.getImageHeight(imageIndex,levelIndex);var hasAlpha=basisFile.getHasAlpha();var{compressed,format,basisFormat}=getBasisOptions(options,hasAlpha);var decodedSize=basisFile.getImageTranscodedSizeInBytes(imageIndex,levelIndex,basisFormat);var decodedData=new Uint8Array(decodedSize);if(!basisFile.transcodeImage(decodedData,imageIndex,levelIndex,basisFormat,0,0)){return null;}return {width,height,data:decodedData,compressed,hasAlpha,format};}function parseKTX2File(KTX2File,data,options){var ktx2File=new KTX2File(new Uint8Array(data));try{if(!ktx2File.startTranscoding()){return null;}var levelsCount=ktx2File.getLevels();var levels=[];for(var levelIndex=0;levelIndex<levelsCount;levelIndex++){levels.push(transcodeKTX2Image(ktx2File,levelIndex,options));break;}return levels;}finally{ktx2File.close();ktx2File.delete();}}function transcodeKTX2Image(ktx2File,levelIndex,options){var{alphaFlag,height,width}=ktx2File.getImageLevelInfo(levelIndex,0,0);var{compressed,format,basisFormat}=getBasisOptions(options,alphaFlag);var decodedSize=ktx2File.getImageTranscodedSizeInBytes(levelIndex,0,0,basisFormat);var decodedData=new Uint8Array(decodedSize);if(!ktx2File.transcodeImage(decodedData,levelIndex,0,0,basisFormat,0,-1,-1)){return null;}return {width,height,data:decodedData,compressed,alphaFlag,format};}function getBasisOptions(options,hasAlpha){var format=options&&options.basis&&options.basis.format;if(format==='auto'){format=selectSupportedBasisFormat();}if(typeof format==='object'){format=hasAlpha?format.alpha:format.noAlpha;}format=format.toLowerCase();return OutputFormat[format];}function selectSupportedBasisFormat(){var supportedFormats=getSupportedGPUTextureFormats();if(supportedFormats.has('astc')){return 'astc-4x4';}else if(supportedFormats.has('dxt')){return {alpha:'bc3',noAlpha:'bc1'};}else if(supportedFormats.has('pvrtc')){return {alpha:'pvrtc1-4-rgba',noAlpha:'pvrtc1-4-rgb'};}else if(supportedFormats.has('etc1')){return 'etc1';}else if(supportedFormats.has('etc2')){return 'etc2';}return 'rgb565';}var BasisWorkerLoader={name:'Basis',id:'basis',module:'textures',version:VERSION$2,worker:true,extensions:['basis','ktx2'],mimeTypes:['application/octet-stream','image/ktx2'],tests:['sB'],binary:true,options:{basis:{format:'auto',libraryPath:'libs/',containerFormat:'auto',module:'transcoder'}}};var BasisLoader=_objectSpread2(_objectSpread2({},BasisWorkerLoader),{},{parse:parseBasis});var VERSION="3.1.4";var{_parseImageNode}=globalThis;var IMAGE_SUPPORTED=typeof Image!=='undefined';var IMAGE_BITMAP_SUPPORTED=typeof ImageBitmap!=='undefined';var NODE_IMAGE_SUPPORTED=Boolean(_parseImageNode);var DATA_SUPPORTED=isBrowser$2?true:NODE_IMAGE_SUPPORTED;function isImageTypeSupported(type){switch(type){case'auto':return IMAGE_BITMAP_SUPPORTED||IMAGE_SUPPORTED||DATA_SUPPORTED;case'imagebitmap':return IMAGE_BITMAP_SUPPORTED;case'image':return IMAGE_SUPPORTED;case'data':return DATA_SUPPORTED;default:throw new Error("@loaders.gl/images: image ".concat(type," not supported in this environment"));}}function getDefaultImageType(){if(IMAGE_BITMAP_SUPPORTED){return 'imagebitmap';}if(IMAGE_SUPPORTED){return 'image';}if(DATA_SUPPORTED){return 'data';}throw new Error('Install \'@loaders.gl/polyfills\' to parse images under Node.js');}function getImageType(image){var format=getImageTypeOrNull(image);if(!format){throw new Error('Not an image');}return format;}function getImageData(image){switch(getImageType(image)){case'data':return image;case'image':case'imagebitmap':var canvas=document.createElement('canvas');var context=canvas.getContext('2d');if(!context){throw new Error('getImageData');}canvas.width=image.width;canvas.height=image.height;context.drawImage(image,0,0);return context.getImageData(0,0,image.width,image.height);default:throw new Error('getImageData');}}function getImageTypeOrNull(image){if(typeof ImageBitmap!=='undefined'&&image instanceof ImageBitmap){return 'imagebitmap';}if(typeof Image!=='undefined'&&image instanceof Image){return 'image';}if(image&&typeof image==='object'&&image.data&&image.width&&image.height){return 'data';}return null;}var SVG_DATA_URL_PATTERN=/^data:image\/svg\+xml/;var SVG_URL_PATTERN=/\.svg((\?|#).*)?$/;function isSVG(url){return url&&(SVG_DATA_URL_PATTERN.test(url)||SVG_URL_PATTERN.test(url));}function getBlobOrSVGDataUrl(arrayBuffer,url){if(isSVG(url)){var textDecoder=new TextDecoder();var xmlText=textDecoder.decode(arrayBuffer);try{if(typeof unescape==='function'&&typeof encodeURIComponent==='function'){xmlText=unescape(encodeURIComponent(xmlText));}}catch(error){throw new Error(error.message);}var src="data:image/svg+xml;base64,".concat(btoa(xmlText));return src;}return getBlob(arrayBuffer,url);}function getBlob(arrayBuffer,url){if(isSVG(url)){throw new Error('SVG cannot be parsed directly to imagebitmap');}return new Blob([new Uint8Array(arrayBuffer)]);}function parseToImage(_x65,_x66,_x67){return _parseToImage.apply(this,arguments);}function _parseToImage(){_parseToImage=_asyncToGenerator(function*(arrayBuffer,options,url){var blobOrDataUrl=getBlobOrSVGDataUrl(arrayBuffer,url);var URL=self.URL||self.webkitURL;var objectUrl=typeof blobOrDataUrl!=='string'&&URL.createObjectURL(blobOrDataUrl);try{return yield loadToImage(objectUrl||blobOrDataUrl,options);}finally{if(objectUrl){URL.revokeObjectURL(objectUrl);}}});return _parseToImage.apply(this,arguments);}function loadToImage(_x68,_x69){return _loadToImage.apply(this,arguments);}function _loadToImage(){_loadToImage=_asyncToGenerator(function*(url,options){var image=new Image();image.src=url;if(options.image&&options.image.decode&&image.decode){yield image.decode();return image;}return yield new Promise((resolve,reject)=>{try{image.onload=()=>resolve(image);image.onerror=err=>reject(new Error("Could not load image ".concat(url,": ").concat(err)));}catch(error){reject(error);}});});return _loadToImage.apply(this,arguments);}var EMPTY_OBJECT={};var imagebitmapOptionsSupported=true;function parseToImageBitmap(_x70,_x71,_x72){return _parseToImageBitmap.apply(this,arguments);}function _parseToImageBitmap(){_parseToImageBitmap=_asyncToGenerator(function*(arrayBuffer,options,url){var blob;if(isSVG(url)){var image=yield parseToImage(arrayBuffer,options,url);blob=image;}else {blob=getBlob(arrayBuffer,url);}var imagebitmapOptions=options&&options.imagebitmap;return yield safeCreateImageBitmap(blob,imagebitmapOptions);});return _parseToImageBitmap.apply(this,arguments);}function safeCreateImageBitmap(_x73){return _safeCreateImageBitmap.apply(this,arguments);}function _safeCreateImageBitmap(){_safeCreateImageBitmap=_asyncToGenerator(function*(blob){var imagebitmapOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(isEmptyObject(imagebitmapOptions)||!imagebitmapOptionsSupported){imagebitmapOptions=null;}if(imagebitmapOptions){try{return yield createImageBitmap(blob,imagebitmapOptions);}catch(error){console.warn(error);imagebitmapOptionsSupported=false;}}return yield createImageBitmap(blob);});return _safeCreateImageBitmap.apply(this,arguments);}function isEmptyObject(object){for(var key in object||EMPTY_OBJECT){return false;}return true;}var BIG_ENDIAN=false;var LITTLE_ENDIAN=true;function getBinaryImageMetadata(binaryData){var dataView=toDataView(binaryData);return getPngMetadata(dataView)||getJpegMetadata(dataView)||getGifMetadata(dataView)||getBmpMetadata(dataView);}function getPngMetadata(binaryData){var dataView=toDataView(binaryData);var isPng=dataView.byteLength>=24&&dataView.getUint32(0,BIG_ENDIAN)===0x89504e47;if(!isPng){return null;}return {mimeType:'image/png',width:dataView.getUint32(16,BIG_ENDIAN),height:dataView.getUint32(20,BIG_ENDIAN)};}function getGifMetadata(binaryData){var dataView=toDataView(binaryData);var isGif=dataView.byteLength>=10&&dataView.getUint32(0,BIG_ENDIAN)===0x47494638;if(!isGif){return null;}return {mimeType:'image/gif',width:dataView.getUint16(6,LITTLE_ENDIAN),height:dataView.getUint16(8,LITTLE_ENDIAN)};}function getBmpMetadata(binaryData){var dataView=toDataView(binaryData);var isBmp=dataView.byteLength>=14&&dataView.getUint16(0,BIG_ENDIAN)===0x424d&&dataView.getUint32(2,LITTLE_ENDIAN)===dataView.byteLength;if(!isBmp){return null;}return {mimeType:'image/bmp',width:dataView.getUint32(18,LITTLE_ENDIAN),height:dataView.getUint32(22,LITTLE_ENDIAN)};}function getJpegMetadata(binaryData){var dataView=toDataView(binaryData);var isJpeg=dataView.byteLength>=3&&dataView.getUint16(0,BIG_ENDIAN)===0xffd8&&dataView.getUint8(2)===0xff;if(!isJpeg){return null;}var{tableMarkers,sofMarkers}=getJpegMarkers();var i=2;while(i+9<dataView.byteLength){var _marker=dataView.getUint16(i,BIG_ENDIAN);if(sofMarkers.has(_marker)){return {mimeType:'image/jpeg',height:dataView.getUint16(i+5,BIG_ENDIAN),width:dataView.getUint16(i+7,BIG_ENDIAN)};}if(!tableMarkers.has(_marker)){return null;}i+=2;i+=dataView.getUint16(i,BIG_ENDIAN);}return null;}function getJpegMarkers(){var tableMarkers=new Set([0xffdb,0xffc4,0xffcc,0xffdd,0xfffe]);for(var _i49=0xffe0;_i49<0xfff0;++_i49){tableMarkers.add(_i49);}var sofMarkers=new Set([0xffc0,0xffc1,0xffc2,0xffc3,0xffc5,0xffc6,0xffc7,0xffc9,0xffca,0xffcb,0xffcd,0xffce,0xffcf,0xffde]);return {tableMarkers,sofMarkers};}function toDataView(data){if(data instanceof DataView){return data;}if(ArrayBuffer.isView(data)){return new DataView(data.buffer);}if(data instanceof ArrayBuffer){return new DataView(data);}throw new Error('toDataView');}function parseToNodeImage(_x74,_x75){return _parseToNodeImage.apply(this,arguments);}function _parseToNodeImage(){_parseToNodeImage=_asyncToGenerator(function*(arrayBuffer,options){var{mimeType}=getBinaryImageMetadata(arrayBuffer)||{};var _parseImageNode=globalThis._parseImageNode;assert$7(_parseImageNode);return yield _parseImageNode(arrayBuffer,mimeType);});return _parseToNodeImage.apply(this,arguments);}function parseImage(_x76,_x77,_x78){return _parseImage.apply(this,arguments);}function _parseImage(){_parseImage=_asyncToGenerator(function*(arrayBuffer,options,context){options=options||{};var imageOptions=options.image||{};var imageType=imageOptions.type||'auto';var{url}=context||{};var loadType=getLoadableImageType(imageType);var image;switch(loadType){case'imagebitmap':image=yield parseToImageBitmap(arrayBuffer,options,url);break;case'image':image=yield parseToImage(arrayBuffer,options,url);break;case'data':image=yield parseToNodeImage(arrayBuffer);break;default:assert$7(false);}if(imageType==='data'){image=getImageData(image);}return image;});return _parseImage.apply(this,arguments);}function getLoadableImageType(type){switch(type){case'auto':case'data':return getDefaultImageType();default:isImageTypeSupported(type);return type;}}var EXTENSIONS$1=['png','jpg','jpeg','gif','webp','bmp','ico','svg'];var MIME_TYPES=['image/png','image/jpeg','image/gif','image/webp','image/bmp','image/vnd.microsoft.icon','image/svg+xml'];var DEFAULT_IMAGE_LOADER_OPTIONS={image:{type:'auto',decode:true}};var ImageLoader$1={id:'image',module:'images',name:'Images',version:VERSION,mimeTypes:MIME_TYPES,extensions:EXTENSIONS$1,parse:parseImage,tests:[arrayBuffer=>Boolean(getBinaryImageMetadata(new DataView(arrayBuffer)))],options:DEFAULT_IMAGE_LOADER_OPTIONS};var NODE_FORMAT_SUPPORT=['image/png','image/jpeg','image/gif'];var mimeTypeSupported={};function _isImageFormatSupported(mimeType){if(mimeTypeSupported[mimeType]===undefined){mimeTypeSupported[mimeType]=checkFormatSupport(mimeType);}return mimeTypeSupported[mimeType];}function checkFormatSupport(mimeType){switch(mimeType){case'image/webp':return checkWebPSupport();case'image/svg':return isBrowser$2;default:if(!isBrowser$2){var{_parseImageNode:_parseImageNode2}=globalThis;return Boolean(_parseImageNode2)&&NODE_FORMAT_SUPPORT.includes(mimeType);}return true;}}function checkWebPSupport(){if(!isBrowser$2){return false;}try{var element=document.createElement('canvas');return element.toDataURL('image/webp').indexOf('data:image/webp')===0;}catch(_unused){return false;}}function assert$1(condition,message){if(!condition){throw new Error(message||'assert failed: gltf');}}function resolveUrl(url,options){var absolute=url.startsWith('data:')||url.startsWith('http:')||url.startsWith('https:');if(absolute){return url;}var baseUrl=options.baseUri||options.uri;if(!baseUrl){throw new Error("'baseUri' must be provided to resolve relative url ".concat(url));}return baseUrl.substr(0,baseUrl.lastIndexOf('/')+1)+url;}function getTypedArrayForBufferView(json,buffers,bufferViewIndex){var bufferView=json.bufferViews[bufferViewIndex];assert$1(bufferView);var bufferIndex=bufferView.buffer;var binChunk=buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}var TYPES=['SCALAR','VEC2','VEC3','VEC4'];var ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]];var ARRAY_TO_COMPONENT_TYPE=new Map(ARRAY_CONSTRUCTOR_TO_WEBGL_CONSTANT);var ATTRIBUTE_TYPE_TO_COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function getAccessorTypeFromSize(size){var type=TYPES[size-1];return type||TYPES[0];}function getComponentTypeFromArray(typedArray){var componentType=ARRAY_TO_COMPONENT_TYPE.get(typedArray.constructor);if(!componentType){throw new Error('Illegal typed array');}return componentType;}function getAccessorArrayTypeAndLength(accessor,bufferView){var ArrayType=ATTRIBUTE_COMPONENT_TYPE_TO_ARRAY[accessor.componentType];var components=ATTRIBUTE_TYPE_TO_COMPONENTS[accessor.type];var bytesPerComponent=ATTRIBUTE_COMPONENT_TYPE_TO_BYTE_SIZE[accessor.componentType];var length=accessor.count*components;var byteLength=accessor.count*components*bytesPerComponent;assert$1(byteLength>=0&&byteLength<=bufferView.byteLength);return {ArrayType,length,byteLength};}var DEFAULT_GLTF_JSON={asset:{version:'2.0',generator:'loaders.gl'},buffers:[]};class GLTFScenegraph{constructor(gltf){_defineProperty$1(this,"gltf",void 0);_defineProperty$1(this,"sourceBuffers",void 0);_defineProperty$1(this,"byteLength",void 0);this.gltf=gltf||{json:_objectSpread2({},DEFAULT_GLTF_JSON),buffers:[]};this.sourceBuffers=[];this.byteLength=0;if(this.gltf.buffers&&this.gltf.buffers[0]){this.byteLength=this.gltf.buffers[0].byteLength;this.sourceBuffers=[this.gltf.buffers[0]];}}get json(){return this.gltf.json;}getApplicationData(key){var data=this.json[key];return data;}getExtraData(key){var extras=this.json.extras||{};return extras[key];}getExtension(extensionName){var isExtension=this.getUsedExtensions().find(name=>name===extensionName);var extensions=this.json.extensions||{};return isExtension?extensions[extensionName]||true:null;}getRequiredExtension(extensionName){var isRequired=this.getRequiredExtensions().find(name=>name===extensionName);return isRequired?this.getExtension(extensionName):null;}getRequiredExtensions(){return this.json.extensionsRequired||[];}getUsedExtensions(){return this.json.extensionsUsed||[];}getObjectExtension(object,extensionName){var extensions=object.extensions||{};return extensions[extensionName];}getScene(index){return this.getObject('scenes',index);}getNode(index){return this.getObject('nodes',index);}getSkin(index){return this.getObject('skins',index);}getMesh(index){return this.getObject('meshes',index);}getMaterial(index){return this.getObject('materials',index);}getAccessor(index){return this.getObject('accessors',index);}getTexture(index){return this.getObject('textures',index);}getSampler(index){return this.getObject('samplers',index);}getImage(index){return this.getObject('images',index);}getBufferView(index){return this.getObject('bufferViews',index);}getBuffer(index){return this.getObject('buffers',index);}getObject(array,index){if(typeof index==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){throw new Error("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}getTypedArrayForBufferView(bufferView){bufferView=this.getBufferView(bufferView);var bufferIndex=bufferView.buffer;var binChunk=this.gltf.buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}getTypedArrayForAccessor(accessor){accessor=this.getAccessor(accessor);var bufferView=this.getBufferView(accessor.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var{ArrayType,length}=getAccessorArrayTypeAndLength(accessor,bufferView);var byteOffset=bufferView.byteOffset+accessor.byteOffset;return new ArrayType(arrayBuffer,byteOffset,length);}getTypedArrayForImageData(image){image=this.getAccessor(image);var bufferView=this.getBufferView(image.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var byteOffset=bufferView.byteOffset||0;return new Uint8Array(arrayBuffer,byteOffset,bufferView.byteLength);}addApplicationData(key,data){this.json[key]=data;return this;}addExtraData(key,data){this.json.extras=this.json.extras||{};this.json.extras[key]=data;return this;}addObjectExtension(object,extensionName,data){object.extensions=object.extensions||{};object.extensions[extensionName]=data;this.registerUsedExtension(extensionName);return this;}setObjectExtension(object,extensionName,data){var extensions=object.extensions||{};extensions[extensionName]=data;}removeObjectExtension(object,extensionName){var extensions=object.extensions||{};var extension=extensions[extensionName];delete extensions[extensionName];return extension;}addExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.json.extensions=this.json.extensions||{};this.json.extensions[extensionName]=extensionData;this.registerUsedExtension(extensionName);return extensionData;}addRequiredExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.addExtension(extensionName,extensionData);this.registerRequiredExtension(extensionName);return extensionData;}registerUsedExtension(extensionName){this.json.extensionsUsed=this.json.extensionsUsed||[];if(!this.json.extensionsUsed.find(ext=>ext===extensionName)){this.json.extensionsUsed.push(extensionName);}}registerRequiredExtension(extensionName){this.registerUsedExtension(extensionName);this.json.extensionsRequired=this.json.extensionsRequired||[];if(!this.json.extensionsRequired.find(ext=>ext===extensionName)){this.json.extensionsRequired.push(extensionName);}}removeExtension(extensionName){if(this.json.extensionsRequired){this._removeStringFromArray(this.json.extensionsRequired,extensionName);}if(this.json.extensionsUsed){this._removeStringFromArray(this.json.extensionsUsed,extensionName);}if(this.json.extensions){delete this.json.extensions[extensionName];}}setDefaultScene(sceneIndex){this.json.scene=sceneIndex;}addScene(scene){var{nodeIndices}=scene;this.json.scenes=this.json.scenes||[];this.json.scenes.push({nodes:nodeIndices});return this.json.scenes.length-1;}addNode(node){var{meshIndex,matrix}=node;this.json.nodes=this.json.nodes||[];var nodeData={mesh:meshIndex};if(matrix){nodeData.matrix=matrix;}this.json.nodes.push(nodeData);return this.json.nodes.length-1;}addMesh(mesh){var{attributes,indices,material,mode=4}=mesh;var accessors=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessors,mode}]};if(indices){var indicesAccessor=this._addIndices(indices);glTFMesh.primitives[0].indices=indicesAccessor;}if(Number.isFinite(material)){glTFMesh.primitives[0].material=material;}this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}addPointCloud(attributes){var accessorIndices=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessorIndices,mode:0}]};this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}addImage(imageData,mimeTypeOpt){var metadata=getBinaryImageMetadata(imageData);var mimeType=mimeTypeOpt||(metadata===null||metadata===void 0?void 0:metadata.mimeType);var bufferViewIndex=this.addBufferView(imageData);var glTFImage={bufferView:bufferViewIndex,mimeType};this.json.images=this.json.images||[];this.json.images.push(glTFImage);return this.json.images.length-1;}addBufferView(buffer){var byteLength=buffer.byteLength;assert$1(Number.isFinite(byteLength));this.sourceBuffers=this.sourceBuffers||[];this.sourceBuffers.push(buffer);var glTFBufferView={buffer:0,byteOffset:this.byteLength,byteLength};this.byteLength+=padToNBytes(byteLength,4);this.json.bufferViews=this.json.bufferViews||[];this.json.bufferViews.push(glTFBufferView);return this.json.bufferViews.length-1;}addAccessor(bufferViewIndex,accessor){var glTFAccessor={bufferView:bufferViewIndex,type:getAccessorTypeFromSize(accessor.size),componentType:accessor.componentType,count:accessor.count,max:accessor.max,min:accessor.min};this.json.accessors=this.json.accessors||[];this.json.accessors.push(glTFAccessor);return this.json.accessors.length-1;}addBinaryBuffer(sourceBuffer){var accessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{size:3};var bufferViewIndex=this.addBufferView(sourceBuffer);var minMax={min:accessor.min,max:accessor.max};if(!minMax.min||!minMax.max){minMax=this._getAccessorMinMax(sourceBuffer,accessor.size);}var accessorDefaults={size:accessor.size,componentType:getComponentTypeFromArray(sourceBuffer),count:Math.round(sourceBuffer.length/accessor.size),min:minMax.min,max:minMax.max};return this.addAccessor(bufferViewIndex,Object.assign(accessorDefaults,accessor));}addTexture(texture){var{imageIndex}=texture;var glTFTexture={source:imageIndex};this.json.textures=this.json.textures||[];this.json.textures.push(glTFTexture);return this.json.textures.length-1;}addMaterial(pbrMaterialInfo){this.json.materials=this.json.materials||[];this.json.materials.push(pbrMaterialInfo);return this.json.materials.length-1;}createBinaryChunk(){var _this$json,_this$json$buffers;this.gltf.buffers=[];var totalByteLength=this.byteLength;var arrayBuffer=new ArrayBuffer(totalByteLength);var targetArray=new Uint8Array(arrayBuffer);var dstByteOffset=0;for(var sourceBuffer of this.sourceBuffers||[]){dstByteOffset=copyToArray(sourceBuffer,targetArray,dstByteOffset);}if((_this$json=this.json)!==null&&_this$json!==void 0&&(_this$json$buffers=_this$json.buffers)!==null&&_this$json$buffers!==void 0&&_this$json$buffers[0]){this.json.buffers[0].byteLength=totalByteLength;}else {this.json.buffers=[{byteLength:totalByteLength}];}this.gltf.binary=arrayBuffer;this.sourceBuffers=[arrayBuffer];}_removeStringFromArray(array,string){var found=true;while(found){var index=array.indexOf(string);if(index>-1){array.splice(index,1);}else {found=false;}}}_addAttributes(){var attributes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var result={};for(var attributeKey in attributes){var attributeData=attributes[attributeKey];var attrName=this._getGltfAttributeName(attributeKey);var accessor=this.addBinaryBuffer(attributeData.value,attributeData);result[attrName]=accessor;}return result;}_addIndices(indices){return this.addBinaryBuffer(indices,{size:1});}_getGltfAttributeName(attributeName){switch(attributeName.toLowerCase()){case'position':case'positions':case'vertices':return 'POSITION';case'normal':case'normals':return 'NORMAL';case'color':case'colors':return 'COLOR_0';case'texcoord':case'texcoords':return 'TEXCOORD_0';default:return attributeName;}}_getAccessorMinMax(buffer,size){var result={min:null,max:null};if(buffer.length<size){return result;}result.min=[];result.max=[];var initValues=buffer.subarray(0,size);for(var value of initValues){result.min.push(value);result.max.push(value);}for(var index=size;index<buffer.length;index+=size){for(var componentIndex=0;componentIndex<size;componentIndex++){result.min[0+componentIndex]=Math.min(result.min[0+componentIndex],buffer[index+componentIndex]);result.max[0+componentIndex]=Math.max(result.max[0+componentIndex],buffer[index+componentIndex]);}}return result;}}var isWebAssemblySupported=typeof WebAssembly!=='object';var wasm_base='B9h9z9tFBBBF8fL9gBB9gLaaaaaFa9gEaaaB9gFaFa9gEaaaFaEMcBFFFGGGEIIILF9wFFFLEFBFKNFaFCx/IFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBF8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBGy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBEn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBIi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBKI9z9iqlBOc+x8ycGBM/qQFTa8jUUUUBCU/EBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAGTkUUUBRNCUoBAG9uC/wgBZHKCUGAKCUG9JyRVAECFJRICBRcGXEXAcAF9PQFAVAFAclAcAVJAF9JyRMGXGXAG9FQBAMCbJHKC9wZRSAKCIrCEJCGrRQANCUGJRfCBRbAIRTEXGXAOATlAQ9PQBCBRISEMATAQJRIGXAS9FQBCBRtCBREEXGXAOAIlCi9PQBCBRISLMANCU/CBJAEJRKGXGXGXGXGXATAECKrJ2BBAtCKZrCEZfIBFGEBMAKhB83EBAKCNJhB83EBSEMAKAI2BIAI2BBHmCKrHYAYCE6HYy86BBAKCFJAICIJAYJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCGJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCEJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCIJAYAmJHY2BBAI2BFHmCKrHPAPCE6HPy86BBAKCLJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCKJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCOJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCNJAYAmJHY2BBAI2BGHmCKrHPAPCE6HPy86BBAKCVJAYAPJHY2BBAmCIrCEZHPAPCE6HPy86BBAKCcJAYAPJHY2BBAmCGrCEZHPAPCE6HPy86BBAKCMJAYAPJHY2BBAmCEZHmAmCE6Hmy86BBAKCSJAYAmJHm2BBAI2BEHICKrHYAYCE6HYy86BBAKCQJAmAYJHm2BBAICIrCEZHYAYCE6HYy86BBAKCfJAmAYJHm2BBAICGrCEZHYAYCE6HYy86BBAKCbJAmAYJHK2BBAICEZHIAICE6HIy86BBAKAIJRISGMAKAI2BNAI2BBHmCIrHYAYCb6HYy86BBAKCFJAICNJAYJHY2BBAmCbZHmAmCb6Hmy86BBAKCGJAYAmJHm2BBAI2BFHYCIrHPAPCb6HPy86BBAKCEJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCIJAmAYJHm2BBAI2BGHYCIrHPAPCb6HPy86BBAKCLJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCKJAmAYJHm2BBAI2BEHYCIrHPAPCb6HPy86BBAKCOJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCNJAmAYJHm2BBAI2BIHYCIrHPAPCb6HPy86BBAKCVJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCcJAmAYJHm2BBAI2BLHYCIrHPAPCb6HPy86BBAKCMJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCSJAmAYJHm2BBAI2BKHYCIrHPAPCb6HPy86BBAKCQJAmAPJHm2BBAYCbZHYAYCb6HYy86BBAKCfJAmAYJHm2BBAI2BOHICIrHYAYCb6HYy86BBAKCbJAmAYJHK2BBAICbZHIAICb6HIy86BBAKAIJRISFMAKAI8pBB83BBAKCNJAICNJ8pBB83BBAICTJRIMAtCGJRtAECTJHEAS9JQBMMGXAIQBCBRISEMGXAM9FQBANAbJ2BBRtCBRKAfREEXAEANCU/CBJAKJ2BBHTCFrCBATCFZl9zAtJHt86BBAEAGJREAKCFJHKAM9HQBMMAfCFJRfAIRTAbCFJHbAG9HQBMMABAcAG9sJANCUGJAMAG9sTkUUUBpANANCUGJAMCaJAG9sJAGTkUUUBpMAMCBAIyAcJRcAIQBMC9+RKSFMCBC99AOAIlAGCAAGCA9Ly6yRKMALCU/EBJ8kUUUUBAKM+OmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUFT+JUUUBpALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM+lLKFaF99GaG99FaG99GXGXAGCI9HQBAF9FQFEXGXGX9DBBB8/9DBBB+/ABCGJHG1BB+yAB1BBHE+yHI+L+TABCFJHL1BBHK+yHO+L+THN9DBBBB9gHVyAN9DBB/+hANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE86BBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG86BBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG86BBABCIJRBAFCaJHFQBSGMMAF9FQBEXGXGX9DBBB8/9DBBB+/ABCIJHG8uFB+yAB8uFBHE+yHI+L+TABCGJHL8uFBHK+yHO+L+THN9DBBBB9gHVyAN9DB/+g6ANAN+U9DBBBBANAVyHcAc+MHMAECa3yAI+SHIAI+UAcAMAKCa3yAO+SHcAc+U+S+S+R+VHO+U+SHN+L9DBBB9P9d9FQBAN+oRESFMCUUUU94REMAGAE87FBGXGX9DBBB8/9DBBB+/Ac9DBBBB9gyAcAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMALAG87FBGXGX9DBBB8/9DBBB+/AI9DBBBB9gyAIAO+U+SHN+L9DBBB9P9d9FQBAN+oRGSFMCUUUU94RGMABAG87FBABCNJRBAFCaJHFQBMMM/SEIEaE99EaF99GXAF9FQBCBREABRIEXGXGX9D/zI818/AICKJ8uFBHLCEq+y+VHKAI8uFB+y+UHO9DB/+g6+U9DBBB8/9DBBB+/AO9DBBBB9gy+SHN+L9DBBB9P9d9FQBAN+oRVSFMCUUUU94RVMAICIJ8uFBRcAICGJ8uFBRMABALCFJCEZAEqCFWJAV87FBGXGXAKAM+y+UHN9DB/+g6+U9DBBB8/9DBBB+/AN9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRMSFMCUUUU94RMMABALCGJCEZAEqCFWJAM87FBGXGXAKAc+y+UHK9DB/+g6+U9DBBB8/9DBBB+/AK9DBBBB9gy+SHS+L9DBBB9P9d9FQBAS+oRcSFMCUUUU94RcMABALCaJCEZAEqCFWJAc87FBGXGX9DBBU8/AOAO+U+TANAN+U+TAKAK+U+THO9DBBBBAO9DBBBB9gy+R9DB/+g6+U9DBBB8/+SHO+L9DBBB9P9d9FQBAO+oRcSFMCUUUU94RcMABALCEZAEqCFWJAc87FBAICNJRIAECIJREAFCaJHFQBMMM9JBGXAGCGrAF9sHF9FQBEXABAB8oGBHGCNWCN91+yAGCi91CnWCUUU/8EJ+++U84GBABCIJRBAFCaJHFQBMMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEM/lFFFaGXGXAFABqCEZ9FQBABRESFMGXGXAGCT9PQBABRESFMABREEXAEAF8oGBjGBAECIJAFCIJ8oGBjGBAECNJAFCNJ8oGBjGBAECSJAFCSJ8oGBjGBAECTJREAFCTJRFAGC9wJHGCb9LQBMMAGCI9JQBEXAEAF8oGBjGBAFCIJRFAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF2BB86BBAECFJREAFCFJRFAGCaJHGQBMMABMoFFGaGXGXABCEZ9FQBABRESFMAFCgFZC+BwsN9sRIGXGXAGCT9PQBABRESFMABREEXAEAIjGBAECSJAIjGBAECNJAIjGBAECIJAIjGBAECTJREAGC9wJHGCb9LQBMMAGCI9JQBEXAEAIjGBAECIJREAGC98JHGCE9LQBMMGXAG9FQBEXAEAF86BBAECFJREAGCaJHGQBMMABMMMFBCUNMIT9kBB';var wasm_simd='B9h9z9tFBBBF8dL9gBB9gLaaaaaFa9gEaaaB9gGaaB9gFaFaEQSBBFBFFGEGEGIILF9wFFFLEFBFKNFaFCx/aFMO/LFVK9tv9t9vq95GBt9f9f939h9z9t9f9j9h9s9s9f9jW9vq9zBBp9tv9z9o9v9wW9f9kv9j9v9kv9WvqWv94h919m9mvqBG8Z9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv94h919m9mvqBIy9tv9z9o9v9wW9f9kv9j9v9kv9J9u9kv949TvZ91v9u9jvBLn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9P9jWBKi9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9R919hWBNn9tv9z9o9v9wW9f9kv9j9v9kv69p9sWvq9F949wBcI9z9iqlBMc/j9JSIBTEM9+FLa8jUUUUBCTlRBCBRFEXCBRGCBREEXABCNJAGJAECUaAFAGrCFZHIy86BBAEAIJREAGCFJHGCN9HQBMAFCx+YUUBJAE86BBAFCEWCxkUUBJAB8pEN83EBAFCFJHFCUG9HQBMMkRIbaG97FaK978jUUUUBCU/KBlHL8kUUUUBC9+RKGXAGCFJAI9LQBCaRKAE2BBC+gF9HQBALAEAIJHOAGlAG/8cBBCUoBAG9uC/wgBZHKCUGAKCUG9JyRNAECFJRKCBRVGXEXAVAF9PQFANAFAVlAVANJAF9JyRcGXGXAG9FQBAcCbJHIC9wZHMCE9sRSAMCFWRQAICIrCEJCGrRfCBRbEXAKRTCBRtGXEXGXAOATlAf9PQBCBRKSLMALCU/CBJAtAM9sJRmATAfJRKCBREGXAMCoB9JQBAOAKlC/gB9JQBCBRIEXAmAIJREGXGXGXGXGXATAICKrJ2BBHYCEZfIBFGEBMAECBDtDMIBSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIBAKCTJRKMGXGXGXGXGXAYCGrCEZfIBFGEBMAECBDtDMITSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMITAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMITAKCTJRKMGXGXGXGXGXAYCIrCEZfIBFGEBMAECBDtDMIASEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIAAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAEAKDBBBDMIAAKCTJRKMGXGXGXGXGXAYCKrfIBFGEBMAECBDtDMI8wSEMAEAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCIJAnDeBJAYCx+YUUBJ2BBJRKSGMAEAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBAYCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HYCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMI8wAKCNJAnDeBJAYCx+YUUBJ2BBJRKSFMAEAKDBBBDMI8wAKCTJRKMAICoBJREAICUFJAM9LQFAERIAOAKlC/fB9LQBMMGXAEAM9PQBAECErRIEXGXAOAKlCi9PQBCBRKSOMAmAEJRYGXGXGXGXGXATAECKrJ2BBAICKZrCEZfIBFGEBMAYCBDtDMIBSEMAYAKDBBIAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnHPCGD+MFAPDQBTFtGmEYIPLdKeOnC0+G+MiDtD9OHdCEDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCIJAnDeBJAeCx+YUUBJ2BBJRKSGMAYAKDBBNAKDBBBHPCID+MFAPDQBTFtGmEYIPLdKeOnC+P+e+8/4BDtD9OHdCbDbD8jHPD8dBhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBAeCx+YUUBJDBBBHnAnDQBBBBBBBBBBBBBBBBAPD8dFhUg/8/4/w/goB9+h84k7HeCEWCxkUUBJDBEBD9uDQBFGEILKOTtmYPdenDfAdAPD9SDMIBAKCNJAnDeBJAeCx+YUUBJ2BBJRKSFMAYAKDBBBDMIBAKCTJRKMAICGJRIAECTJHEAM9JQBMMGXAK9FQBAKRTAtCFJHtCI6QGSFMMCBRKSEMGXAM9FQBALCUGJAbJREALAbJDBGBRnCBRYEXAEALCU/CBJAYJHIDBIBHdCFD9tAdCFDbHPD9OD9hD9RHdAIAMJDBIBHiCFD9tAiAPD9OD9hD9RHiDQBTFtGmEYIPLdKeOnH8ZAIAQJDBIBHpCFD9tApAPD9OD9hD9RHpAIASJDBIBHyCFD9tAyAPD9OD9hD9RHyDQBTFtGmEYIPLdKeOnH8cDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGEAnD9uHnDyBjGBAEAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnA8ZA8cDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNiV8ZcpMyS8cQ8df8eb8fHdApAyDQNiV8ZcpMyS8cQ8df8eb8fHiDQBFTtGEmYILPdKOenHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJHIAnAdAiDQNVi8ZcMpySQ8c8dfb8e8fHPAPDQBFGEBFGEBFGEBFGED9uHnDyBjGBAIAGJHIAnAPAPDQILKOILKOILKOILKOD9uHnDyBjGBAIAGJHIAnAPAPDQNVcMNVcMNVcMNVcMD9uHnDyBjGBAIAGJHIAnAPAPDQSQfbSQfbSQfbSQfbD9uHnDyBjGBAIAGJREAYCTJHYAM9JQBMMAbCIJHbAG9JQBMMABAVAG9sJALCUGJAcAG9s/8cBBALALCUGJAcCaJAG9sJAG/8cBBMAcCBAKyAVJRVAKQBMC9+RKSFMCBC99AOAKlAGCAAGCA9Ly6yRKMALCU/KBJ8kUUUUBAKMNBT+BUUUBM+KmFTa8jUUUUBCoFlHL8kUUUUBC9+RKGXAFCE9uHOCtJAI9LQBCaRKAE2BBHNC/wFZC/gF9HQBANCbZHVCF9LQBALCoBJCgFCUF/8MBALC84Jha83EBALC8wJha83EBALC8oJha83EBALCAJha83EBALCiJha83EBALCTJha83EBALha83ENALha83EBAEAIJC9wJRcAECFJHNAOJRMGXAF9FQBCQCbAVCF6yRSABRECBRVCBRQCBRfCBRICBRKEXGXAMAcuQBC9+RKSEMGXGXAN2BBHOC/vF9LQBALCoBJAOCIrCa9zAKJCbZCEWJHb8oGIRTAb8oGBRtGXAOCbZHbAS9PQBALAOCa9zAIJCbZCGWJ8oGBAVAbyROAb9FRbGXGXAGCG9HQBABAt87FBABCIJAO87FBABCGJAT87FBSFMAEAtjGBAECNJAOjGBAECIJATjGBMAVAbJRVALCoBJAKCEWJHmAOjGBAmATjGIALAICGWJAOjGBALCoBJAKCFJCbZHKCEWJHTAtjGBATAOjGIAIAbJRIAKCFJRKSGMGXGXAbCb6QBAQAbJAbC989zJCFJRQSFMAM1BBHbCgFZROGXGXAbCa9MQBAMCFJRMSFMAM1BFHbCgBZCOWAOCgBZqROGXAbCa9MQBAMCGJRMSFMAM1BGHbCgBZCfWAOqROGXAbCa9MQBAMCEJRMSFMAM1BEHbCgBZCdWAOqROGXAbCa9MQBAMCIJRMSFMAM2BIC8cWAOqROAMCLJRMMAOCFrCBAOCFZl9zAQJRQMGXGXAGCG9HQBABAt87FBABCIJAQ87FBABCGJAT87FBSFMAEAtjGBAECNJAQjGBAECIJATjGBMALCoBJAKCEWJHOAQjGBAOATjGIALAICGWJAQjGBALCoBJAKCFJCbZHKCEWJHOAtjGBAOAQjGIAICFJRIAKCFJRKSFMGXAOCDF9LQBALAIAcAOCbZJ2BBHbCIrHTlCbZCGWJ8oGBAVCFJHtATyROALAIAblCbZCGWJ8oGBAtAT9FHmJHtAbCbZHTyRbAT9FRTGXGXAGCG9HQBABAV87FBABCIJAb87FBABCGJAO87FBSFMAEAVjGBAECNJAbjGBAECIJAOjGBMALAICGWJAVjGBALCoBJAKCEWJHYAOjGBAYAVjGIALAICFJHICbZCGWJAOjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAIAmJCbZHICGWJAbjGBALCoBJAKCGJCbZHKCEWJHOAVjGBAOAbjGIAKCFJRKAIATJRIAtATJRVSFMAVCBAM2BBHYyHTAOC/+F6HPJROAYCbZRtGXGXAYCIrHmQBAOCFJRbSFMAORbALAIAmlCbZCGWJ8oGBROMGXGXAtQBAbCFJRVSFMAbRVALAIAYlCbZCGWJ8oGBRbMGXGXAP9FQBAMCFJRYSFMAM1BFHYCgFZRTGXGXAYCa9MQBAMCGJRYSFMAM1BGHYCgBZCOWATCgBZqRTGXAYCa9MQBAMCEJRYSFMAM1BEHYCgBZCfWATqRTGXAYCa9MQBAMCIJRYSFMAM1BIHYCgBZCdWATqRTGXAYCa9MQBAMCLJRYSFMAMCKJRYAM2BLC8cWATqRTMATCFrCBATCFZl9zAQJHQRTMGXGXAmCb6QBAYRPSFMAY1BBHMCgFZROGXGXAMCa9MQBAYCFJRPSFMAY1BFHMCgBZCOWAOCgBZqROGXAMCa9MQBAYCGJRPSFMAY1BGHMCgBZCfWAOqROGXAMCa9MQBAYCEJRPSFMAY1BEHMCgBZCdWAOqROGXAMCa9MQBAYCIJRPSFMAYCLJRPAY2BIC8cWAOqROMAOCFrCBAOCFZl9zAQJHQROMGXGXAtCb6QBAPRMSFMAP1BBHMCgFZRbGXGXAMCa9MQBAPCFJRMSFMAP1BFHMCgBZCOWAbCgBZqRbGXAMCa9MQBAPCGJRMSFMAP1BGHMCgBZCfWAbqRbGXAMCa9MQBAPCEJRMSFMAP1BEHMCgBZCdWAbqRbGXAMCa9MQBAPCIJRMSFMAPCLJRMAP2BIC8cWAbqRbMAbCFrCBAbCFZl9zAQJHQRbMGXGXAGCG9HQBABAT87FBABCIJAb87FBABCGJAO87FBSFMAEATjGBAECNJAbjGBAECIJAOjGBMALCoBJAKCEWJHYAOjGBAYATjGIALAICGWJATjGBALCoBJAKCFJCbZCEWJHYAbjGBAYAOjGIALAICFJHICbZCGWJAOjGBALCoBJAKCGJCbZCEWJHOATjGBAOAbjGIALAIAm9FAmCb6qJHICbZCGWJAbjGBAIAt9FAtCb6qJRIAKCEJRKMANCFJRNABCKJRBAECSJREAKCbZRKAICbZRIAfCEJHfAF9JQBMMCBC99AMAc6yRKMALCoFJ8kUUUUBAKM/tIFGa8jUUUUBCTlRLC9+RKGXAFCLJAI9LQBCaRKAE2BBC/+FZC/QF9HQBALhB83ENAECFJRKAEAIJC98JREGXAF9FQBGXAGCG6QBEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMALCNJAICFZCGWqHGAICGrCBAICFrCFZl9zAG8oGBJHIjGBABAIjGBABCIJRBAFCaJHFQBSGMMEXGXAKAE9JQBC9+bMAK1BBHGCgFZRIGXGXAGCa9MQBAKCFJRKSFMAK1BFHGCgBZCOWAICgBZqRIGXAGCa9MQBAKCGJRKSFMAK1BGHGCgBZCfWAIqRIGXAGCa9MQBAKCEJRKSFMAK1BEHGCgBZCdWAIqRIGXAGCa9MQBAKCIJRKSFMAK2BIC8cWAIqRIAKCLJRKMABAICGrCBAICFrCFZl9zALCNJAICFZCGWqHI8oGBJHG87FBAIAGjGBABCGJRBAFCaJHFQBMMCBC99AKAE6yRKMAKM/xLGEaK978jUUUUBCAlHE8kUUUUBGXGXAGCI9HQBGXAFC98ZHI9FQBABRGCBRLEXAGAGDBBBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMBBAGCTJRGALCIJHLAI9JQBMMAIAF9PQFAEAFCEZHLCGWHGqCBCTAGl/8MBAEABAICGWJHIAG/8cBBGXAL9FQBAEAEDBIBHKCiD+rFCiD+sFD/6FHOAKCND+rFCiD+sFD/6FAOD/gFAKCTD+rFCiD+sFD/6FHND/gFD/kFD/lFHVCBDtD+2FHcAOCUUUU94DtHMD9OD9RD/kFHO9DBB/+hDYAOAOD/mFAVAVD/mFANAcANAMD9OD9RD/kFHOAOD/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHcD/kFCgFDtD9OAKCUUU94DtD9OD9QAOAND/mFAcD/kFCND+rFCU/+EDtD9OD9QAVAND/mFAcD/kFCTD+rFCUU/8ODtD9OD9QDMIBMAIAEAG/8cBBSFMABAFC98ZHGT+HUUUBAGAF9PQBAEAFCEZHICEWHLJCBCAALl/8MBAEABAGCEWJHGAL/8cBBAEAIT+HUUUBAGAEAL/8cBBMAECAJ8kUUUUBM+yEGGaO97GXAF9FQBCBRGEXABCTJHEAEDBBBHICBDtHLCUU98D8cFCUU98D8cEHKD9OABDBBBHOAIDQILKOSQfbPden8c8d8e8fCggFDtD9OD/6FAOAIDQBFGENVcMTtmYi8ZpyHICTD+sFD/6FHND/gFAICTD+rFCTD+sFD/6FHVD/gFD/kFD/lFHI9DB/+g6DYAVAIALD+2FHLAVCUUUU94DtHcD9OD9RD/kFHVAVD/mFAIAID/mFANALANAcD9OD9RD/kFHIAID/mFD/kFD/kFD/jFD/nFHND/mF9DBBX9LDYHLD/kFCTD+rFAVAND/mFALD/kFCggEDtD9OD9QHVAIAND/mFALD/kFCaDbCBDnGCBDnECBDnKCBDnOCBDncCBDnMCBDnfCBDnbD9OHIDQNVi8ZcMpySQ8c8dfb8e8fD9QDMBBABAOAKD9OAVAIDQBFTtGEmYILPdKOenD9QDMBBABCAJRBAGCIJHGAF9JQBMMM94FEa8jUUUUBCAlHE8kUUUUBABAFC98ZHIT+JUUUBGXAIAF9PQBAEAFCEZHLCEWHFJCBCAAFl/8MBAEABAICEWJHBAF/8cBBAEALT+JUUUBABAEAF/8cBBMAECAJ8kUUUUBM/hEIGaF97FaL978jUUUUBCTlRGGXAF9FQBCBREEXAGABDBBBHIABCTJHLDBBBHKDQILKOSQfbPden8c8d8e8fHOCTD+sFHNCID+rFDMIBAB9DBBU8/DY9D/zI818/DYANCEDtD9QD/6FD/nFHNAIAKDQBFGENVcMTtmYi8ZpyHICTD+rFCTD+sFD/6FD/mFHKAKD/mFANAICTD+sFD/6FD/mFHVAVD/mFANAOCTD+rFCTD+sFD/6FD/mFHOAOD/mFD/kFD/kFD/lFCBDtD+4FD/jF9DB/+g6DYHND/mF9DBBX9LDYHID/kFCggEDtHcD9OAVAND/mFAID/kFCTD+rFD9QHVAOAND/mFAID/kFCTD+rFAKAND/mFAID/kFAcD9OD9QHNDQBFTtGEmYILPdKOenHID8dBAGDBIBDyB+t+J83EBABCNJAID8dFAGDBIBDyF+t+J83EBALAVANDQNVi8ZcMpySQ8c8dfb8e8fHND8dBAGDBIBDyG+t+J83EBABCiJAND8dFAGDBIBDyE+t+J83EBABCAJRBAECIJHEAF9JQBMMM/3FGEaF978jUUUUBCoBlREGXAGCGrAF9sHIC98ZHL9FQBCBRGABRFEXAFAFDBBBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMBBAFCTJRFAGCIJHGAL9JQBMMGXALAI9PQBAEAICEZHGCGWHFqCBCoBAFl/8MBAEABALCGWJHLAF/8cBBGXAG9FQBAEAEDBIBHKCND+rFCND+sFD/6FAKCiD+sFCnD+rFCUUU/8EDtD+uFD/mFDMIBMALAEAF/8cBBMM9TFEaCBCB8oGUkUUBHFABCEJC98ZJHBjGUkUUBGXGXAB8/BCTWHGuQBCaREABAGlCggEJCTrXBCa6QFMAFREMAEMMMFBCUNMIT9tBB';var detector=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,3,2,0,0,5,3,1,0,1,12,1,0,10,22,2,12,0,65,0,65,0,65,0,252,10,0,0,11,7,0,65,0,253,15,26,11]);var wasmpack=new Uint8Array([32,0,65,253,3,1,2,34,4,106,6,5,11,8,7,20,13,33,12,16,128,9,116,64,19,113,127,15,10,21,22,14,255,66,24,54,136,107,18,23,192,26,114,118,132,17,77,101,130,144,27,87,131,44,45,74,156,154,70,167]);var FILTERS={0:'',1:'meshopt_decodeFilterOct',2:'meshopt_decodeFilterQuat',3:'meshopt_decodeFilterExp',NONE:'',OCTAHEDRAL:'meshopt_decodeFilterOct',QUATERNION:'meshopt_decodeFilterQuat',EXPONENTIAL:'meshopt_decodeFilterExp'};var DECODERS={0:'meshopt_decodeVertexBuffer',1:'meshopt_decodeIndexBuffer',2:'meshopt_decodeIndexSequence',ATTRIBUTES:'meshopt_decodeVertexBuffer',TRIANGLES:'meshopt_decodeIndexBuffer',INDICES:'meshopt_decodeIndexSequence'};function isMeshoptSupported(){return isWebAssemblySupported;}function meshoptDecodeGltfBuffer(_x79,_x80,_x81,_x82,_x83){return _meshoptDecodeGltfBuffer.apply(this,arguments);}function _meshoptDecodeGltfBuffer(){_meshoptDecodeGltfBuffer=_asyncToGenerator(function*(target,count,size,source,mode){var filter=arguments.length>5&&arguments[5]!==undefined?arguments[5]:'NONE';var instance=yield loadWasmInstance();decode$5(instance,instance.exports[DECODERS[mode]],target,count,size,source,instance.exports[FILTERS[filter||'NONE']]);});return _meshoptDecodeGltfBuffer.apply(this,arguments);}var wasmPromise;function loadWasmInstance(){return _loadWasmInstance.apply(this,arguments);}function _loadWasmInstance(){_loadWasmInstance=_asyncToGenerator(function*(){if(!wasmPromise){wasmPromise=loadWasmModule();}return wasmPromise;});return _loadWasmInstance.apply(this,arguments);}function loadWasmModule(){return _loadWasmModule.apply(this,arguments);}function _loadWasmModule(){_loadWasmModule=_asyncToGenerator(function*(){var wasm=wasm_base;if(WebAssembly.validate(detector)){wasm=wasm_simd;console.log('Warning: meshopt_decoder is using experimental SIMD support');}var result=yield WebAssembly.instantiate(unpack(wasm),{});yield result.instance.exports.__wasm_call_ctors();return result.instance;});return _loadWasmModule.apply(this,arguments);}function unpack(data){var result=new Uint8Array(data.length);for(var _i50=0;_i50<data.length;++_i50){var ch=data.charCodeAt(_i50);result[_i50]=ch>96?ch-71:ch>64?ch-65:ch>47?ch+4:ch>46?63:62;}var write=0;for(var _i51=0;_i51<data.length;++_i51){result[write++]=result[_i51]<60?wasmpack[result[_i51]]:(result[_i51]-60)*64+result[++_i51];}return result.buffer.slice(0,write);}function decode$5(instance,fun,target,count,size,source,filter){var sbrk=instance.exports.sbrk;var count4=count+3&~3;var tp=sbrk(count4*size);var sp=sbrk(source.length);var heap=new Uint8Array(instance.exports.memory.buffer);heap.set(source,sp);var res=fun(tp,count,size,sp,source.length);if(res===0&&filter){filter(tp,count4,size);}target.set(heap.subarray(tp,tp+count*size));sbrk(tp-sbrk(0));if(res!==0){throw new Error("Malformed buffer data: ".concat(res));}}var EXT_MESHOPT_COMPRESSION='EXT_meshopt_compression';var name$6=EXT_MESHOPT_COMPRESSION;function preprocess$4(gltfData){var scenegraph=new GLTFScenegraph(gltfData);if(scenegraph.getRequiredExtensions().includes(EXT_MESHOPT_COMPRESSION)&&!isMeshoptSupported()){throw new Error("gltf: Required extension ".concat(EXT_MESHOPT_COMPRESSION," not supported by browser"));}}function decode$4(_x84,_x85){return _decode$.apply(this,arguments);}function _decode$(){_decode$=_asyncToGenerator(function*(gltfData,options){var _options$gltf;var scenegraph=new GLTFScenegraph(gltfData);if(!(options!==null&&options!==void 0&&(_options$gltf=options.gltf)!==null&&_options$gltf!==void 0&&_options$gltf.decompressMeshes)){return;}var promises=[];for(var bufferViewIndex of gltfData.json.bufferViews||[]){promises.push(decodeMeshoptBufferView(scenegraph,bufferViewIndex));}yield Promise.all(promises);scenegraph.removeExtension(EXT_MESHOPT_COMPRESSION);});return _decode$.apply(this,arguments);}function decodeMeshoptBufferView(_x86,_x87){return _decodeMeshoptBufferView.apply(this,arguments);}function _decodeMeshoptBufferView(){_decodeMeshoptBufferView=_asyncToGenerator(function*(scenegraph,bufferView){var meshoptExtension=scenegraph.getObjectExtension(bufferView,EXT_MESHOPT_COMPRESSION);if(meshoptExtension){var buffer=bufferView.buffer;var{byteOffset=0,byteLength=0,byteStride,count,mode,filter='NONE'}=meshoptExtension;var source=new Uint8Array(buffer,byteOffset,byteLength);var result=new ArrayBuffer(count*byteStride);yield meshoptDecodeGltfBuffer(new Uint8Array(result),count,byteStride,source,mode,filter);return result;}return null;});return _decodeMeshoptBufferView.apply(this,arguments);}var EXT_meshopt_compression=/*#__PURE__*/Object.freeze({__proto__:null,name:name$6,preprocess:preprocess$4,decode:decode$4});var EXT_TEXTURE_WEBP='EXT_texture_webp';var name$5=EXT_TEXTURE_WEBP;function preprocess$3(gltfData,options){var scenegraph=new GLTFScenegraph(gltfData);if(!_isImageFormatSupported('image/webp')){if(scenegraph.getRequiredExtensions().includes(EXT_TEXTURE_WEBP)){throw new Error("gltf: Required extension ".concat(EXT_TEXTURE_WEBP," not supported by browser"));}return;}var{json}=scenegraph;for(var texture of json.textures||[]){var extension=scenegraph.getObjectExtension(texture,EXT_TEXTURE_WEBP);if(extension){texture.source=extension.source;}scenegraph.removeObjectExtension(texture,EXT_TEXTURE_WEBP);}scenegraph.removeExtension(EXT_TEXTURE_WEBP);}var EXT_texture_webp=/*#__PURE__*/Object.freeze({__proto__:null,name:name$5,preprocess:preprocess$3});var KHR_TEXTURE_BASISU='KHR_texture_basisu';var name$4=KHR_TEXTURE_BASISU;function preprocess$2(gltfData,options){var scene=new GLTFScenegraph(gltfData);var{json}=scene;for(var texture of json.textures||[]){var extension=scene.getObjectExtension(texture,KHR_TEXTURE_BASISU);if(extension){texture.source=extension.source;}scene.removeObjectExtension(texture,KHR_TEXTURE_BASISU);}scene.removeExtension(KHR_TEXTURE_BASISU);}var KHR_texture_basisu=/*#__PURE__*/Object.freeze({__proto__:null,name:name$4,preprocess:preprocess$2});function getGLTFAccessors(attributes){var accessors={};for(var _name5 in attributes){var attribute=attributes[_name5];if(_name5!=='indices'){var glTFAccessor=getGLTFAccessor(attribute);accessors[_name5]=glTFAccessor;}}return accessors;}function getGLTFAccessor(attribute){var{buffer,size,count}=getAccessorData(attribute);var glTFAccessor={value:buffer,size,byteOffset:0,count,type:getAccessorTypeFromSize(size),componentType:getComponentTypeFromArray(buffer)};return glTFAccessor;}function getAccessorData(attribute){var buffer=attribute;var size=1;var count=0;if(attribute&&attribute.value){buffer=attribute.value;size=attribute.size||1;}if(buffer){if(!ArrayBuffer.isView(buffer)){buffer=toTypedArray(buffer,Float32Array);}count=buffer.length/size;}return {buffer,size,count};}function toTypedArray(array,ArrayType){var convertTypedArrays=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(!array){return null;}if(Array.isArray(array)){return new ArrayType(array);}if(convertTypedArrays&&!(array instanceof ArrayType)){return new ArrayType(array);}return array;}var KHR_DRACO_MESH_COMPRESSION='KHR_draco_mesh_compression';var name$3=KHR_DRACO_MESH_COMPRESSION;function preprocess$1(gltfData,options,context){var scenegraph=new GLTFScenegraph(gltfData);for(var primitive of makeMeshPrimitiveIterator(scenegraph)){if(scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION));}}function decode$3(_x88,_x89,_x90){return _decode$2.apply(this,arguments);}function _decode$2(){_decode$2=_asyncToGenerator(function*(gltfData,options,context){var _options$gltf;if(!(options!==null&&options!==void 0&&(_options$gltf=options.gltf)!==null&&_options$gltf!==void 0&&_options$gltf.decompressMeshes)){return;}var scenegraph=new GLTFScenegraph(gltfData);var promises=[];for(var primitive of makeMeshPrimitiveIterator(scenegraph)){if(scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION)){promises.push(decompressPrimitive(scenegraph,primitive,options,context));}}yield Promise.all(promises);scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);});return _decode$2.apply(this,arguments);}function encode$3(gltfData){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var scenegraph=new GLTFScenegraph(gltfData);for(var mesh of scenegraph.json.meshes||[]){compressMesh(mesh);scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);}}function decompressPrimitive(_x91,_x92,_x93,_x94){return _decompressPrimitive.apply(this,arguments);}function _decompressPrimitive(){_decompressPrimitive=_asyncToGenerator(function*(scenegraph,primitive,options,context){var dracoExtension=scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION);if(!dracoExtension){return;}var buffer=scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);var bufferCopy=sliceArrayBuffer(buffer.buffer,buffer.byteOffset);var{parse}=context;var dracoOptions=_objectSpread2({},options);delete dracoOptions['3d-tiles'];var decodedData=yield parse(bufferCopy,DracoLoader,dracoOptions,context);var decodedAttributes=getGLTFAccessors(decodedData.attributes);for(var[attributeName,decodedAttribute]of Object.entries(decodedAttributes)){if(attributeName in primitive.attributes){var accessorIndex=primitive.attributes[attributeName];var accessor=scenegraph.getAccessor(accessorIndex);if(accessor!==null&&accessor!==void 0&&accessor.min&&accessor!==null&&accessor!==void 0&&accessor.max){decodedAttribute.min=accessor.min;decodedAttribute.max=accessor.max;}}}primitive.attributes=decodedAttributes;if(decodedData.indices){primitive.indices=getGLTFAccessor(decodedData.indices);}checkPrimitive(primitive);});return _decompressPrimitive.apply(this,arguments);}function compressMesh(attributes,indices){var mode=arguments.length>2&&arguments[2]!==undefined?arguments[2]:4;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _context$parseSync;if(!options.DracoWriter){throw new Error('options.gltf.DracoWriter not provided');}var compressedData=options.DracoWriter.encodeSync({attributes});var decodedData=context===null||context===void 0?void 0:(_context$parseSync=context.parseSync)===null||_context$parseSync===void 0?void 0:_context$parseSync.call(context,{attributes});var fauxAccessors=options._addFauxAttributes(decodedData.attributes);var bufferViewIndex=options.addBufferView(compressedData);var glTFMesh={primitives:[{attributes:fauxAccessors,mode,extensions:{[KHR_DRACO_MESH_COMPRESSION]:{bufferView:bufferViewIndex,attributes:fauxAccessors}}}]};return glTFMesh;}function checkPrimitive(primitive){if(!primitive.attributes&&Object.keys(primitive.attributes).length>0){throw new Error('glTF: Empty primitive detected: Draco decompression failure?');}}function*makeMeshPrimitiveIterator(scenegraph){for(var mesh of scenegraph.json.meshes||[]){for(var primitive of mesh.primitives){yield primitive;}}}var KHR_draco_mesh_compression=/*#__PURE__*/Object.freeze({__proto__:null,name:name$3,preprocess:preprocess$1,decode:decode$3,encode:encode$3});var KHR_LIGHTS_PUNCTUAL='KHR_lights_punctual';var name$2=KHR_LIGHTS_PUNCTUAL;function decode$2(_x95){return _decode$3.apply(this,arguments);}function _decode$3(){_decode$3=_asyncToGenerator(function*(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;var extension=gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);if(extension){gltfScenegraph.json.lights=extension.lights;gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);}for(var _node3 of json.nodes||[]){var nodeExtension=gltfScenegraph.getObjectExtension(_node3,KHR_LIGHTS_PUNCTUAL);if(nodeExtension){_node3.light=nodeExtension.light;}gltfScenegraph.removeObjectExtension(_node3,KHR_LIGHTS_PUNCTUAL);}});return _decode$3.apply(this,arguments);}function encode$2(_x96){return _encode$.apply(this,arguments);}function _encode$(){_encode$=_asyncToGenerator(function*(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;if(json.lights){var extension=gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);assert$1(!extension.lights);extension.lights=json.lights;delete json.lights;}if(gltfScenegraph.json.lights){for(var light of gltfScenegraph.json.lights){var _node4=light.node;gltfScenegraph.addObjectExtension(_node4,KHR_LIGHTS_PUNCTUAL,light);}delete gltfScenegraph.json.lights;}});return _encode$.apply(this,arguments);}var KHR_lights_punctual=/*#__PURE__*/Object.freeze({__proto__:null,name:name$2,decode:decode$2,encode:encode$2});var KHR_MATERIALS_UNLIT='KHR_materials_unlit';var name$1=KHR_MATERIALS_UNLIT;function decode$1(_x97){return _decode$4.apply(this,arguments);}function _decode$4(){_decode$4=_asyncToGenerator(function*(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);for(var material of json.materials||[]){var extension=material.extensions&&material.extensions.KHR_materials_unlit;if(extension){material.unlit=true;}gltfScenegraph.removeObjectExtension(material,KHR_MATERIALS_UNLIT);}});return _decode$4.apply(this,arguments);}function encode$1(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;if(gltfScenegraph.materials){for(var material of json.materials||[]){if(material.unlit){delete material.unlit;gltfScenegraph.addObjectExtension(material,KHR_MATERIALS_UNLIT,{});gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);}}}}var KHR_materials_unlit=/*#__PURE__*/Object.freeze({__proto__:null,name:name$1,decode:decode$1,encode:encode$1});var KHR_TECHNIQUES_WEBGL='KHR_techniques_webgl';var name$7=KHR_TECHNIQUES_WEBGL;function decode(_x98){return _decode.apply(this,arguments);}function _decode(){_decode=_asyncToGenerator(function*(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;var extension=gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);if(extension){var techniques=resolveTechniques(extension,gltfScenegraph);for(var material of json.materials||[]){var materialExtension=gltfScenegraph.getObjectExtension(material,KHR_TECHNIQUES_WEBGL);if(materialExtension){material.technique=Object.assign({},materialExtension,techniques[materialExtension.technique]);material.technique.values=resolveValues(material.technique,gltfScenegraph);}gltfScenegraph.removeObjectExtension(material,KHR_TECHNIQUES_WEBGL);}gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);}});return _decode.apply(this,arguments);}function encode(_x99,_x100){return _encode.apply(this,arguments);}function _encode(){_encode=_asyncToGenerator(function*(gltfData,options){});return _encode.apply(this,arguments);}function resolveTechniques(techniquesExtension,gltfScenegraph){var{programs=[],shaders=[],techniques=[]}=techniquesExtension;var textDecoder=new TextDecoder();shaders.forEach(shader=>{if(Number.isFinite(shader.bufferView)){shader.code=textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));}else {throw new Error('KHR_techniques_webgl: no shader code');}});programs.forEach(program=>{program.fragmentShader=shaders[program.fragmentShader];program.vertexShader=shaders[program.vertexShader];});techniques.forEach(technique=>{technique.program=programs[technique.program];});return techniques;}function resolveValues(technique,gltfScenegraph){var values=Object.assign({},technique.values);Object.keys(technique.uniforms||{}).forEach(uniform=>{if(technique.uniforms[uniform].value&&!(uniform in values)){values[uniform]=technique.uniforms[uniform].value;}});Object.keys(values).forEach(uniform=>{if(typeof values[uniform]==='object'&&values[uniform].index!==undefined){values[uniform].texture=gltfScenegraph.getTexture(values[uniform].index);}});return values;}var KHR_techniques_webgl=/*#__PURE__*/Object.freeze({__proto__:null,name:name$7,decode:decode,encode:encode});var EXTENSIONS$2=[EXT_meshopt_compression,EXT_texture_webp,KHR_texture_basisu,KHR_draco_mesh_compression,KHR_lights_punctual,KHR_materials_unlit,KHR_techniques_webgl];function preprocessExtensions(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS$2.filter(extension=>useExtension(extension.name,options));for(var extension of extensions){var _extension$preprocess;(_extension$preprocess=extension.preprocess)===null||_extension$preprocess===void 0?void 0:_extension$preprocess.call(extension,gltf,options,context);}}function decodeExtensions(_x101){return _decodeExtensions.apply(this,arguments);}function _decodeExtensions(){_decodeExtensions=_asyncToGenerator(function*(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS$2.filter(extension=>useExtension(extension.name,options));for(var extension of extensions){var _extension$decode;yield (_extension$decode=extension.decode)===null||_extension$decode===void 0?void 0:_extension$decode.call(extension,gltf,options,context);}});return _decodeExtensions.apply(this,arguments);}function useExtension(extensionName,options){var _options$gltf;var excludes=(options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.excludeExtensions)||{};var exclude=extensionName in excludes&&!excludes[extensionName];return !exclude;}var KHR_BINARY_GLTF='KHR_binary_glTF';function preprocess(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var{json}=gltfScenegraph;for(var image of json.images||[]){var extension=gltfScenegraph.getObjectExtension(image,KHR_BINARY_GLTF);if(extension){Object.assign(image,extension);}gltfScenegraph.removeObjectExtension(image,KHR_BINARY_GLTF);}if(json.buffers&&json.buffers[0]){delete json.buffers[0].uri;}gltfScenegraph.removeExtension(KHR_BINARY_GLTF);}var GLTF_ARRAYS={accessors:'accessor',animations:'animation',buffers:'buffer',bufferViews:'bufferView',images:'image',materials:'material',meshes:'mesh',nodes:'node',samplers:'sampler',scenes:'scene',skins:'skin',textures:'texture'};var GLTF_KEYS={accessor:'accessors',animations:'animation',buffer:'buffers',bufferView:'bufferViews',image:'images',material:'materials',mesh:'meshes',node:'nodes',sampler:'samplers',scene:'scenes',skin:'skins',texture:'textures'};class GLTFV1Normalizer{constructor(){_defineProperty$1(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}});_defineProperty$1(this,"json",void 0);}normalize(gltf,options){this.json=gltf.json;var json=gltf.json;switch(json.asset&&json.asset.version){case'2.0':return;case undefined:case'1.0':break;default:console.warn("glTF: Unknown version ".concat(json.asset.version));return;}if(!options.normalize){throw new Error('glTF v1 is not supported.');}console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');this._addAsset(json);this._convertTopLevelObjectsToArrays(json);preprocess(gltf);this._convertObjectIdsToArrayIndices(json);this._updateObjects(json);this._updateMaterial(json);}_addAsset(json){json.asset=json.asset||{};json.asset.version='2.0';json.asset.generator=json.asset.generator||'Normalized to glTF 2.0 by loaders.gl';}_convertTopLevelObjectsToArrays(json){for(var arrayName in GLTF_ARRAYS){this._convertTopLevelObjectToArray(json,arrayName);}}_convertTopLevelObjectToArray(json,mapName){var objectMap=json[mapName];if(!objectMap||Array.isArray(objectMap)){return;}json[mapName]=[];for(var id in objectMap){var object=objectMap[id];object.id=object.id||id;var index=json[mapName].length;json[mapName].push(object);this.idToIndexMap[mapName][id]=index;}}_convertObjectIdsToArrayIndices(json){for(var arrayName in GLTF_ARRAYS){this._convertIdsToIndices(json,arrayName);}if('scene'in json){json.scene=this._convertIdToIndex(json.scene,'scene');}for(var texture of json.textures){this._convertTextureIds(texture);}for(var mesh of json.meshes){this._convertMeshIds(mesh);}for(var _node of json.nodes){this._convertNodeIds(_node);}for(var _node2 of json.scenes){this._convertSceneIds(_node2);}}_convertTextureIds(texture){if(texture.source){texture.source=this._convertIdToIndex(texture.source,'image');}}_convertMeshIds(mesh){for(var primitive of mesh.primitives){var{attributes,indices,material}=primitive;for(var attributeName in attributes){attributes[attributeName]=this._convertIdToIndex(attributes[attributeName],'accessor');}if(indices){primitive.indices=this._convertIdToIndex(indices,'accessor');}if(material){primitive.material=this._convertIdToIndex(material,'material');}}}_convertNodeIds(node){if(node.children){node.children=node.children.map(child=>this._convertIdToIndex(child,'node'));}if(node.meshes){node.meshes=node.meshes.map(mesh=>this._convertIdToIndex(mesh,'mesh'));}}_convertSceneIds(scene){if(scene.nodes){scene.nodes=scene.nodes.map(node=>this._convertIdToIndex(node,'node'));}}_convertIdsToIndices(json,topLevelArrayName){if(!json[topLevelArrayName]){console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));json[topLevelArrayName]=[];}for(var object of json[topLevelArrayName]){for(var key in object){var id=object[key];var index=this._convertIdToIndex(id,key);object[key]=index;}}}_convertIdToIndex(id,key){var arrayName=GLTF_KEYS[key];if(arrayName in this.idToIndexMap){var index=this.idToIndexMap[arrayName][id];if(!Number.isFinite(index)){throw new Error("gltf v1: failed to resolve ".concat(key," with id ").concat(id));}return index;}return id;}_updateObjects(json){for(var buffer of this.json.buffers){delete buffer.type;}}_updateMaterial(json){var _loop3=function _loop3(){material.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var textureId=material.values&&material.values.tex;var textureIndex=json.textures.findIndex(texture=>texture.id===textureId);if(textureIndex!==-1){material.pbrMetallicRoughness.baseColorTexture={index:textureIndex};}};for(var material of json.materials){_loop3();}}}function normalizeGLTFV1(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return new GLTFV1Normalizer().normalize(gltf,options);}var COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var BYTES={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var GL_SAMPLER={TEXTURE_MAG_FILTER:0x2800,TEXTURE_MIN_FILTER:0x2801,TEXTURE_WRAP_S:0x2802,TEXTURE_WRAP_T:0x2803,REPEAT:0x2901,LINEAR:0x2601,NEAREST_MIPMAP_LINEAR:0x2702};var SAMPLER_PARAMETER_GLTF_TO_GL={magFilter:GL_SAMPLER.TEXTURE_MAG_FILTER,minFilter:GL_SAMPLER.TEXTURE_MIN_FILTER,wrapS:GL_SAMPLER.TEXTURE_WRAP_S,wrapT:GL_SAMPLER.TEXTURE_WRAP_T};var DEFAULT_SAMPLER={[GL_SAMPLER.TEXTURE_MAG_FILTER]:GL_SAMPLER.LINEAR,[GL_SAMPLER.TEXTURE_MIN_FILTER]:GL_SAMPLER.NEAREST_MIPMAP_LINEAR,[GL_SAMPLER.TEXTURE_WRAP_S]:GL_SAMPLER.REPEAT,[GL_SAMPLER.TEXTURE_WRAP_T]:GL_SAMPLER.REPEAT};function getBytesFromComponentType(componentType){return BYTES[componentType];}function getSizeFromAccessorType(type){return COMPONENTS[type];}class GLTFPostProcessor{constructor(){_defineProperty$1(this,"baseUri",'');_defineProperty$1(this,"json",{});_defineProperty$1(this,"buffers",[]);_defineProperty$1(this,"images",[]);}postProcess(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var{json,buffers=[],images=[],baseUri=''}=gltf;assert$1(json);this.baseUri=baseUri;this.json=json;this.buffers=buffers;this.images=images;this._resolveTree(this.json,options);return this.json;}_resolveTree(json){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(json.bufferViews){json.bufferViews=json.bufferViews.map((bufView,i)=>this._resolveBufferView(bufView,i));}if(json.images){json.images=json.images.map((image,i)=>this._resolveImage(image,i));}if(json.samplers){json.samplers=json.samplers.map((sampler,i)=>this._resolveSampler(sampler,i));}if(json.textures){json.textures=json.textures.map((texture,i)=>this._resolveTexture(texture,i));}if(json.accessors){json.accessors=json.accessors.map((accessor,i)=>this._resolveAccessor(accessor,i));}if(json.materials){json.materials=json.materials.map((material,i)=>this._resolveMaterial(material,i));}if(json.meshes){json.meshes=json.meshes.map((mesh,i)=>this._resolveMesh(mesh,i));}if(json.nodes){json.nodes=json.nodes.map((node,i)=>this._resolveNode(node,i));}if(json.skins){json.skins=json.skins.map((skin,i)=>this._resolveSkin(skin,i));}if(json.scenes){json.scenes=json.scenes.map((scene,i)=>this._resolveScene(scene,i));}if(json.scene!==undefined){json.scene=json.scenes[this.json.scene];}}getScene(index){return this._get('scenes',index);}getNode(index){return this._get('nodes',index);}getSkin(index){return this._get('skins',index);}getMesh(index){return this._get('meshes',index);}getMaterial(index){return this._get('materials',index);}getAccessor(index){return this._get('accessors',index);}getCamera(index){return null;}getTexture(index){return this._get('textures',index);}getSampler(index){return this._get('samplers',index);}getImage(index){return this._get('images',index);}getBufferView(index){return this._get('bufferViews',index);}getBuffer(index){return this._get('buffers',index);}_get(array,index){if(typeof index==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){console.warn("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}_resolveScene(scene,index){scene.id=scene.id||"scene-".concat(index);scene.nodes=(scene.nodes||[]).map(node=>this.getNode(node));return scene;}_resolveNode(node,index){node.id=node.id||"node-".concat(index);if(node.children){node.children=node.children.map(child=>this.getNode(child));}if(node.mesh!==undefined){node.mesh=this.getMesh(node.mesh);}else if(node.meshes!==undefined&&node.meshes.length){node.mesh=node.meshes.reduce((accum,meshIndex)=>{var mesh=this.getMesh(meshIndex);accum.id=mesh.id;accum.primitives=accum.primitives.concat(mesh.primitives);return accum;},{primitives:[]});}if(node.camera!==undefined){node.camera=this.getCamera(node.camera);}if(node.skin!==undefined){node.skin=this.getSkin(node.skin);}return node;}_resolveSkin(skin,index){skin.id=skin.id||"skin-".concat(index);skin.inverseBindMatrices=this.getAccessor(skin.inverseBindMatrices);return skin;}_resolveMesh(mesh,index){mesh.id=mesh.id||"mesh-".concat(index);if(mesh.primitives){mesh.primitives=mesh.primitives.map(primitive=>{primitive=_objectSpread2({},primitive);var attributes=primitive.attributes;primitive.attributes={};for(var attribute in attributes){primitive.attributes[attribute]=this.getAccessor(attributes[attribute]);}if(primitive.indices!==undefined){primitive.indices=this.getAccessor(primitive.indices);}if(primitive.material!==undefined){primitive.material=this.getMaterial(primitive.material);}return primitive;});}return mesh;}_resolveMaterial(material,index){material.id=material.id||"material-".concat(index);if(material.normalTexture){material.normalTexture=_objectSpread2({},material.normalTexture);material.normalTexture.texture=this.getTexture(material.normalTexture.index);}if(material.occlusionTexture){material.occlustionTexture=_objectSpread2({},material.occlustionTexture);material.occlusionTexture.texture=this.getTexture(material.occlusionTexture.index);}if(material.emissiveTexture){material.emmisiveTexture=_objectSpread2({},material.emmisiveTexture);material.emissiveTexture.texture=this.getTexture(material.emissiveTexture.index);}if(!material.emissiveFactor){material.emissiveFactor=material.emmisiveTexture?[1,1,1]:[0,0,0];}if(material.pbrMetallicRoughness){material.pbrMetallicRoughness=_objectSpread2({},material.pbrMetallicRoughness);var mr=material.pbrMetallicRoughness;if(mr.baseColorTexture){mr.baseColorTexture=_objectSpread2({},mr.baseColorTexture);mr.baseColorTexture.texture=this.getTexture(mr.baseColorTexture.index);}if(mr.metallicRoughnessTexture){mr.metallicRoughnessTexture=_objectSpread2({},mr.metallicRoughnessTexture);mr.metallicRoughnessTexture.texture=this.getTexture(mr.metallicRoughnessTexture.index);}}return material;}_resolveAccessor(accessor,index){accessor.id=accessor.id||"accessor-".concat(index);if(accessor.bufferView!==undefined){accessor.bufferView=this.getBufferView(accessor.bufferView);}accessor.bytesPerComponent=getBytesFromComponentType(accessor.componentType);accessor.components=getSizeFromAccessorType(accessor.type);accessor.bytesPerElement=accessor.bytesPerComponent*accessor.components;if(accessor.bufferView){var buffer=accessor.bufferView.buffer;var{ArrayType,byteLength}=getAccessorArrayTypeAndLength(accessor,accessor.bufferView);var byteOffset=(accessor.bufferView.byteOffset||0)+(accessor.byteOffset||0)+buffer.byteOffset;var cutBuffer=buffer.arrayBuffer.slice(byteOffset,byteOffset+byteLength);if(accessor.bufferView.byteStride){cutBuffer=this._getValueFromInterleavedBuffer(buffer,byteOffset,accessor.bufferView.byteStride,accessor.bytesPerElement,accessor.count);}accessor.value=new ArrayType(cutBuffer);}return accessor;}_getValueFromInterleavedBuffer(buffer,byteOffset,byteStride,bytesPerElement,count){var result=new Uint8Array(count*bytesPerElement);for(var _i52=0;_i52<count;_i52++){var elementOffset=byteOffset+_i52*byteStride;result.set(new Uint8Array(buffer.arrayBuffer.slice(elementOffset,elementOffset+bytesPerElement)),_i52*bytesPerElement);}return result.buffer;}_resolveTexture(texture,index){texture.id=texture.id||"texture-".concat(index);texture.sampler='sampler'in texture?this.getSampler(texture.sampler):DEFAULT_SAMPLER;texture.source=this.getImage(texture.source);return texture;}_resolveSampler(sampler,index){sampler.id=sampler.id||"sampler-".concat(index);sampler.parameters={};for(var key in sampler){var glEnum=this._enumSamplerParameter(key);if(glEnum!==undefined){sampler.parameters[glEnum]=sampler[key];}}return sampler;}_enumSamplerParameter(key){return SAMPLER_PARAMETER_GLTF_TO_GL[key];}_resolveImage(image,index){image.id=image.id||"image-".concat(index);if(image.bufferView!==undefined){image.bufferView=this.getBufferView(image.bufferView);}var preloadedImage=this.images[index];if(preloadedImage){image.image=preloadedImage;}return image;}_resolveBufferView(bufferView,index){var bufferIndex=bufferView.buffer;var result=_objectSpread2(_objectSpread2({id:"bufferView-".concat(index)},bufferView),{},{buffer:this.buffers[bufferIndex]});var arrayBuffer=this.buffers[bufferIndex].arrayBuffer;var byteOffset=this.buffers[bufferIndex].byteOffset||0;if('byteOffset'in bufferView){byteOffset+=bufferView.byteOffset;}result.data=new Uint8Array(arrayBuffer,byteOffset,bufferView.byteLength);return result;}_resolveCamera(camera,index){camera.id=camera.id||"camera-".concat(index);if(camera.perspective);if(camera.orthographic);return camera;}}function postProcessGLTF(gltf,options){return new GLTFPostProcessor().postProcess(gltf,options);}var MAGIC_glTF=0x676c5446;var GLB_FILE_HEADER_SIZE=12;var GLB_CHUNK_HEADER_SIZE=8;var GLB_CHUNK_TYPE_JSON=0x4e4f534a;var GLB_CHUNK_TYPE_BIN=0x004e4942;var GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED=0;var GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED=1;var GLB_V1_CONTENT_FORMAT_JSON=0x0;var LE=true;function getMagicString(dataView){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;return "".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}function isGLB(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var dataView=new DataView(arrayBuffer);var{magic=MAGIC_glTF}=options;var magic1=dataView.getUint32(byteOffset,false);return magic1===magic||magic1===MAGIC_glTF;}function parseGLBSync(glb,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var dataView=new DataView(arrayBuffer);var type=getMagicString(dataView,byteOffset+0);var version=dataView.getUint32(byteOffset+4,LE);var byteLength=dataView.getUint32(byteOffset+8,LE);Object.assign(glb,{header:{byteOffset,byteLength,hasBinChunk:false},type,version,json:{},binChunks:[]});byteOffset+=GLB_FILE_HEADER_SIZE;switch(glb.version){case 1:return parseGLBV1(glb,dataView,byteOffset);case 2:return parseGLBV2(glb,dataView,byteOffset,options={});default:throw new Error("Invalid GLB version ".concat(glb.version,". Only supports v1 and v2."));}}function parseGLBV1(glb,dataView,byteOffset){assert$7(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);var contentLength=dataView.getUint32(byteOffset+0,LE);var contentFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;assert$7(contentFormat===GLB_V1_CONTENT_FORMAT_JSON);parseJSONChunk(glb,dataView,byteOffset,contentLength);byteOffset+=contentLength;byteOffset+=parseBINChunk(glb,dataView,byteOffset,glb.header.byteLength);return byteOffset;}function parseGLBV2(glb,dataView,byteOffset,options){assert$7(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);parseGLBChunksSync(glb,dataView,byteOffset,options);return byteOffset+glb.header.byteLength;}function parseGLBChunksSync(glb,dataView,byteOffset,options){while(byteOffset+8<=glb.header.byteLength){var chunkLength=dataView.getUint32(byteOffset+0,LE);var chunkFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;switch(chunkFormat){case GLB_CHUNK_TYPE_JSON:parseJSONChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_BIN:parseBINChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:if(!options.strict){parseJSONChunk(glb,dataView,byteOffset,chunkLength);}break;case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:if(!options.strict){parseBINChunk(glb,dataView,byteOffset,chunkLength);}break;}byteOffset+=padToNBytes(chunkLength,4);}return byteOffset;}function parseJSONChunk(glb,dataView,byteOffset,chunkLength){var jsonChunk=new Uint8Array(dataView.buffer,byteOffset,chunkLength);var textDecoder=new TextDecoder('utf8');var jsonText=textDecoder.decode(jsonChunk);glb.json=JSON.parse(jsonText);return padToNBytes(chunkLength,4);}function parseBINChunk(glb,dataView,byteOffset,chunkLength){glb.header.hasBinChunk=true;glb.binChunks.push({byteOffset,byteLength:chunkLength,arrayBuffer:dataView.buffer});return padToNBytes(chunkLength,4);}function parseGLTF(_x102,_x103){return _parseGLTF.apply(this,arguments);}function _parseGLTF(){_parseGLTF=_asyncToGenerator(function*(gltf,arrayBufferOrString){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _options$gltf,_options$gltf2,_options$gltf3,_options$gltf4;parseGLTFContainerSync(gltf,arrayBufferOrString,byteOffset,options);normalizeGLTFV1(gltf,{normalize:options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.normalize});preprocessExtensions(gltf,options,context);var promises=[];if(options!==null&&options!==void 0&&(_options$gltf2=options.gltf)!==null&&_options$gltf2!==void 0&&_options$gltf2.loadBuffers&&gltf.json.buffers){yield loadBuffers(gltf,options,context);}if(options!==null&&options!==void 0&&(_options$gltf3=options.gltf)!==null&&_options$gltf3!==void 0&&_options$gltf3.loadImages){var _promise=loadImages(gltf,options,context);promises.push(_promise);}var promise=decodeExtensions(gltf,options,context);promises.push(promise);yield Promise.all(promises);gltf.json.gltfArrayBuffer=arrayBufferOrString;// !zeg add 兼容gltf
  78915. return options!==null&&options!==void 0&&(_options$gltf4=options.gltf)!==null&&_options$gltf4!==void 0&&_options$gltf4.postProcess?postProcessGLTF(gltf,options):gltf;});return _parseGLTF.apply(this,arguments);}function parseGLTFContainerSync(gltf,data,byteOffset,options){if(options.uri){gltf.baseUri=options.uri;}if(data instanceof ArrayBuffer&&!isGLB(data,byteOffset,options)){var textDecoder=new TextDecoder();data=textDecoder.decode(data);}if(typeof data==='string'){gltf.json=parseJSON(data);}else if(data instanceof ArrayBuffer){var glb={};byteOffset=parseGLBSync(glb,data,byteOffset,options.glb);assert$1(glb.type==='glTF',"Invalid GLB magic string ".concat(glb.type));gltf._glb=glb;gltf.json=glb.json;}else {assert$1(false,'GLTF: must be ArrayBuffer or string');}var buffers=gltf.json.buffers||[];gltf.buffers=new Array(buffers.length).fill(null);if(gltf._glb&&gltf._glb.header.hasBinChunk){var{binChunks}=gltf._glb;gltf.buffers[0]={arrayBuffer:binChunks[0].arrayBuffer,byteOffset:binChunks[0].byteOffset,byteLength:binChunks[0].byteLength};}var images=gltf.json.images||[];gltf.images=new Array(images.length).fill({});}function loadBuffers(_x104,_x105,_x106){return _loadBuffers.apply(this,arguments);}function _loadBuffers(){_loadBuffers=_asyncToGenerator(function*(gltf,options,context){var buffers=gltf.json.buffers||[];for(var _i56=0;_i56<buffers.length;++_i56){var buffer=buffers[_i56];if(buffer.uri){var _context$fetch,_response$arrayBuffer;var{fetch:_fetch}=context;assert$1(_fetch);var uri=resolveUrl(buffer.uri,options);var response=yield context===null||context===void 0?void 0:(_context$fetch=context.fetch)===null||_context$fetch===void 0?void 0:_context$fetch.call(context,uri);var arrayBuffer=yield response===null||response===void 0?void 0:(_response$arrayBuffer=response.arrayBuffer)===null||_response$arrayBuffer===void 0?void 0:_response$arrayBuffer.call(response);gltf.buffers[_i56]={arrayBuffer,byteOffset:0,byteLength:arrayBuffer.byteLength};delete buffer.uri;}}});return _loadBuffers.apply(this,arguments);}function loadImages(_x107,_x108,_x109){return _loadImages.apply(this,arguments);}function _loadImages(){_loadImages=_asyncToGenerator(function*(gltf,options,context){var imageIndices=getReferencesImageIndices(gltf);var images=gltf.json.images||[];var promises=[];for(var imageIndex of imageIndices){promises.push(loadImage(gltf,images[imageIndex],imageIndex,options,context));}return yield Promise.all(promises);});return _loadImages.apply(this,arguments);}function getReferencesImageIndices(gltf){var imageIndices=new Set();var textures=gltf.json.textures||[];for(var texture of textures){if(texture.source!==undefined){imageIndices.add(texture.source);}}return Array.from(imageIndices).sort();}function loadImage(_x110,_x111,_x112,_x113,_x114){return _loadImage.apply(this,arguments);}function _loadImage(){_loadImage=_asyncToGenerator(function*(gltf,image,index,options,context){var{fetch,parse}=context;var arrayBuffer;if(image.uri){var uri=resolveUrl(image.uri,options);var response=yield fetch(uri);arrayBuffer=yield response.arrayBuffer();}if(Number.isFinite(image.bufferView)){var array=getTypedArrayForBufferView(gltf.json,gltf.buffers,image.bufferView);arrayBuffer=sliceArrayBuffer(array.buffer,array.byteOffset,array.byteLength);}assert$1(arrayBuffer,'glTF image has no data');var parsedImage=yield parse(arrayBuffer,[ImageLoader$1,BasisLoader],{mimeType:image.mimeType,basis:options.basis||{format:selectSupportedBasisFormat()}},context);if(parsedImage&&parsedImage[0]){parsedImage={compressed:true,mipmaps:false,width:parsedImage[0].width,height:parsedImage[0].height,data:parsedImage};}gltf.images=gltf.images||[];gltf.images[index]=parsedImage;});return _loadImage.apply(this,arguments);}var GLTFLoader$1={name:'glTF',id:'gltf',module:'gltf',version:VERSION$3,extensions:['gltf','glb'],mimeTypes:['model/gltf+json','model/gltf-binary'],text:true,binary:true,tests:['glTF'],parse:parse$1,options:{gltf:{normalize:true,loadBuffers:true,loadImages:true,decompressMeshes:true,postProcess:true},log:console},deprecatedOptions:{fetchImages:'gltf.loadImages',createImages:'gltf.loadImages',decompress:'gltf.decompressMeshes',postProcess:'gltf.postProcess',gltf:{decompress:'gltf.decompressMeshes'}}};function parse$1(_x115){return _parse$3.apply(this,arguments);}function _parse$3(){_parse$3=_asyncToGenerator(function*(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;options=_objectSpread2(_objectSpread2({},GLTFLoader$1.options),options);options.gltf=_objectSpread2(_objectSpread2({},GLTFLoader$1.options.gltf),options.gltf);var{byteOffset=0}=options;var gltf={};return yield parseGLTF(gltf,arrayBuffer,byteOffset,options,context);});return _parse$3.apply(this,arguments);}var GLTF_FORMAT={URI:0,EMBEDDED:1};function parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options){tile.rotateYtoZ=true;var gltfByteLength=tile.byteOffset+tile.byteLength-byteOffset;if(gltfByteLength===0){throw new Error('glTF byte length must be greater than 0.');}tile.gltfUpAxis=options['3d-tiles']&&options['3d-tiles'].assetGltfUpAxis?options['3d-tiles'].assetGltfUpAxis:'Y';tile.gltfArrayBuffer=sliceArrayBuffer(arrayBuffer,byteOffset,gltfByteLength);tile.gltfByteOffset=0;tile.gltfByteLength=gltfByteLength;if(byteOffset%4===0);else {console.warn("".concat(tile.type,": embedded glb is not aligned to a 4-byte boundary."));}return tile.byteOffset+tile.byteLength;}function extractGLTF(_x116,_x117,_x118,_x119){return _extractGLTF.apply(this,arguments);}function _extractGLTF(){_extractGLTF=_asyncToGenerator(function*(tile,gltfFormat,options,context){var tile3DOptions=options['3d-tiles']||{};extractGLTFBufferOrURL(tile,gltfFormat);if(tile3DOptions.loadGLTF){var{parse:_parse3,fetch:_fetch2}=context;if(tile.gltfUrl){tile.gltfArrayBuffer=yield _fetch2(tile.gltfUrl,options);tile.gltfByteOffset=0;}if(tile.gltfArrayBuffer){tile.gltf=yield _parse3(tile.gltfArrayBuffer,GLTFLoader$1,options,context);delete tile.gltfArrayBuffer;delete tile.gltfByteOffset;delete tile.gltfByteLength;}}});return _extractGLTF.apply(this,arguments);}function extractGLTFBufferOrURL(tile,gltfFormat,options){switch(gltfFormat){case GLTF_FORMAT.URI:var gltfUrlBytes=new Uint8Array(tile.gltfArrayBuffer,tile.gltfByteOffset);var textDecoder=new TextDecoder();var gltfUrl=textDecoder.decode(gltfUrlBytes);tile.gltfUrl=gltfUrl.replace(/[\s\0]+$/,'');delete tile.gltfArrayBuffer;delete tile.gltfByteOffset;delete tile.gltfByteLength;break;case GLTF_FORMAT.EMBEDDED:break;default:throw new Error('b3dm: Illegal glTF format field');}}function parseBatchedModel3DTile(_x120,_x121,_x122,_x123,_x124){return _parseBatchedModel3DTile.apply(this,arguments);}function _parseBatchedModel3DTile(){_parseBatchedModel3DTile=_asyncToGenerator(function*(tile,arrayBuffer,byteOffset,options,context){var _tile$gltf;byteOffset=parseBatchedModel(tile,arrayBuffer,byteOffset,options);yield extractGLTF(tile,GLTF_FORMAT.EMBEDDED,options,context);var extensions=tile===null||tile===void 0?void 0:(_tile$gltf=tile.gltf)===null||_tile$gltf===void 0?void 0:_tile$gltf.extensions;if(extensions&&extensions.CESIUM_RTC){tile.rtcCenter=extensions.CESIUM_RTC.center;}return byteOffset;});return _parseBatchedModel3DTile.apply(this,arguments);}function parseBatchedModel(tile,arrayBuffer,byteOffset,options,context){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileTablesSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options);var featureTable=new Tile3DFeatureTable(tile.featureTableJson,tile.featureTableBinary);tile.rtcCenter=featureTable.getGlobalProperty('RTC_CENTER',GL$1.FLOAT,3);return byteOffset;}function parseInstancedModel3DTile(_x125,_x126,_x127,_x128,_x129){return _parseInstancedModel3DTile.apply(this,arguments);}function _parseInstancedModel3DTile(){_parseInstancedModel3DTile=_asyncToGenerator(function*(tile,arrayBuffer,byteOffset,options,context){byteOffset=parseInstancedModel(tile,arrayBuffer,byteOffset,options);yield extractGLTF(tile,tile.gltfFormat,options,context);return byteOffset;});return _parseInstancedModel3DTile.apply(this,arguments);}function parseInstancedModel(tile,arrayBuffer,byteOffset,options,context){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);if(tile.version!==1){throw new Error("Instanced 3D Model version ".concat(tile.version," is not supported"));}byteOffset=parse3DTileTablesHeaderSync(tile,arrayBuffer,byteOffset);var view=new DataView(arrayBuffer);tile.gltfFormat=view.getUint32(byteOffset,true);byteOffset+=4;byteOffset=parse3DTileTablesSync(tile,arrayBuffer,byteOffset);byteOffset=parse3DTileGLTFViewSync(tile,arrayBuffer,byteOffset,options);if(tile.featureTableJsonByteLength===0){throw new Error('i3dm parser: featureTableJsonByteLength is zero.');}var featureTable=new Tile3DFeatureTable(tile.featureTableJson,tile.featureTableBinary);var instancesLength=featureTable.getGlobalProperty('INSTANCES_LENGTH');featureTable.featuresLength=instancesLength;if(!Number.isFinite(instancesLength)){throw new Error('i3dm parser: INSTANCES_LENGTH must be defined');}tile.eastNorthUp=featureTable.getGlobalProperty('EAST_NORTH_UP');tile.rtcCenter=featureTable.getGlobalProperty('RTC_CENTER',GL$1.FLOAT,3);var batchTable=new Tile3DBatchTableParser(tile.batchTableJson,tile.batchTableBinary,instancesLength);extractInstancedAttributes(tile,featureTable,batchTable,instancesLength);return byteOffset;}function extractInstancedAttributes(tile,featureTable,batchTable,instancesLength){var collectionOptions={instances:new Array(instancesLength),batchTable:tile._batchTable,cull:false,url:undefined,gltf:undefined,basePath:undefined,incrementallyLoadTextures:false,forwardAxis:[1,0,0]};var instances=collectionOptions.instances;var instancePosition=new Vector3$1();new Vector3$1();new Vector3$1();new Vector3$1();var instanceRotation=new Matrix3$1();var instanceQuaternion=new Quaternion$1();var instanceScale=new Vector3$1();var instanceTranslationRotationScale={};var instanceTransform=new Matrix4$1();var scratch1=[];var scratch2=[];var scratchVector1=new Vector3$1();var scratchVector2=new Vector3$1();for(var _i53=0;_i53<instancesLength;_i53++){var position=void 0;if(featureTable.hasProperty('POSITION')){position=featureTable.getProperty('POSITION',GL$1.FLOAT,3,_i53,instancePosition);}else if(featureTable.hasProperty('POSITION_QUANTIZED')){position=featureTable.getProperty('POSITION_QUANTIZED',GL$1.UNSIGNED_SHORT,3,_i53,instancePosition);var quantizedVolumeOffset=featureTable.getGlobalProperty('QUANTIZED_VOLUME_OFFSET',GL$1.FLOAT,3,scratchVector1);if(!quantizedVolumeOffset){throw new Error('i3dm parser: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions.');}var quantizedVolumeScale=featureTable.getGlobalProperty('QUANTIZED_VOLUME_SCALE',GL$1.FLOAT,3,scratchVector2);if(!quantizedVolumeScale){throw new Error('i3dm parser: QUANTIZED_VOLUME_SCALE must be defined for quantized positions.');}var MAX_UNSIGNED_SHORT=65535.0;for(var j=0;j<3;j++){position[j]=position[j]/MAX_UNSIGNED_SHORT*quantizedVolumeScale[j]+quantizedVolumeOffset[j];}}if(!position){throw new Error('i3dm: POSITION or POSITION_QUANTIZED must be defined for each instance.');}instancePosition.copy(position);instanceTranslationRotationScale.translation=instancePosition;tile.normalUp=featureTable.getProperty('NORMAL_UP',GL$1.FLOAT,3,_i53,scratch1);tile.normalRight=featureTable.getProperty('NORMAL_RIGHT',GL$1.FLOAT,3,_i53,scratch2);if(tile.normalUp){if(!tile.normalRight){throw new Error('i3dm: Custom orientation requires both NORMAL_UP and NORMAL_RIGHT.');}tile.hasCustomOrientation=true;}else {tile.octNormalUp=featureTable.getProperty('NORMAL_UP_OCT32P',GL$1.UNSIGNED_SHORT,2,scratch1);tile.octNormalRight=featureTable.getProperty('NORMAL_RIGHT_OCT32P',GL$1.UNSIGNED_SHORT,2,scratch2);if(tile.octNormalUp){if(!tile.octNormalRight){throw new Error('i3dm: oct-encoded orientation requires NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P');}throw new Error('i3dm: oct-encoded orientation not implemented');}else if(tile.eastNorthUp){Ellipsoid.WGS84.eastNorthUpToFixedFrame(instancePosition,instanceTransform);instanceTransform.getRotationMatrix3(instanceRotation);}else {instanceRotation.identity();}}instanceQuaternion.fromMatrix3(instanceRotation);instanceTranslationRotationScale.rotation=instanceQuaternion;instanceScale.set(1.0,1.0,1.0);var _scale=featureTable.getProperty('SCALE',GL$1.FLOAT,1,_i53);if(Number.isFinite(_scale)){instanceScale.multiplyByScalar(_scale);}var nonUniformScale=featureTable.getProperty('SCALE_NON_UNIFORM',GL$1.FLOAT,3,_i53,scratch1);if(nonUniformScale){instanceScale.scale(nonUniformScale);}instanceTranslationRotationScale.scale=instanceScale;var batchId=featureTable.getProperty('BATCH_ID',GL$1.UNSIGNED_SHORT,1,_i53);if(batchId===undefined){batchId=_i53;}var rotationMatrix=new Matrix4$1().fromQuaternion(instanceTranslationRotationScale.rotation);instanceTransform.identity();instanceTransform.translate(instanceTranslationRotationScale.translation);instanceTransform.multiplyRight(rotationMatrix);instanceTransform.scale(instanceTranslationRotationScale.scale);var modelMatrix=instanceTransform.clone();instances[_i53]={modelMatrix,batchId};}tile.instances=instances;}function parseComposite3DTile(_x130,_x131,_x132,_x133,_x134,_x135){return _parseComposite3DTile.apply(this,arguments);}function _parseComposite3DTile(){_parseComposite3DTile=_asyncToGenerator(function*(tile,arrayBuffer,byteOffset,options,context,parse3DTile){byteOffset=parse3DTileHeaderSync(tile,arrayBuffer,byteOffset);var view=new DataView(arrayBuffer);tile.tilesLength=view.getUint32(byteOffset,true);byteOffset+=4;tile.tiles=[];while(tile.tiles.length<tile.tilesLength&&tile.byteLength-byteOffset>12){var subtile={};tile.tiles.push(subtile);byteOffset=yield parse3DTile(arrayBuffer,byteOffset,options,context,subtile);}return byteOffset;});return _parseComposite3DTile.apply(this,arguments);}function parseGltf3DTile(_x136,_x137,_x138,_x139){return _parseGltf3DTile.apply(this,arguments);}function _parseGltf3DTile(){_parseGltf3DTile=_asyncToGenerator(function*(tile,arrayBuffer,options,context){tile.rotateYtoZ=true;tile.gltfUpAxis=options['3d-tiles']&&options['3d-tiles'].assetGltfUpAxis?options['3d-tiles'].assetGltfUpAxis:'Y';var{parse}=context;tile.gltf=yield parse(arrayBuffer,GLTFLoader$1,options,context);});return _parseGltf3DTile.apply(this,arguments);}function parse3DTile(_x140){return _parse3DTile.apply(this,arguments);}function _parse3DTile(){_parse3DTile=_asyncToGenerator(function*(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;var tile=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};tile.byteOffset=byteOffset;tile.type=getMagicString$1(arrayBuffer,byteOffset);switch(tile.type){case TILE3D_TYPE.COMPOSITE:return yield parseComposite3DTile(tile,arrayBuffer,byteOffset,options,context,parse3DTile);case TILE3D_TYPE.BATCHED_3D_MODEL:return yield parseBatchedModel3DTile(tile,arrayBuffer,byteOffset,options,context);case TILE3D_TYPE.GLTF:return yield parseGltf3DTile(tile,arrayBuffer,options,context);case TILE3D_TYPE.INSTANCED_3D_MODEL:return yield parseInstancedModel3DTile(tile,arrayBuffer,byteOffset,options,context);case TILE3D_TYPE.POINT_CLOUD:return yield parsePointCloud3DTile(tile,arrayBuffer,byteOffset,options,context);default:throw new Error("3DTileLoader: unknown type ".concat(tile.type));}});return _parse3DTile.apply(this,arguments);}var SUBTREE_FILE_MAGIC=0x74627573;var SUBTREE_FILE_VERSION=1;function parse3DTilesSubtree(_x141){return _parse3DTilesSubtree.apply(this,arguments);}function _parse3DTilesSubtree(){_parse3DTilesSubtree=_asyncToGenerator(function*(data){var magic=new Uint32Array(data.slice(0,4));if(magic[0]!==SUBTREE_FILE_MAGIC){throw new Error('Wrong subtree file magic number');}var version=new Uint32Array(data.slice(4,8));if(version[0]!==SUBTREE_FILE_VERSION){throw new Error('Wrong subtree file verson, must be 1');}var jsonByteLength=parseUint64Value(data.slice(8,16));var stringAttribute=new Uint8Array(data,24,jsonByteLength);var textDecoder=new TextDecoder('utf8');var string=textDecoder.decode(stringAttribute);var subtree=JSON.parse(string);var binaryByteLength=parseUint64Value(data.slice(16,24));var internalBinaryBuffer=new ArrayBuffer(0);if(binaryByteLength){internalBinaryBuffer=data.slice(24+jsonByteLength);}if('bufferView'in subtree.tileAvailability){subtree.tileAvailability.explicitBitstream=yield getExplicitBitstream(subtree,'tileAvailability',internalBinaryBuffer);}if('bufferView'in subtree.contentAvailability){subtree.contentAvailability.explicitBitstream=yield getExplicitBitstream(subtree,'contentAvailability',internalBinaryBuffer);}if('bufferView'in subtree.childSubtreeAvailability){subtree.childSubtreeAvailability.explicitBitstream=yield getExplicitBitstream(subtree,'childSubtreeAvailability',internalBinaryBuffer);}return subtree;});return _parse3DTilesSubtree.apply(this,arguments);}function getExplicitBitstream(_x142,_x143,_x144){return _getExplicitBitstream.apply(this,arguments);}function _getExplicitBitstream(){_getExplicitBitstream=_asyncToGenerator(function*(subtree,name,internalBinaryBuffer){var bufferViewIndex=subtree[name].bufferView;var bufferView=subtree.bufferViews[bufferViewIndex];var buffer=subtree.buffers[bufferView.buffer];if(buffer.uri){var response=yield fetchFile(buffer.uri);var data=yield response.arrayBuffer();return new Uint8Array(data,bufferView.byteOffset,bufferView.byteLength);}return new Uint8Array(internalBinaryBuffer,bufferView.byteOffset,bufferView.byteLength);});return _getExplicitBitstream.apply(this,arguments);}function parseUint64Value(buffer){var dataView=new DataView(buffer);var left=dataView.getUint32(0,true);var right=dataView.getUint32(4,true);return left+2**32*right;}var Tile3DSubtreeLoader={id:'3d-tiles-subtree',name:'3D Tiles Subtree',module:'3d-tiles',version:VERSION$5,extensions:['subtree'],mimeTypes:['application/octet-stream'],tests:['subtree'],parse:parse3DTilesSubtree,options:{}};var QUADTREE_DEVISION_COUNT=4;var OCTREE_DEVISION_COUNT=8;var SUBDIVISION_COUNT_MAP={QUADTREE:QUADTREE_DEVISION_COUNT,OCTREE:OCTREE_DEVISION_COUNT};function parseImplicitTiles(_x145,_x146){return _parseImplicitTiles.apply(this,arguments);}function _parseImplicitTiles(){_parseImplicitTiles=_asyncToGenerator(function*(subtree,options){var parentData=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{mortonIndex:0,x:0,y:0,z:0};var childIndex=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var level=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalData=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{level:0,mortonIndex:0,x:0,y:0,z:0};var{subdivisionScheme,subtreeLevels,maximumLevel,contentUrlTemplate,subtreesUriTemplate,basePath}=options;var tile={children:[],lodMetricValue:0,contentUrl:''};var childrenPerTile=SUBDIVISION_COUNT_MAP[subdivisionScheme];var childX=childIndex&0b01;var childY=childIndex>>1&0b01;var childZ=childIndex>>2&0b01;var levelOffset=(childrenPerTile**level-1)/(childrenPerTile-1);var childTileMortonIndex=concatBits(parentData.mortonIndex,childIndex);var tileAvailabilityIndex=levelOffset+childTileMortonIndex;var childTileX=concatBits(parentData.x,childX);var childTileY=concatBits(parentData.y,childY);var childTileZ=concatBits(parentData.z,childZ);var isChildSubtreeAvailable=false;if(level+1>subtreeLevels){isChildSubtreeAvailable=getAvailabilityResult(subtree.childSubtreeAvailability,childTileMortonIndex);}var x=concatBits(globalData.x,childTileX);var y=concatBits(globalData.y,childTileY);var z=concatBits(globalData.z,childTileZ);var lev=level+globalData.level;if(isChildSubtreeAvailable){var subtreePath="".concat(basePath,"/").concat(subtreesUriTemplate);var childSubtreeUrl=replaceContentUrlTemplate(subtreePath,lev,x,y,z);var childSubtree=yield load(childSubtreeUrl,Tile3DSubtreeLoader);subtree=childSubtree;globalData.mortonIndex=childTileMortonIndex;globalData.x=childTileX;globalData.y=childTileY;globalData.z=childTileZ;globalData.level=level;childTileMortonIndex=0;tileAvailabilityIndex=0;childTileX=0;childTileY=0;childTileZ=0;level=0;}var isTileAvailable=getAvailabilityResult(subtree.tileAvailability,tileAvailabilityIndex);if(!isTileAvailable||level>maximumLevel){return tile;}var isContentAvailable=getAvailabilityResult(subtree.contentAvailability,tileAvailabilityIndex);if(isContentAvailable){tile.contentUrl=replaceContentUrlTemplate(contentUrlTemplate,lev,x,y,z);}var childTileLevel=level+1;var pData={mortonIndex:childTileMortonIndex,x:childTileX,y:childTileY,z:childTileZ};for(var index=0;index<childrenPerTile;index++){var currentTile=yield parseImplicitTiles(subtree,options,pData,index,childTileLevel,globalData);if(currentTile.contentUrl||currentTile.children.length){var globalLevel=lev+1;var childCoordinates={childTileX,childTileY,childTileZ};var formattedTile=formatTileData(currentTile,globalLevel,childCoordinates,options);tile.children.push(formattedTile);}}return tile;});return _parseImplicitTiles.apply(this,arguments);}function getAvailabilityResult(availabilityData,index){if('constant'in availabilityData){return Boolean(availabilityData.constant);}if(availabilityData.explicitBitstream){return getBooleanValueFromBitstream(index,availabilityData.explicitBitstream);}return false;}function formatTileData(tile,level,childCoordinates,options){var{basePath,refine,getRefine,lodMetricType,getTileType,rootLodMetricValue,rootBoundingVolume}=options;var uri=tile.contentUrl&&tile.contentUrl.replace("".concat(basePath,"/"),'');var lodMetricValue=rootLodMetricValue/2**level;var boundingVolume=calculateBoundingVolumeForChildTile(level,rootBoundingVolume,childCoordinates);return {children:tile.children,contentUrl:tile.contentUrl,content:{uri},id:tile.contentUrl,refine:getRefine(refine),type:getTileType(tile),lodMetricType,lodMetricValue,boundingVolume};}function calculateBoundingVolumeForChildTile(level,rootBoundingVolume,childCoordinates){if(rootBoundingVolume.region){var{childTileX,childTileY,childTileZ}=childCoordinates;var[west,south,east,north,minimumHeight,maximumHeight]=rootBoundingVolume.region;var boundingVolumesCount=2**level;var sizeX=(east-west)/boundingVolumesCount;var sizeY=(north-south)/boundingVolumesCount;var sizeZ=(maximumHeight-minimumHeight)/boundingVolumesCount;var[childWest,childEast]=[west+sizeX*childTileX,west+sizeX*(childTileX+1)];var[childSouth,childNorth]=[south+sizeY*childTileY,south+sizeY*(childTileY+1)];var[childMinimumHeight,childMaximumHeight]=[minimumHeight+sizeZ*childTileZ,minimumHeight+sizeZ*(childTileZ+1)];return {region:[childWest,childSouth,childEast,childNorth,childMinimumHeight,childMaximumHeight]};}console.warn('Unsupported bounding volume type: ',rootBoundingVolume);return null;}function concatBits(first,second){return parseInt(first.toString(2)+second.toString(2),2);}function replaceContentUrlTemplate(templateUrl,level,x,y,z){var mapUrl=generateMapUrl({level,x,y,z});return templateUrl.replace(/{level}|{x}|{y}|{z}/gi,matched=>mapUrl[matched]);}function generateMapUrl(items){var mapUrl={};for(var key in items){mapUrl["{".concat(key,"}")]=items[key];}return mapUrl;}function getBooleanValueFromBitstream(availabilityIndex,availabilityBuffer){var byteIndex=Math.floor(availabilityIndex/8);var bitIndex=availabilityIndex%8;var bitValue=availabilityBuffer[byteIndex]>>bitIndex&1;return bitValue===1;}function getTileType(tile){if(!tile.contentUrl){return TILE_TYPE.EMPTY;}var contentUrl=tile.contentUrl;var fileExtension=contentUrl.split('.').pop();switch(fileExtension){case'pnts':return TILE_TYPE.POINTCLOUD;case'i3dm':case'b3dm':case'glb':case'gltf':return TILE_TYPE.SCENEGRAPH;default:return fileExtension;}}function getRefine(refine){switch(refine){case'REPLACE':case'replace':return TILE_REFINEMENT.REPLACE;case'ADD':case'add':return TILE_REFINEMENT.ADD;default:return refine;}}function normalizeTileData(tile,options){if(!tile){return null;}if(tile.content){var contentUri=tile.content.uri||tile.content.url;tile.contentUrl="".concat(options.basePath,"/").concat(contentUri);}tile.id=tile.contentUrl;tile.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tile.lodMetricValue=tile.geometricError;tile.transformMatrix=tile.transform;tile.type=getTileType(tile);tile.refine=getRefine(tile.refine);return tile;}function normalizeTileHeaders(tileset){var basePath=tileset.basePath;var root=normalizeTileData(tileset.root,tileset);var stack=[];stack.push(root);while(stack.length>0){var tile=stack.pop()||{};var children=tile.children||[];for(var childHeader of children){normalizeTileData(childHeader,{basePath});stack.push(childHeader);}}return root;}function normalizeImplicitTileHeaders(_x147){return _normalizeImplicitTileHeaders.apply(this,arguments);}function _normalizeImplicitTileHeaders(){_normalizeImplicitTileHeaders=_asyncToGenerator(function*(tileset){if(!tileset.root){return null;}var basePath=tileset.basePath;var implicitTilingExtension=tileset.root.extensions['3DTILES_implicit_tiling'];var{subdivisionScheme,maximumLevel,subtreeLevels,subtrees:{uri:subtreesUriTemplate}}=implicitTilingExtension;var subtreeUrl=replaceContentUrlTemplate(subtreesUriTemplate,0,0,0,0);var rootSubtreeUrl="".concat(basePath,"/").concat(subtreeUrl);var rootSubtree=yield load(rootSubtreeUrl,Tile3DSubtreeLoader);var contentUrlTemplate="".concat(basePath,"/").concat(tileset.root.content.uri);var refine=tileset.root.refine;var rootLodMetricValue=tileset.root.geometricError;var rootBoundingVolume=tileset.root.boundingVolume;var options={contentUrlTemplate,subtreesUriTemplate,subdivisionScheme,subtreeLevels,maximumLevel,refine,basePath,lodMetricType:LOD_METRIC_TYPE.GEOMETRIC_ERROR,rootLodMetricValue,rootBoundingVolume,getTileType,getRefine};return yield normalizeImplicitTileData(tileset.root,rootSubtree,options);});return _normalizeImplicitTileHeaders.apply(this,arguments);}function normalizeImplicitTileData(_x148,_x149,_x150){return _normalizeImplicitTileData.apply(this,arguments);}function _normalizeImplicitTileData(){_normalizeImplicitTileData=_asyncToGenerator(function*(tile,rootSubtree,options){if(!tile){return null;}tile.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tile.lodMetricValue=tile.geometricError;tile.transformMatrix=tile.transform;var{children,contentUrl}=yield parseImplicitTiles(rootSubtree,options);if(contentUrl){tile.contentUrl=contentUrl;tile.content={uri:contentUrl.replace("".concat(options.basePath,"/"),'')};}tile.refine=getRefine(tile.refine);tile.type=getTileType(tile);tile.children=children;tile.id=tile.contentUrl;return tile;});return _normalizeImplicitTileData.apply(this,arguments);}var IMPLICIT_TILING_EXTENSION_NAME='3DTILES_implicit_tiling';var Tiles3DLoader={id:'3d-tiles',name:'3D Tiles',module:'3d-tiles',version:VERSION$5,extensions:['cmpt','pnts','b3dm','i3dm'],mimeTypes:['application/octet-stream'],tests:['cmpt','pnts','b3dm','i3dm'],parse: parse$4,options:{'3d-tiles':{loadGLTF:true,decodeQuantizedPositions:false,isTileset:'auto',assetGltfUpAxis:null}}};function getBaseUri(tileset){return dirname(tileset.url);}function parseTile(_x151,_x152,_x153){return _parseTile.apply(this,arguments);}function _parseTile(){_parseTile=_asyncToGenerator(function*(arrayBuffer,options,context){var tile={content:{featureIds:null}};var byteOffset=0;yield parse3DTile(arrayBuffer,byteOffset,options,context,tile.content);return tile.content;});return _parseTile.apply(this,arguments);}function parseTileset(_x154,_x155,_x156){return _parseTileset.apply(this,arguments);}function _parseTileset(){_parseTileset=_asyncToGenerator(function*(data,options,context){var _tilesetJson$root;var tilesetJson=JSON.parse(new TextDecoder().decode(data));tilesetJson.loader=options.loader||Tiles3DLoader;tilesetJson.url=context.url;tilesetJson.basePath=getBaseUri(tilesetJson);tilesetJson.root=hasImplicitTilingExtension(tilesetJson)?yield normalizeImplicitTileHeaders(tilesetJson):normalizeTileHeaders(tilesetJson);tilesetJson.type=TILESET_TYPE.TILES3D;tilesetJson.lodMetricType=LOD_METRIC_TYPE.GEOMETRIC_ERROR;tilesetJson.lodMetricValue=((_tilesetJson$root=tilesetJson.root)===null||_tilesetJson$root===void 0?void 0:_tilesetJson$root.lodMetricValue)||0;return tilesetJson;});return _parseTileset.apply(this,arguments);}function parse$4(_x157,_x158,_x159){return _parse.apply(this,arguments);}function _parse(){_parse=_asyncToGenerator(function*(data,options,context){var loaderOptions=options['3d-tiles']||{};var isTileset;if(loaderOptions.isTileset==='auto'){isTileset=context.url&&context.url.indexOf('.json')!==-1;}else {isTileset=loaderOptions.isTileset;}if(isTileset){data=yield parseTileset(data,options,context);}else {data=yield parseTile(data,options,context);}return data;});return _parse.apply(this,arguments);}function hasImplicitTilingExtension(tilesetJson){var _tilesetJson$extensio,_tilesetJson$extensio2;return (tilesetJson===null||tilesetJson===void 0?void 0:(_tilesetJson$extensio=tilesetJson.extensionsRequired)===null||_tilesetJson$extensio===void 0?void 0:_tilesetJson$extensio.includes(IMPLICIT_TILING_EXTENSION_NAME))&&(tilesetJson===null||tilesetJson===void 0?void 0:(_tilesetJson$extensio2=tilesetJson.extensionsUsed)===null||_tilesetJson$extensio2===void 0?void 0:_tilesetJson$extensio2.includes(IMPLICIT_TILING_EXTENSION_NAME));}var CESIUM_ION_URL='https://api.cesium.com/v1/assets';function getIonTilesetMetadata(_x160,_x161){return _getIonTilesetMetadata.apply(this,arguments);}function _getIonTilesetMetadata(){_getIonTilesetMetadata=_asyncToGenerator(function*(accessToken,assetId){if(!assetId){var assets=yield getIonAssets(accessToken);for(var item of assets.items){if(item.type==='3DTILES'){assetId=item.id;}}}var ionAssetMetadata=yield getIonAssetMetadata(accessToken,assetId);var{type,url}=ionAssetMetadata;assert$7(type==='3DTILES'&&url);ionAssetMetadata.headers={Authorization:"Bearer ".concat(ionAssetMetadata.accessToken)};return ionAssetMetadata;});return _getIonTilesetMetadata.apply(this,arguments);}function getIonAssets(_x162){return _getIonAssets.apply(this,arguments);}function _getIonAssets(){_getIonAssets=_asyncToGenerator(function*(accessToken){assert$7(accessToken);var url=CESIUM_ION_URL;var headers={Authorization:"Bearer ".concat(accessToken)};var response=yield fetchFile(url,{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}return yield response.json();});return _getIonAssets.apply(this,arguments);}function getIonAssetMetadata(_x163,_x164){return _getIonAssetMetadata.apply(this,arguments);}function _getIonAssetMetadata(){_getIonAssetMetadata=_asyncToGenerator(function*(accessToken,assetId){assert$7(accessToken,assetId);var headers={Authorization:"Bearer ".concat(accessToken)};var url="".concat(CESIUM_ION_URL,"/").concat(assetId);var response=yield fetchFile("".concat(url),{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}var metadata=yield response.json();response=yield fetchFile("".concat(url,"/endpoint"),{fetch:{headers}});if(!response.ok){throw new Error(response.statusText);}var tilesetInfo=yield response.json();metadata=_objectSpread2(_objectSpread2({},metadata),tilesetInfo);return metadata;});return _getIonAssetMetadata.apply(this,arguments);}function preload(_x165){return _preload.apply(this,arguments);}function _preload(){_preload=_asyncToGenerator(function*(url){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};options=options['cesium-ion']||{};var{accessToken}=options;var assetId=options.assetId;if(!Number.isFinite(assetId)){var matched=url.match(/\/([0-9]+)\/tileset.json/);assetId=matched&&matched[1];}return getIonTilesetMetadata(accessToken,assetId);});return _preload.apply(this,arguments);}var CesiumIonLoader=_objectSpread2(_objectSpread2({},Tiles3DLoader),{},{id:'cesium-ion',name:'Cesium Ion',preload,parse:function(){var _parse2=_asyncToGenerator(function*(data,options,context){options=_objectSpread2({},options);options['3d-tiles']=options['cesium-ion'];options.loader=CesiumIonLoader;return Tiles3DLoader.parse(data,options,context);});function parse(_x166,_x167,_x168){return _parse2.apply(this,arguments);}return parse;}(),options:{'cesium-ion':_objectSpread2(_objectSpread2({},Tiles3DLoader.options['3d-tiles']),{},{accessToken:null})}});// From https://github.com/potree/potree/blob/master/src/materials/PointCloudMaterial.js
  78916. function generateGradientTexture(gradient){var size=64;// create canvas
  78917. var canvas=document.createElement('canvas');canvas.width=size;canvas.height=size;// get context
  78918. var context=canvas.getContext('2d');// draw gradient
  78919. context.rect(0,0,size,size);var ctxGradient=context.createLinearGradient(0,0,size,size);for(var _i54=0;_i54<gradient.length;_i54++){var step=gradient[_i54];ctxGradient.addColorStop(step[0],'#'+step[1].getHexString());}context.fillStyle=ctxGradient;context.fill();//let texture = new THREE.Texture(canvas);
  78920. var texture=new CanvasTexture(canvas);texture.needsUpdate=true;texture.minFilter=LinearFilter;texture.wrapS=RepeatWrapping;texture.wrapT=RepeatWrapping;texture.repeat.set(2,2);// textureImage = texture.image;
  78921. return texture;}function _getCameraFrustum(camera){camera.updateMatrix();// make sure camera's local matrix is updated
  78922. camera.updateMatrixWorld();// make sure camera's world matrix is updated
  78923. camera.matrixWorldInverse.copy(camera.matrixWorld).invert();var frustum=new Frustum();frustum.setFromProjectionMatrix(new Matrix4().multiplyMatrices(camera.projectionMatrix,camera.matrixWorldInverse));return frustum;}function loadersPlaneToMesh(plane){var group=new Group();// Create a basic rectangle geometry from math.gl plane
  78924. var planeGeometry=new PlaneGeometry(10,5);// Align the geometry to the plane
  78925. var coplanarPoint=new Vector3(...plane.projectPointOntoPlane([0,0,0]));var normal=new Vector3(plane.normal.x,plane.normal.y,plane.normal.z);var focalPoint=new Vector3().copy(coplanarPoint).add(normal);planeGeometry.lookAt(focalPoint);planeGeometry.translate(coplanarPoint.x,coplanarPoint.y,coplanarPoint.z);// Edges
  78926. /*
  78927. const edges = new EdgesGeometry(planeGeometry)
  78928. var dispPlane = new LineSegments(edges, new LineBasicMaterial({ color: 0x00ffff }))*/ //plane
  78929. var material=new BasicMaterial({color:0x00ffff,side:DoubleSide});var mesh=new Mesh(planeGeometry,material);var arrowHelper=new ArrowHelper(normal,coplanarPoint,5,0xffff00);group.add(arrowHelper);group.add(mesh);return group;}function loadersBoundingBoxToMesh(tile){// Create a basic rectangle geometry from math.gl half-axes
  78930. var boundUntransformed=tile.type=='empty'?tile.boundingVolume:tile.getBoundUntransformed();//empty时没创建好,直接给boundingVolume一样
  78931. /* let redColor = 0;
  78932. if (tile.content) {
  78933. //redColor = Math.min((tile.content.byteLength != void 0 ? tile.content.byteLength : 0) / 500000, 1.0);
  78934. redColor = Math.min( tile.depth / 10 , 1.0); //改
  78935. } */var hue=0;if(tile.content){hue=Math.min(tile.depth/10,1.0);//改
  78936. }var boxColor=new THREE.Color().setHSL(hue,0.9,0.85);//const boxColor = new Color(redColor, 1.0, 0.0);
  78937. var boxGeometry=new BoxGeometry(1,1,1);var boxTransform=new Matrix4();if(boundUntransformed.halfAxes){boxTransform.copy(getMatrix4FromHalfAxes(boundUntransformed.halfAxes));}else if(boundUntransformed.radius){boxGeometry.scale(boundUntransformed.radius*2,boundUntransformed.radius*2,boundUntransformed.radius*2);}boxTransform.premultiply(new Matrix4().setPosition(...boundUntransformed.center));//add
  78938. /* if(tile.type != "empty"){ //root单独处理了
  78939. boxTransform.premultiply((new Matrix4$1()).makeScale(1,1,-1))//xzw 因为mesh倒转了所以box也
  78940. }else{
  78941. console.log('empty')
  78942. } */boxGeometry.applyMatrix4(boxTransform);var edges=new EdgesGeometry(boxGeometry);var dispPlane=new LineSegments(edges,new LineBasicMaterial({color:boxColor,transparent:true}));//dispPlane.position.copy(new Vector3$1(...boundingVolume.center));
  78943. dispPlane.matrixAutoUpdate=false;//add
  78944. var label=new Potree.TextSprite({mat:new THREE.MeshBasicMaterial({transparent:true}),//depthTest:false会导致经常显示不出
  78945. backgroundColor:{r:0,g:0,b:0,a:0.1},textColor:{r:boxColor.r*255,g:boxColor.g*255,b:boxColor.b*255,a:0.9},fontsize:100,//useDepth : true ,
  78946. renderOrder:5,text:tile.id.split('/').pop().split('.b3dm')[0],//Tile_+094_-010.b3dm'
  78947. name:'tile'});label.addEventListener('mouseover',()=>{if(label.sprite.material.opacity<1)return;window.hoverTile=tile;console.log('hoverLabel',tile.id,tile._distanceToCamera);});/* let s = 0.6
  78948. label.scale.set(s,s,s) */var s=tile.tileset.options.maximumScreenSpaceError/400;label.scale.set(s,s,s);dispPlane.add(label);label.position.set(...boundUntransformed.center);//label.position.z *= -1
  78949. /* if(tile.content.byteLength == void 0){
  78950. let oldUpdate = dispPlane.updateMatrixWorld.bind(dispPlane)
  78951. dispPlane.updateMatrixWorld = (a,b)=>{
  78952. oldUpdate(a,b)
  78953. }
  78954. let oldU = dispPlane.updateMatrix.bind(dispPlane)
  78955. dispPlane.updateMatrix = (a,b)=>{
  78956. oldU(a,b)
  78957. }
  78958. } */tile.volumeBox=dispPlane;return dispPlane;}function getMatrix4FromHalfAxes(halfAxes){var m=halfAxes;var rotateMatrix=new Matrix4().fromArray([m[0]*2,m[1]*2,m[2]*2,0,m[3]*2,m[4]*2,m[5]*2,0,m[6]*2,m[7]*2,m[8]*2,0,0,0,0,1]);return rotateMatrix;}/*
  78959. * from https://github.com/tentone/geo-three
  78960. * Tree-shaking did not work, probably due to static class methods
  78961. */function datumsToSpherical(latitude,longitude){var EARTH_RADIUS=6378137;var EARTH_PERIMETER=2*Math.PI*EARTH_RADIUS;var EARTH_ORIGIN=EARTH_PERIMETER/2.0;var x=longitude*EARTH_ORIGIN/180.0;var y=Math.log(Math.tan((90+latitude)*Math.PI/360.0))/(Math.PI/180.0);y=y*EARTH_ORIGIN/180.0;return new Vector2(x,y);}var Gradients$1={// From chroma spectral http://gka.github.io/chroma.js/
  78962. SPECTRAL:[[0,new Color(0.3686,0.3098,0.6353)],[0.1,new Color(0.1961,0.5333,0.7412)],[0.2,new Color(0.4,0.7608,0.6471)],[0.3,new Color(0.6706,0.8667,0.6431)],[0.4,new Color(0.902,0.9608,0.5961)],[0.5,new Color(1.0,1.0,0.749)],[0.6,new Color(0.9961,0.8784,0.5451)],[0.7,new Color(0.9922,0.6824,0.3804)],[0.8,new Color(0.9569,0.4275,0.2627)],[0.9,new Color(0.8353,0.2431,0.3098)],[1,new Color(0.6196,0.0039,0.2588)]],PLASMA:[[0.0,new Color(0.241,0.015,0.61)],[0.1,new Color(0.387,0.001,0.654)],[0.2,new Color(0.524,0.025,0.653)],[0.3,new Color(0.651,0.125,0.596)],[0.4,new Color(0.752,0.227,0.513)],[0.5,new Color(0.837,0.329,0.431)],[0.6,new Color(0.907,0.435,0.353)],[0.7,new Color(0.963,0.554,0.272)],[0.8,new Color(0.992,0.681,0.195)],[0.9,new Color(0.987,0.822,0.144)],[1.0,new Color(0.94,0.975,0.131)]],YELLOW_GREEN:[[0,new Color(0.1647,0.2824,0.3451)],[0.1,new Color(0.1338,0.3555,0.4227)],[0.2,new Color(0.061,0.4319,0.4864)],[0.3,new Color(0.0,0.5099,0.5319)],[0.4,new Color(0.0,0.5881,0.5569)],[0.5,new Color(0.137,0.665,0.5614)],[0.6,new Color(0.2906,0.7395,0.5477)],[0.7,new Color(0.4453,0.8099,0.5201)],[0.8,new Color(0.6102,0.8748,0.485)],[0.9,new Color(0.7883,0.9323,0.4514)],[1,new Color(0.9804,0.9804,0.4314)]],VIRIDIS:[[0.0,new Color(0.267,0.005,0.329)],[0.1,new Color(0.283,0.141,0.458)],[0.2,new Color(0.254,0.265,0.53)],[0.3,new Color(0.207,0.372,0.553)],[0.4,new Color(0.164,0.471,0.558)],[0.5,new Color(0.128,0.567,0.551)],[0.6,new Color(0.135,0.659,0.518)],[0.7,new Color(0.267,0.749,0.441)],[0.8,new Color(0.478,0.821,0.318)],[0.9,new Color(0.741,0.873,0.15)],[1.0,new Color(0.993,0.906,0.144)]],INFERNO:[[0.0,new Color(0.077,0.042,0.206)],[0.1,new Color(0.225,0.036,0.388)],[0.2,new Color(0.373,0.074,0.432)],[0.3,new Color(0.522,0.128,0.42)],[0.4,new Color(0.665,0.182,0.37)],[0.5,new Color(0.797,0.255,0.287)],[0.6,new Color(0.902,0.364,0.184)],[0.7,new Color(0.969,0.516,0.063)],[0.8,new Color(0.988,0.683,0.072)],[0.9,new Color(0.961,0.859,0.298)],[1.0,new Color(0.988,0.998,0.645)]],GRAYSCALE:[[0,new Color(0,0,0)],[1,new Color(1,1,1)]],// 16 samples of the TURBU color scheme
  78963. // values taken from: https://gist.github.com/mikhailov-work/ee72ba4191942acecc03fe6da94fc73f
  78964. // original file licensed under Apache-2.0
  78965. TURBO:[[0.0,new Color(0.18995,0.07176,0.23217)],[0.07,new Color(0.25107,0.25237,0.63374)],[0.13,new Color(0.27628,0.42118,0.89123)],[0.2,new Color(0.25862,0.57958,0.99876)],[0.27,new Color(0.15844,0.73551,0.92305)],[0.33,new Color(0.09267,0.86554,0.7623)],[0.4,new Color(0.19659,0.94901,0.59466)],[0.47,new Color(0.42778,0.99419,0.38575)],[0.53,new Color(0.64362,0.98999,0.23356)],[0.6,new Color(0.80473,0.92452,0.20459)],[0.67,new Color(0.93301,0.81236,0.22667)],[0.73,new Color(0.99314,0.67408,0.20348)],[0.8,new Color(0.9836,0.49291,0.12849)],[0.87,new Color(0.92105,0.31489,0.05475)],[0.93,new Color(0.81608,0.18462,0.01809)],[1.0,new Color(0.66449,0.08436,0.00424)]],RAINBOW:[[0,new Color(0.278,0,0.714)],[1/6,new Color(0,0,1)],[2/6,new Color(0,1,1)],[3/6,new Color(0,1,0)],[4/6,new Color(1,1,0)],[5/6,new Color(1,0.64,0)],[1,new Color(1,0,0)]],CONTOUR:[[0.0,new Color(0,0,0)],[0.03,new Color(0,0,0)],[0.04,new Color(1,1,1)],[1.0,new Color(1,1,1)]]};var PointCloudFS="\n varying vec3 vColor;\n uniform float alpha;\n\n void main() {\n if (vColor == vec3(0.0, 0.0, 0.0)) {\n discard;\n } else {\n gl_FragColor = vec4( vColor, alpha);\n }\n }\n";var PointCloudVS="\n varying vec3 vColor;\n uniform sampler2D gradient;\n uniform sampler2D grayscale;\n attribute float intensity;\n attribute float classification;\n uniform vec3 rootCenter;\n uniform vec3 rootNormal;\n uniform vec2 elevationRange;\n uniform int coloring;\n uniform bool hideGround;\n uniform float maxIntensity;\n uniform float intensityContrast;\n uniform float pointSize;\n\n #ifdef USE_COLOR\n vec3 getRGB() {\n vec3 rgb = color;\n return rgb;\n }\n #endif\n\n vec3 getElevation(){\n vec4 world = modelMatrix * vec4( position, 1.0 );\n float diff = abs(dot(rootNormal, (vec3(world) - rootCenter)));\n float w = max(diff - elevationRange.x,0.0) / max(elevationRange.y - elevationRange.x,1.0);\n vec3 cElevation = texture2D(gradient, vec2(w,1.0-w)).rgb;\n\n return cElevation;\n }\n\n vec3 getIntensity(){\n // TODO: real contrast enhancement. Check https://github.com/yuki-koyama/enhancer/blob/master/shaders/enhancer.fs\n float intmod = pow(intensity, intensityContrast);\n vec3 cIntensity = texture2D(grayscale, vec2(intmod / maxIntensity ,1.0-(intmod / maxIntensity))).rgb;\n return cIntensity;\n }\n\n vec3 getClassification(){\n float classNormalized = classification / 255.0;\n vec3 cClassification = texture2D(gradient, vec2(classNormalized * 5.0,1.0-classNormalized * 5.0)).rgb;\n return cClassification;\n }\n\n vec3 getColor(){\n vec3 color;\n if (hideGround && classification == 2.0) {\n return vec3(0.0, 0.0, 0.0); \n }\n\n if (coloring == 1) {\n color = getIntensity();\n }\n else if (coloring == 2) {\n color = getClassification();\n } else if (coloring == 3) {\n color = getElevation();\n } \n #ifdef USE_COLOR\n else if (coloring == 4) {\n color = getRGB();\n }\n #endif\n else {\n color = vec3(1.0, 1.0, 1.0);\n }\n return color;\n }\n\n void main() {\n vColor = getColor();\n\n gl_PointSize = pointSize;\n gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n }\n";/** Types of coloring used when viewing point cloud tiles */var PointCloudColoring;(function(PointCloudColoring){PointCloudColoring[PointCloudColoring["Intensity"]=1]="Intensity";PointCloudColoring[PointCloudColoring["Classification"]=2]="Classification";PointCloudColoring[PointCloudColoring["Elevation"]=3]="Elevation";PointCloudColoring[PointCloudColoring["RGB"]=4]="RGB";PointCloudColoring[PointCloudColoring["White"]=5]="White";})(PointCloudColoring||(PointCloudColoring={}));/** Types of shading used when viewing b3dm (mesh) tiles */var Shading;(function(Shading){Shading[Shading["FlatTexture"]=1]="FlatTexture";Shading[Shading["ShadedTexture"]=2]="ShadedTexture";Shading[Shading["ShadedNoTexture"]=3]="ShadedNoTexture";})(Shading||(Shading={}));var GeoTransform;(function(GeoTransform){GeoTransform[GeoTransform["Reset"]=1]="Reset";GeoTransform[GeoTransform["Mercator"]=2]="Mercator";GeoTransform[GeoTransform["WGS84Cartesian"]=3]="WGS84Cartesian";})(GeoTransform||(GeoTransform={}));var gradient=Gradients$1.RAINBOW;var gradientTexture=typeof document!='undefined'?generateGradientTexture(gradient):null;var grayscale=Gradients$1.GRAYSCALE;var grayscaleTexture=typeof document!='undefined'?generateGradientTexture(grayscale):null;var defaultOptions={throttleRequests:true,maxRequests:64,updateInterval:0.1,maxConcurrency:1,maximumScreenSpaceError:16,maximumMemoryUsage:32,viewDistanceScale:1.0,skipLevelOfDetail:false,updateTransforms:true,shading:Shading.FlatTexture,transparent:false,pointCloudColoring:PointCloudColoring.White,pointSize:1.0,worker:true,wireframe:false,debug:false,basisTranscoderPath:null,dracoDecoderPath:null,material:null,computeNormals:false,shaderCallback:null,geoTransform:GeoTransform.Reset,preloadTilesCount:null};/** 3D Tiles Loader */class Loader3DTiles{/**
  78966. * Loads a tileset of 3D Tiles according to the given {@link LoaderProps}
  78967. * @public
  78968. *
  78969. * @param props - Properties for this load call {@link LoaderProps}.
  78970. * @returns An object containing the 3D Model to be added to the scene
  78971. * and a runtime engine to be updated every frame.
  78972. */static load(props){return __awaiter(this,void 0,void 0,function*(){var options=Object.assign(Object.assign({},defaultOptions),props.options);var{url}=props;var UPDATE_INTERVAL=options.updateInterval;var MAX_DEPTH_FOR_ORIENTATION=5;var loadersGLOptions={};if(options.cesiumIONToken){loadersGLOptions['cesium-ion']={accessToken:options.cesiumIONToken};var metadata=yield CesiumIonLoader.preload(url,loadersGLOptions);loadersGLOptions['fetch']={headers:metadata.headers};}if(props.loadingManager){props.loadingManager.itemStart(url);}var tilesetJson=yield load(url,Tiles3DLoader,Object.assign({},loadersGLOptions));var renderMap={};var boxMap={};var unloadQueue=[];var root=new Group();var tileBoxes=new Group();tileBoxes.matrixAutoUpdate=false;//add
  78973. if(!options.debug){tileBoxes.visible=false;}else {options.parent.add(tileBoxes);//add
  78974. }var pointcloudUniforms={pointSize:{type:'f',value:options.pointSize},gradient:{type:'t',value:gradientTexture},grayscale:{type:'t',value:grayscaleTexture},rootCenter:{type:'vec3',value:new Vector3()},rootNormal:{type:'vec3',value:new Vector3()},coloring:{type:'i',value:options.pointCloudColoring},hideGround:{type:'b',value:true},elevationRange:{type:'vec2',value:new Vector2(0,400)},maxIntensity:{type:'f',value:1.0},intensityContrast:{type:'f',value:1.0},alpha:{type:'f',value:1.0}};var pointcloudMaterial=new ShaderMaterial({uniforms:pointcloudUniforms,vertexShader:PointCloudVS,fragmentShader:PointCloudFS,transparent:options.transparent,vertexColors:true});var cameraReference=null;var rendererReference=null;var gltfLoader=props.gltfLoader||new GLTFLoader();//xzw改
  78975. var ktx2Loader=undefined;var dracoLoader=undefined;if(options.basisTranscoderPath){ktx2Loader=new KTX2Loader();ktx2Loader.detectSupport(props.renderer);ktx2Loader.setTranscoderPath(options.basisTranscoderPath+'/');ktx2Loader.setWorkerLimit(1);gltfLoader.setKTX2Loader(ktx2Loader);}if(options.dracoDecoderPath){dracoLoader=new DRACOLoader();dracoLoader.setDecoderPath(options.dracoDecoderPath+'/');dracoLoader.setWorkerLimit(options.maxConcurrency);gltfLoader.setDRACOLoader(dracoLoader);}var unlitMaterial=new BasicMaterial({transparent:options.transparent});var tileOptions={maximumMemoryUsage:options.maximumMemoryUsage,maximumScreenSpaceError:options.maximumScreenSpaceError,viewDistanceScale:options.viewDistanceScale,skipLevelOfDetail:options.skipLevelOfDetail,updateTransforms:options.updateTransforms,throttleRequests:options.throttleRequests,maxRequests:options.maxRequests,updateTime:options.updateTime||0,//add
  78976. //maxDepth: options.maxDepth || 50, // !zeg改
  78977. contentLoader:tile=>__awaiter(this,void 0,void 0,function*(){var tileContent=null;switch(tile.type){case TILE_TYPE.POINTCLOUD:{tileContent=createPointNodes(tile,pointcloudMaterial,options,rootTransformInverse);break;}case TILE_TYPE.SCENEGRAPH:case TILE_TYPE.MESH:{tileContent=yield createGLTFNodes(gltfLoader,tile,unlitMaterial,options,rootTransformInverse);break;}}if(tileContent){tileContent.visible=false;renderMap[tile.id]=tileContent;tileContent.name=tile.id;//add
  78978. tileContent.tile=tile;//add
  78979. root.add(renderMap[tile.id]);if(options.debug){var box=loadersBoundingBoxToMesh(tile);tileBoxes.add(box);boxMap[tile.id]=box;}//xzw :
  78980. tileset.dispatchEvent({type:'tileLoaded',tileContent});//每一个tile加载完要更改透明度等
  78981. }}),onTileLoad:tile=>__awaiter(this,void 0,void 0,function*(){if(tileset){if(!orientationDetected&&(tile===null||tile===void 0?void 0:tile.depth)<=MAX_DEPTH_FOR_ORIENTATION){detectOrientation(tile);}tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);}}),onTileUnload:tile=>{unloadQueue.push(tile);},onTileError:(tile,message)=>{console.error('Tile error',tile.id,message);}};var tileset=new Tileset3D(tilesetJson,Object.assign(Object.assign({},tileOptions),{loadOptions:Object.assign(Object.assign({},loadersGLOptions),{maxConcurrency:options.maxConcurrency,worker:options.worker,gltf:{loadImages:false},'3d-tiles':{loadGLTF:false}})}));tileset.boxMap=boxMap;//add
  78982. // transformations
  78983. var threeMat=new Matrix4();var tileTransform=new Matrix4();var rootCenter=new Vector3();var orientationDetected=false;if(tileset.root.boundingVolume){if(tileset.root.header.boundingVolume.region){// TODO: Handle region type bounding volumes
  78984. // https://github.com/visgl/loaders.gl/issues/1994
  78985. console.warn("Cannot apply a model matrix to bounding volumes of type region. Tileset stays in original geo-coordinates.");options.geoTransform=GeoTransform.WGS84Cartesian;}tileTransform.setPosition(tileset.root.boundingVolume.center[0],tileset.root.boundingVolume.center[1],tileset.root.boundingVolume.center[2]);}else {console.warn("Bounding volume not found, no transformations applied");}if(options.debug){var box=loadersBoundingBoxToMesh(tileset.root);tileBoxes.add(box);boxMap[tileset.root.id]=box;}var disposeFlag=false;var loadingEnded=false;pointcloudUniforms.rootCenter.value.copy(rootCenter);pointcloudUniforms.rootNormal.value.copy(new Vector3(0,0,1).normalize());// Extra stats
  78986. tileset.stats.get('Loader concurrency').count=options.maxConcurrency;tileset.stats.get('Maximum SSE').count=options.maximumScreenSpaceError;tileset.stats.get('Maximum mem usage').count=options.maximumMemoryUsage;var timer=0;var lastCameraTransform=null;var lastCameraAspect=null;var lastCameraPosition=new Vector3(Infinity,Infinity,Infinity);var sseDenominator=null;root.updateMatrixWorld(true);var lastRootTransform=new Matrix4().copy(root.matrixWorld);var rootTransformInverse=new Matrix4().copy(lastRootTransform).invert();tileset.lastRootTransform=lastRootTransform;//add
  78987. detectOrientation(tileset.root);updateResetTransform();if(options.debug){boxMap[tileset.root.id].applyMatrix4(threeMat);tileBoxes.matrixWorld.copy(root.matrixWorld);}if(options.geoTransform==GeoTransform.Mercator){var coords=datumsToSpherical(tileset.cartographicCenter[1],tileset.cartographicCenter[0]);rootCenter.set(coords.x,0,-coords.y);root.position.copy(rootCenter);root.rotation.set(-Math.PI/2,0,0);root.updateMatrixWorld(true);}else if(options.geoTransform==GeoTransform.WGS84Cartesian){root.applyMatrix4(tileTransform);root.updateMatrixWorld(true);rootCenter.copy(root.position);}function detectOrientation(tile){if(!tile.boundingVolume.halfAxes){return;}var halfAxes=tile.boundingVolume.halfAxes;var orientationMatrix=new Matrix4().extractRotation(getMatrix4FromHalfAxes(halfAxes)).premultiply(new Matrix4().extractRotation(rootTransformInverse));var rotation=new Euler().setFromRotationMatrix(orientationMatrix);if(!rotation.equals(new Euler())){orientationDetected=true;var pos=new Vector3(tileTransform.elements[12],tileTransform.elements[13],tileTransform.elements[14]);tileTransform.extractRotation(orientationMatrix);tileTransform.setPosition(pos);updateResetTransform();}}function updateResetTransform(){if(options.geoTransform!=GeoTransform.WGS84Cartesian){// Reset the current model matrix and apply our own transformation
  78988. //threeMat.copy(tileTransform).invert();
  78989. //threeMat.premultiply(lastRootTransform); //xzw删 被下面copy这句覆盖了
  78990. var tileTransInvert=new Matrix4().copy(tileTransform).invert();threeMat.copy(lastRootTransform).multiply(tileTransInvert);tileset.modelMatrix=new Matrix4$1(threeMat.toArray());//console.log('update tileset ModelMatrix', tileset.modelMatrix.elements)
  78991. tileset.tileTransInvert=tileTransInvert.toArray();// add for volumebox
  78992. }}// 更新瓦片显隐和瓦片迭代更新
  78993. function tilesetUpdate(tileset,renderMap,renderer,camera){if(disposeFlag||options.pauseTilesetUpdate){// !zeg改 pauseTilesetUpdate
  78994. return;}// Assumes camera fov, near and far are not changing
  78995. if(!sseDenominator||camera.aspect!=lastCameraAspect){var loadersFrustum=new PerspectiveFrustum({fov:camera.fov/180*Math.PI,aspectRatio:camera.aspect,near:camera.near,far:camera.far});sseDenominator=loadersFrustum.sseDenominator;lastCameraAspect=camera.aspect;if(camera.aspect==0)return;//add
  78996. if(options.debug){console.log('Updated sse denonimator:',sseDenominator);}}var frustum=_getCameraFrustum(camera);var planes=frustum.planes.map(plane=>new Plane$1(plane.normal.toArray(),plane.constant));var cullingVolume=new CullingVolume(planes);var rendererSize=new Vector2();renderer.getSize(rendererSize);var frameState={camera:{position:lastCameraPosition.toArray()},height:rendererSize.y,frameNumber:tileset._frameNumber,sseDenominator:sseDenominator,cullingVolume:cullingVolume,viewport:{id:0}};tileset._cache.reset();tileset._traverser.traverse(tileset.root,frameState,tileset.options);for(var tile of tileset.tiles){if(tile.selected){if(!renderMap[tile.id]){console.error('TILE SELECTED BUT NOT LOADED!!',tile.id);}else {// Make sure it's visible
  78997. if(!renderMap[tile.id].visible){if(viewer.visiVertexCount<maxVertexVisi){renderMap[tile.id].visible=true;viewer.visiVertexCount+=renderMap[tile.id].vertexCount;//xzw add
  78998. options.debug&&(boxMap[tile.id].material.opacity=1,boxMap[tile.id].children[0].sprite.material.opacity=1);}else {//console.log('超出', visiVertexCount)
  78999. }}/* if(!renderMap[tile.id].realVisible()){
  79000. console.error('!realVisible')
  79001. } */}}else {if(renderMap[tile.id]){if(renderMap[tile.id].visible){renderMap[tile.id].visible=false;options.debug&&(boxMap[tile.id].material.opacity=0.1,boxMap[tile.id].children[0].sprite.material.opacity=0.1);viewer.visiVertexCount-=renderMap[tile.id].vertexCount;//xzw add
  79002. }}}}while(unloadQueue.length>0){var _tile=unloadQueue.pop();if(renderMap[_tile.id]&&_tile.contentState==TILE_CONTENT_STATE.UNLOADED){//console.log('removevisi', renderMap[tile.id].visible) 如果是true,visiVertexCount要减
  79003. root.remove(renderMap[_tile.id]);disposeNode(renderMap[_tile.id]);delete renderMap[_tile.id];}if(boxMap[_tile.id]){disposeNode(boxMap[_tile.id]);tileBoxes.remove(boxMap[_tile.id]);delete boxMap[_tile.id];}}var tilesLoaded=tileset.stats.get('Tiles Loaded').count;var tilesLoading=tileset.stats.get('Tiles Loading').count;if(props.onProgress){props.onProgress(tilesLoaded,tilesLoaded+tilesLoading);}if(props.loadingManager&&!loadingEnded){if(tilesLoading==0&&(options.preloadTilesCount==null||tilesLoaded>=options.preloadTilesCount)){loadingEnded=true;props.loadingManager.itemEnd(props.url);}}return frameState;}return {model:root,runtime:{getTileset:()=>{return tileset;},getStats:()=>{return tileset.stats;},showTiles:visible=>{tileBoxes.visible=visible;},setWireframe:wireframe=>{options.wireframe=wireframe;root.traverse(object=>{if(object instanceof Mesh){object.material.wireframe=wireframe;}});},setDebug:debug=>{options.debug=debug;tileBoxes.visible=debug;},setShading:shading=>{options.shading=shading;},getTileBoxes:()=>{return tileBoxes;},setViewDistanceScale:scale=>{tileset.options.viewDistanceScale=scale;tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);},setHideGround:enabled=>{pointcloudUniforms.hideGround.value=enabled;},setPointCloudColoring:selection=>{pointcloudUniforms.coloring.value=selection;},setElevationRange:range=>{pointcloudUniforms.elevationRange.value.set(range[0],range[1]);},setMaxIntensity:intensity=>{pointcloudUniforms.maxIntensity.value=intensity;},setIntensityContrast:contrast=>{pointcloudUniforms.intensityContrast.value=contrast;},setPointAlpha:alpha=>{pointcloudUniforms.alpha.value=alpha;},getLatLongHeightFromPosition:position=>{var cartographicPosition=tileset.ellipsoid.cartesianToCartographic(new Vector3().copy(position).applyMatrix4(new Matrix4().copy(threeMat).invert()).toArray());return {lat:cartographicPosition[1],long:cartographicPosition[0],height:cartographicPosition[2]};},getPositionFromLatLongHeight:coord=>{var cartesianPosition=tileset.ellipsoid.cartographicToCartesian([coord.long,coord.lat,coord.height]);return new Vector3(...cartesianPosition).applyMatrix4(threeMat);},getCameraFrustum:camera=>{var frustum=_getCameraFrustum(camera);var meshes=frustum.planes.map(plane=>new Plane$1(plane.normal.toArray(),plane.constant)).map(loadersPlane=>loadersPlaneToMesh(loadersPlane));var model=new Group();for(var mesh of meshes)model.add(mesh);return model;},update:function update(dt,renderer,camera,ifForce){cameraReference=camera;rendererReference=renderer;timer+=dt;if(!ifForce)ifForce=tileset.nextForceUpdate;tileset.nextForceUpdate=false;if(tileset.needRenderNext){//必须在下一帧渲染刷新否则无法显示
  79004. viewer.dispatchEvent('content_changed');}tileset.needRenderNext=ifForce;if(tileset&&(timer>=UPDATE_INTERVAL||ifForce)){if(!lastRootTransform.equals(root.matrixWorld)){timer=0;lastRootTransform.copy(root.matrixWorld);updateResetTransform();var _rootCenter=new Vector3().setFromMatrixPosition(lastRootTransform);pointcloudUniforms.rootCenter.value.copy(_rootCenter);pointcloudUniforms.rootNormal.value.copy(new Vector3(0,0,1).applyMatrix4(lastRootTransform).normalize());rootTransformInverse.copy(lastRootTransform).invert();if(options.debug){/* console.log('move', tileset.root.id, boxMap[tileset.root.id].matrix.elements, boxMap[tileset.root.id].matrixWorld.elements)
  79005. boxMap[tileset.root.id].matrix.copy(root.matrixWorld);
  79006. boxMap[tileset.root.id].matrixWorld.copy(root.matrixWorld); */ //boxMap[tileset.root.id].applyMatrix4(threeMat);
  79007. tileBoxes.matrix.copy(root.matrixWorld);//boxMap[tileset.root.id].matrixWorld.copy(threeMat);
  79008. //boxMap[tileset.root.id].applyMatrix4(lastRootTransform);//boxMap[tileset.root.id].applyMatrix4(lastRootTransform);
  79009. //boxMap[tileset.root.id].updateWorldMatrix()
  79010. }}if(this.lastCameraTransform==null){this.lastCameraTransform=new Matrix4().copy(camera.matrixWorld);}else {var cameraChanged=!camera.matrixWorld.equals(this.lastCameraTransform)||!(camera.aspect==lastCameraAspect);if(cameraChanged||ifForce){timer=0;tileset._frameNumber++;camera.getWorldPosition(lastCameraPosition);this.lastCameraTransform.copy(camera.matrixWorld);tilesetUpdate(tileset,renderMap,renderer,camera);}}}/* else{
  79011. console.log('11')
  79012. } */},dispose:function dispose(){disposeFlag=true;tileset._destroy();while(root.children.length>0){var obj=root.children[0];disposeNode(obj);root.remove(obj);}while(tileBoxes.children.length>0){var _obj=tileBoxes.children[0];tileBoxes.remove(_obj);_obj.geometry.dispose();_obj.material.dispose();}if(ktx2Loader){ktx2Loader.dispose();}if(dracoLoader){dracoLoader.dispose();}},limit2lowestDepth:isLowest=>{//zeg add 设置是否限制为最低精度tile深度
  79013. maxDepth=isLowest?1:100;//影响到shouldRefine, 检查方法:可以看到当maxDepth降低了之后viewer.objs.children[0].runtime.getTileset().tiles.filter(e=> e.tileContent.visible)变少
  79014. if(cameraReference){tileset._frameNumber++;tilesetUpdate(tileset,renderMap,rendererReference,cameraReference);}}}};});}}function createGLTFNodes(gltfLoader,tile,unlitMaterial,options,rootTransformInverse){return __awaiter(this,void 0,void 0,function*(){return new Promise((resolve,reject)=>{var _a;var rotateX=new Matrix4().makeRotationAxis(new Vector3(1,0,0),Math.PI/2);var shouldRotate=((_a=tile.tileset.asset)===null||_a===void 0?void 0:_a.gltfUpAxis)!=="Z";// The computed trasnform already contains the root's transform, so we have to invert it
  79015. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tileMatrix)//.premultiply(rootTransformInverse); //xzw 删。原先的会造成移动后tiles错乱
  79016. //const contentTransform = new Matrix4$1().fromArray(tile.computedTransform).premultiply(tile.tileset.modelMatrix).premultiply(rootTransformInverse)
  79017. // 这句同tile.computedTransform左乘tileTransform。 因为tileTransform拿不到所以使用modelMatrix。modelMatrix为tileTransform左乘rootTransform, 所以再左乘rootTransformInverse
  79018. //改动:contentTransform中的computedTransform 去掉左乘 root.modelMatrixWorld , 因为移动过后这个computedTransform没更新
  79019. gltfLoader.parse(tile.content.type=='glTF'?tile.content.gltf.gltfArrayBuffer:tile.content.gltfArrayBuffer,//tile.content.gltfArrayBuffer,
  79020. tile.contentUrl?tile.contentUrl.substr(0,tile.contentUrl.lastIndexOf('/')+1):'',gltf=>{var tileContent=gltf.scenes[0];tileContent.vertexCount=0;//xzw add
  79021. tile.tileContent=tileContent;//xzw add
  79022. var needUpdate;if(tile.rtcCenterState!=!!tile.content.rtcCenter){// 等mesh加载好才知道rtcCenter,每个mesh坐标都不一样
  79023. needUpdate=true;//console.error('rtcCenter有变化?!')
  79024. }tile.rtcCenterState=rtcCenterGlobal=!!tile.content.rtcCenter;var contentTransform=tile.getContentTransform(needUpdate);if(tile.content.rtcCenter){//大部分模型无 rtcCenter
  79025. //console.error('rtcCenter有?!') //似乎bounding中包含这个信息了 所以getContentTransform不含这个
  79026. var tranM=new Matrix4();tranM.makeTranslation(tile.content.rtcCenter[0],tile.content.rtcCenter[1],tile.content.rtcCenter[2]);contentTransform.premultiply(tranM);}if(needUpdate){tile._updateBoundingVolume(tile.header);//add 重新更新
  79027. }if(shouldRotate){//大部分模型 无需 Rotate
  79028. contentTransform.multiply(rotateX);// convert from GLTF Y-up to Z-up
  79029. }tileContent.applyMatrix4(contentTransform);//'https://testgis.4dage.com/LVBADUI_qp/tileset.json', //村庄 这个案例是 要rotateX 且有rtcCenter的。boundingVolume已经是转换这两者后的值所以getContentTransform不加这个
  79030. //tile总共要左乘的矩阵 rotateX -> tileTransInvert * computedTransform -> 对geometry的tranM修改 -> 整个模型的matrixWorld
  79031. tileContent.traverse(object=>{if(object.type=="Mesh"){var mesh=object;//mesh.tileId = tile.id//add
  79032. var originalMaterial=mesh.material;var originalMap=originalMaterial.map;if(options.material){mesh.material=options.material.clone();originalMaterial.dispose();}else if(options.shading==Shading.FlatTexture){mesh.material=unlitMaterial.clone();originalMaterial.dispose();}if(options.shading!=Shading.ShadedNoTexture){if(mesh.material.type=="ShaderMaterial"&&!(mesh.material instanceof BasicMaterial)){//改
  79033. mesh.material.uniforms.map={value:originalMap};}else {mesh.material.map=originalMap;}}else {if(originalMap){originalMap.dispose();}mesh.material.map=null;}if(options.shaderCallback){mesh.onBeforeRender=options.shaderCallback;}mesh.material.wireframe=options.wireframe;if(options.computeNormals){mesh.geometry.computeVertexNormals();}//xzw add:
  79034. tileContent.vertexCount+=mesh.geometry.attributes.position.count;//------------------add on 2023.1.16----zeg
  79035. //mesh.geometry.applyMatrix4(contentTransform)
  79036. /* if (tile.content.rtcCenter) {
  79037. // 有些b3dm模型会将坐标写在源码的rtcCenter里 如https://testgis.4dage.com/LVBADUI_qp/tileset.json
  79038. mesh.geometry.translate(tile.content.rtcCenter[0], tile.content.rtcCenter[1], tile.content.rtcCenter[2])
  79039. } else {
  79040. mesh.geometry.scale(1, 1, -1) // 调整缩放,对应box也要进行变换(scaleZ对应box[2])
  79041. } */ //---------------------
  79042. }});resolve(tileContent);},e=>{reject(new Error("error parsing gltf in tile ".concat(tile.id,": ").concat(e)));});});});}function createPointNodes(tile,pointcloudMaterial,options,rootTransformInverse){var d={rtc_center:tile.content.rtcCenter,points:tile.content.attributes.positions,intensities:tile.content.attributes.intensity,classifications:tile.content.attributes.classification,rgb:null,rgba:null};var{colors}=tile.content.attributes;if(colors&&colors.size===3){d.rgb=colors.value;}if(colors&&colors.size===4){d.rgba=colors.value;}var geometry=new BufferGeometry();geometry.setAttribute('position',new Float32BufferAttribute(d.points,3));var contentTransform=new Matrix4().fromArray(tile.computedTransform).premultiply(rootTransformInverse);if(d.rgba){geometry.setAttribute('color',new Float32BufferAttribute(d.rgba,4));}else if(d.rgb){geometry.setAttribute('color',new Uint8BufferAttribute(d.rgb,3,true));}if(d.intensities){geometry.setAttribute('intensity',// Handles both 16bit or 8bit intensity values
  79043. new BufferAttribute(d.intensities,1,true));}if(d.classifications){geometry.setAttribute('classification',new Uint8BufferAttribute(d.classifications,1,false));}var tileContent=new Points(geometry,options.material||pointcloudMaterial);if(d.rtc_center){var c=d.rtc_center;contentTransform.multiply(new Matrix4().makeTranslation(c[0],c[1],c[2]));}tileContent.applyMatrix4(contentTransform);return tileContent;}function disposeMaterial(material){var _a,_b,_c,_d;if((_a=material===null||material===void 0?void 0:material.uniforms)===null||_a===void 0?void 0:_a.map){(_c=(_b=material===null||material===void 0?void 0:material.uniforms)===null||_b===void 0?void 0:_b.map.value)===null||_c===void 0?void 0:_c.dispose();}else if(material.map){(_d=material.map)===null||_d===void 0?void 0:_d.dispose();}material.dispose();}function disposeNode(node){node.traverse(object=>{if(object.isMesh){object.geometry.dispose();if(object.material.isMaterial){disposeMaterial(object.material);}else {// an array of materials
  79044. for(var material of object.material){disposeMaterial(material);}}}});for(var _i55=node.children.length-1;_i55>=0;_i55--){var obj=node.children[_i55];node.remove(obj);}}/*
  79045. 关键搜寻:
  79046. Loader3DTiles : const tileset = new Tileset3D
  79047. tileset.dispatchEvent({type:'tileLoaded',tileContent})
  79048. createGLTFNodes(gltfLoader 创建tile
  79049. executeTraversal(root, frameState) 遍历root
  79050. lastRootTransform rootTransformInverse
  79051. tileset._loadTiles 依次加载tiles
  79052. _getPriority 加载优先级 加了一句
  79053. 笔记:
  79054. 主要类:
  79055. class tileset3D 最外层整体。 获取方法: viewer.objs.children[index].runtime.getTileset()。 .tiles包含所有tiles
  79056. class tileHeader 也就是tileset里面的一个个tile 。 其上有.tileset
  79057. tileset里算的tileTransform之后是不会改变的, tile.transform也是,是json里的。
  79058. tileset.modelMatrix (通常这个值很大) 会随着位移改变
  79059. tile.computedTransform 被我修改了,之前左乘了tileset.modelMatrix,现只包含了transform信息 _updateTransform(parentTransfor 其中有_updateBoundingVolume,这个影响可见性, 在computeVisibilityWithPlaneMask中计算
  79060. tileset._cache.trim(), 然后再update //可以将所有不可见的tiles dispose
  79061. 相机靠近容易缺块的bug暂时修改如下: _visible是由computeVisibilityWithPlaneMask计算得
  79062. get isVisibleAndInRequestVolume() {
  79063. return this._inRequestVolume; //去掉了_visible ||
  79064. }
  79065. 显示所有tile似乎也不会卡顿. 但好像影响了加载顺序从而变慢了。visiVertexCount过量。 怀疑应该还是文件的bound有问题。
  79066. 原本会消失的地方虽然不会消失了但一直是模糊的
  79067. =========
  79068. 访问所有tile:
  79069. viewer.objs.children[0].runtime.getTileset().tiles
  79070. 它的mesh: tile.tileContent
  79071. 或者直接得到所有mesh: viewer.objs.children[0].children
  79072. tile.depth最低为1 , root是0
  79073. */
  79074. /**
  79075. * Description: A THREE loader for PLY ASCII files (known as the Polygon
  79076. * File Format or the Stanford Triangle Format).
  79077. *
  79078. * Limitations: ASCII decoding assumes file is UTF-8.
  79079. *
  79080. * Usage:
  79081. * var loader = new PLYLoader();
  79082. * loader.load('./models/ply/ascii/dolphins.ply', function (geometry) {
  79083. *
  79084. * scene.add( new THREE.Mesh( geometry ) );
  79085. *
  79086. * } );
  79087. *
  79088. * If the PLY file uses non standard property names, they can be mapped while
  79089. * loading. For example, the following maps the properties
  79090. * “diffuse_(red|green|blue)” in the file to standard color names.
  79091. *
  79092. * loader.setPropertyNameMapping( {
  79093. * diffuse_red: 'red',
  79094. * diffuse_green: 'green',
  79095. * diffuse_blue: 'blue'
  79096. * } );
  79097. *
  79098. */
  79099. var PLYLoader = function PLYLoader(manager) {
  79100. Loader.call(this, manager);
  79101. this.propertyNameMapping = {};
  79102. };
  79103. PLYLoader.prototype = Object.assign(Object.create(Loader.prototype), {
  79104. constructor: PLYLoader,
  79105. load: function load(url, onLoad, onProgress, onError) {
  79106. var scope = this;
  79107. var loader = new FileLoader(this.manager);
  79108. loader.setPath(this.path);
  79109. loader.setResponseType('arraybuffer');
  79110. loader.setRequestHeader(this.requestHeader);
  79111. loader.setWithCredentials(this.withCredentials);
  79112. loader.load(url, function (text) {
  79113. try {
  79114. onLoad(scope.parse(text));
  79115. } catch (e) {
  79116. if (onError) {
  79117. onError(e);
  79118. } else {
  79119. console.error(e);
  79120. }
  79121. scope.manager.itemError(url);
  79122. }
  79123. }, onProgress, onError);
  79124. },
  79125. setPropertyNameMapping: function setPropertyNameMapping(mapping) {
  79126. this.propertyNameMapping = mapping;
  79127. },
  79128. parse: function parse(data) {
  79129. function parseHeader(data) {
  79130. var patternHeader = /ply([\s\S]*)end_header\r?\n/;
  79131. var headerText = '';
  79132. var headerLength = 0;
  79133. var result = patternHeader.exec(data);
  79134. if (result !== null) {
  79135. headerText = result[1];
  79136. headerLength = new Blob([result[0]]).size;
  79137. }
  79138. var header = {
  79139. comments: [],
  79140. elements: [],
  79141. headerLength: headerLength,
  79142. objInfo: ''
  79143. };
  79144. var lines = headerText.split('\n');
  79145. var currentElement;
  79146. var lineType, lineValues;
  79147. function make_ply_element_property(propertValues, propertyNameMapping) {
  79148. var property = {
  79149. type: propertValues[0]
  79150. };
  79151. if (property.type === 'list') {
  79152. property.name = propertValues[3];
  79153. property.countType = propertValues[1];
  79154. property.itemType = propertValues[2];
  79155. } else {
  79156. property.name = propertValues[1];
  79157. }
  79158. if (property.name in propertyNameMapping) {
  79159. property.name = propertyNameMapping[property.name];
  79160. }
  79161. return property;
  79162. }
  79163. for (var i = 0; i < lines.length; i++) {
  79164. var line = lines[i];
  79165. line = line.trim();
  79166. if (line === '') continue;
  79167. lineValues = line.split(/\s+/);
  79168. lineType = lineValues.shift();
  79169. line = lineValues.join(' ');
  79170. switch (lineType) {
  79171. case 'format':
  79172. header.format = lineValues[0];
  79173. header.version = lineValues[1];
  79174. break;
  79175. case 'comment':
  79176. header.comments.push(line);
  79177. break;
  79178. case 'element':
  79179. if (currentElement !== undefined) {
  79180. header.elements.push(currentElement);
  79181. }
  79182. currentElement = {};
  79183. currentElement.name = lineValues[0];
  79184. currentElement.count = parseInt(lineValues[1]);
  79185. currentElement.properties = [];
  79186. break;
  79187. case 'property':
  79188. currentElement.properties.push(make_ply_element_property(lineValues, scope.propertyNameMapping));
  79189. break;
  79190. case 'obj_info':
  79191. header.objInfo = line;
  79192. break;
  79193. default:
  79194. console.log('unhandled', lineType, lineValues);
  79195. }
  79196. }
  79197. if (currentElement !== undefined) {
  79198. header.elements.push(currentElement);
  79199. }
  79200. return header;
  79201. }
  79202. function parseASCIINumber(n, type) {
  79203. switch (type) {
  79204. case 'char':
  79205. case 'uchar':
  79206. case 'short':
  79207. case 'ushort':
  79208. case 'int':
  79209. case 'uint':
  79210. case 'int8':
  79211. case 'uint8':
  79212. case 'int16':
  79213. case 'uint16':
  79214. case 'int32':
  79215. case 'uint32':
  79216. return parseInt(n);
  79217. case 'float':
  79218. case 'double':
  79219. case 'float32':
  79220. case 'float64':
  79221. return parseFloat(n);
  79222. }
  79223. }
  79224. function parseASCIIElement(properties, line) {
  79225. var values = line.split(/\s+/);
  79226. var element = {};
  79227. for (var i = 0; i < properties.length; i++) {
  79228. if (properties[i].type === 'list') {
  79229. var list = [];
  79230. var n = parseASCIINumber(values.shift(), properties[i].countType);
  79231. for (var j = 0; j < n; j++) {
  79232. list.push(parseASCIINumber(values.shift(), properties[i].itemType));
  79233. }
  79234. element[properties[i].name] = list;
  79235. } else {
  79236. element[properties[i].name] = parseASCIINumber(values.shift(), properties[i].type);
  79237. }
  79238. }
  79239. return element;
  79240. }
  79241. function parseASCII(data, header) {
  79242. // PLY ascii format specification, as per http://en.wikipedia.org/wiki/PLY_(file_format)
  79243. var buffer = {
  79244. indices: [],
  79245. vertices: [],
  79246. normals: [],
  79247. uvs: [],
  79248. faceVertexUvs: [],
  79249. colors: []
  79250. };
  79251. var result;
  79252. var patternBody = /end_header\s([\s\S]*)$/;
  79253. var body = '';
  79254. if ((result = patternBody.exec(data)) !== null) {
  79255. body = result[1];
  79256. }
  79257. var lines = body.split('\n');
  79258. var currentElement = 0;
  79259. var currentElementCount = 0;
  79260. for (var i = 0; i < lines.length; i++) {
  79261. var line = lines[i];
  79262. line = line.trim();
  79263. if (line === '') {
  79264. continue;
  79265. }
  79266. if (currentElementCount >= header.elements[currentElement].count) {
  79267. currentElement++;
  79268. currentElementCount = 0;
  79269. }
  79270. var element = parseASCIIElement(header.elements[currentElement].properties, line);
  79271. handleElement(buffer, header.elements[currentElement].name, element);
  79272. currentElementCount++;
  79273. }
  79274. return postProcess(buffer);
  79275. }
  79276. function postProcess(buffer) {
  79277. var geometry = new BufferGeometry();
  79278. // mandatory buffer data
  79279. if (buffer.indices.length > 0) {
  79280. geometry.setIndex(buffer.indices);
  79281. }
  79282. geometry.setAttribute('position', new Float32BufferAttribute(buffer.vertices, 3));
  79283. // optional buffer data
  79284. if (buffer.normals.length > 0) {
  79285. geometry.setAttribute('normal', new Float32BufferAttribute(buffer.normals, 3));
  79286. }
  79287. if (buffer.uvs.length > 0) {
  79288. geometry.setAttribute('uv', new Float32BufferAttribute(buffer.uvs, 2));
  79289. }
  79290. if (buffer.colors.length > 0) {
  79291. geometry.setAttribute('color', new Float32BufferAttribute(buffer.colors, 3));
  79292. }
  79293. if (buffer.faceVertexUvs.length > 0) {
  79294. geometry = geometry.toNonIndexed();
  79295. geometry.setAttribute('uv', new Float32BufferAttribute(buffer.faceVertexUvs, 2));
  79296. }
  79297. geometry.computeBoundingSphere();
  79298. return geometry;
  79299. }
  79300. function handleElement(buffer, elementName, element) {
  79301. if (elementName === 'vertex') {
  79302. buffer.vertices.push(element.x, element.y, element.z);
  79303. if ('nx' in element && 'ny' in element && 'nz' in element) {
  79304. buffer.normals.push(element.nx, element.ny, element.nz);
  79305. }
  79306. if ('s' in element && 't' in element) {
  79307. buffer.uvs.push(element.s, element.t);
  79308. }
  79309. if ('red' in element && 'green' in element && 'blue' in element) {
  79310. buffer.colors.push(element.red / 255.0, element.green / 255.0, element.blue / 255.0);
  79311. }
  79312. } else if (elementName === 'face') {
  79313. var vertex_indices = element.vertex_indices || element.vertex_index; // issue #9338
  79314. var texcoord = element.texcoord;
  79315. if (vertex_indices.length === 3) {
  79316. buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[2]);
  79317. if (texcoord && texcoord.length === 6) {
  79318. buffer.faceVertexUvs.push(texcoord[0], texcoord[1]);
  79319. buffer.faceVertexUvs.push(texcoord[2], texcoord[3]);
  79320. buffer.faceVertexUvs.push(texcoord[4], texcoord[5]);
  79321. }
  79322. } else if (vertex_indices.length === 4) {
  79323. buffer.indices.push(vertex_indices[0], vertex_indices[1], vertex_indices[3]);
  79324. buffer.indices.push(vertex_indices[1], vertex_indices[2], vertex_indices[3]);
  79325. }
  79326. }
  79327. }
  79328. function binaryRead(dataview, at, type, little_endian) {
  79329. switch (type) {
  79330. // corespondences for non-specific length types here match rply:
  79331. case 'int8':
  79332. case 'char':
  79333. return [dataview.getInt8(at), 1];
  79334. case 'uint8':
  79335. case 'uchar':
  79336. return [dataview.getUint8(at), 1];
  79337. case 'int16':
  79338. case 'short':
  79339. return [dataview.getInt16(at, little_endian), 2];
  79340. case 'uint16':
  79341. case 'ushort':
  79342. return [dataview.getUint16(at, little_endian), 2];
  79343. case 'int32':
  79344. case 'int':
  79345. return [dataview.getInt32(at, little_endian), 4];
  79346. case 'uint32':
  79347. case 'uint':
  79348. return [dataview.getUint32(at, little_endian), 4];
  79349. case 'float32':
  79350. case 'float':
  79351. return [dataview.getFloat32(at, little_endian), 4];
  79352. case 'float64':
  79353. case 'double':
  79354. return [dataview.getFloat64(at, little_endian), 8];
  79355. }
  79356. }
  79357. function binaryReadElement(dataview, at, properties, little_endian) {
  79358. var element = {};
  79359. var result,
  79360. read = 0;
  79361. for (var i = 0; i < properties.length; i++) {
  79362. if (properties[i].type === 'list') {
  79363. var list = [];
  79364. result = binaryRead(dataview, at + read, properties[i].countType, little_endian);
  79365. var n = result[0];
  79366. read += result[1];
  79367. for (var j = 0; j < n; j++) {
  79368. result = binaryRead(dataview, at + read, properties[i].itemType, little_endian);
  79369. list.push(result[0]);
  79370. read += result[1];
  79371. }
  79372. element[properties[i].name] = list;
  79373. } else {
  79374. result = binaryRead(dataview, at + read, properties[i].type, little_endian);
  79375. element[properties[i].name] = result[0];
  79376. read += result[1];
  79377. }
  79378. }
  79379. return [element, read];
  79380. }
  79381. function parseBinary(data, header) {
  79382. var buffer = {
  79383. indices: [],
  79384. vertices: [],
  79385. normals: [],
  79386. uvs: [],
  79387. faceVertexUvs: [],
  79388. colors: []
  79389. };
  79390. var little_endian = header.format === 'binary_little_endian';
  79391. var body = new DataView(data, header.headerLength);
  79392. var result,
  79393. loc = 0;
  79394. for (var currentElement = 0; currentElement < header.elements.length; currentElement++) {
  79395. for (var currentElementCount = 0; currentElementCount < header.elements[currentElement].count; currentElementCount++) {
  79396. result = binaryReadElement(body, loc, header.elements[currentElement].properties, little_endian);
  79397. loc += result[1];
  79398. var element = result[0];
  79399. handleElement(buffer, header.elements[currentElement].name, element);
  79400. }
  79401. }
  79402. return postProcess(buffer);
  79403. }
  79404. //
  79405. var geometry;
  79406. var scope = this;
  79407. if (data instanceof ArrayBuffer) {
  79408. var text = LoaderUtils.decodeText(new Uint8Array(data));
  79409. var header = parseHeader(text);
  79410. geometry = header.format === 'ascii' ? parseASCII(text, header) : parseBinary(data, header);
  79411. } else {
  79412. geometry = parseASCII(data, parseHeader(data));
  79413. }
  79414. return geometry;
  79415. }
  79416. });
  79417. /**
  79418. *
  79419. * Supersample Anti-Aliasing Render Pass
  79420. *
  79421. * @author bhouston / http://clara.io/
  79422. *
  79423. * This manual approach to SSAA re-renders the scene ones for each sample with camera jitter and accumulates the results.
  79424. *
  79425. * References: https://en.wikipedia.org/wiki/Supersampling
  79426. *
  79427. */
  79428. //较为原始的一种抗锯齿 (超级采样抗锯齿)
  79429. var SSAARenderPass = function SSAARenderPass(clearColor, clearAlpha) {
  79430. Pass.call(this);
  79431. //this.scene //= scene;
  79432. //this.camera = camera;
  79433. this.sampleLevel = 4; // specified as n, where the number of samples is 2^n, so sampleLevel = 4, is 2^4 samples, 16.
  79434. this.unbiased = true;
  79435. // as we need to clear the buffer in this pass, clearColor must be set to something, defaults to black.
  79436. this.clearColor = clearColor !== undefined ? clearColor : 0x000000;
  79437. this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0;
  79438. this.renderUniforms = {
  79439. bgTex: {
  79440. value: null
  79441. },
  79442. outlineTex: {
  79443. value: null
  79444. },
  79445. opacity: {
  79446. value: 1
  79447. }
  79448. };
  79449. this.renderMat = new ShaderMaterial({
  79450. uniforms: this.renderUniforms,
  79451. vertexShader: CopyShader.vertexShader,
  79452. /* fragmentShader: CopyShader.fragmentShader, */
  79453. fragmentShader: " \n uniform sampler2D bgTex; \n uniform sampler2D outlineTex; \n uniform float opacity;\n varying vec2 vUv;\n void main() {\n vec4 color1 = texture2D( bgTex, vUv );\n vec4 color2 = texture2D( outlineTex, vUv ); \n gl_FragColor = opacity * mix(color1, color2, color2.a) ;\n \n \n } \n ",
  79454. premultipliedAlpha: true,
  79455. blending: AdditiveBlending,
  79456. depthTest: false,
  79457. depthWrite: false,
  79458. transparent: true
  79459. });
  79460. this.renderMat2 = new ShaderMaterial({
  79461. uniforms: UniformsUtils.clone(CopyShader.uniforms),
  79462. vertexShader: CopyShader.vertexShader,
  79463. fragmentShader: "uniform float opacity; \n uniform sampler2D tDiffuse; \n varying vec2 vUv;\n\n void main() {\n \n vec4 texel = texture2D( tDiffuse, vUv ); \n \n if(texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0){\n discard;\n }else{\n gl_FragColor = opacity * texel;\n }\n } \n ",
  79464. depthTest: false,
  79465. depthWrite: false,
  79466. transparent: true
  79467. });
  79468. ////////////////////
  79469. /* this.renderMat.blendSrc = THREE.OneFactor //即将写入缓冲区的颜色。
  79470. this.renderMat.blendDst = THREE.OneFactor //缓冲区已经存在的颜色
  79471. this.renderMat.blendEquation = THREE.AddEquation;
  79472. this.renderMat.blendEquationAlpha = THREE.AddEquation;
  79473. this.renderMat.blendDstAlpha = THREE.SrcAlphaFactor
  79474. this.renderMat.blendSrcAlpha = THREE.SrcAlphaFactor */
  79475. this.camera2 = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
  79476. this.scene2 = new Scene();
  79477. this.quad2 = new Mesh(new PlaneBufferGeometry(2, 2), this.renderMat /* this.copyMaterial */);
  79478. this.quad2.frustumCulled = false; // Avoid getting clipped
  79479. this.scene2.add(this.quad2);
  79480. this.copyPass = new ShaderPass(CopyShader);
  79481. this.copyPass.renderToScreen = true;
  79482. };
  79483. SSAARenderPass.prototype = Object.assign(Object.create(Pass.prototype), {
  79484. constructor: SSAARenderPass,
  79485. dispose: function dispose() {
  79486. if (this.sampleRenderTarget) {
  79487. this.sampleRenderTarget.dispose();
  79488. this.sampleRenderTarget = null;
  79489. }
  79490. },
  79491. setSize: function setSize(width, height) {
  79492. if (this.sampleRenderTarget) this.sampleRenderTarget.setSize(width, height);
  79493. this.childPass && this.childPass.setSize(width, height);
  79494. },
  79495. addPass: function addPass(pass) {
  79496. this.childPass = pass;
  79497. },
  79498. render: function render(scene, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun) {
  79499. if (this.useCopy) {
  79500. scene = this.copyPass.scene;
  79501. camera = this.copyPass.camera;
  79502. }
  79503. if (!this.sampleRenderTarget) {
  79504. this.sampleRenderTarget = new WebGLRenderTarget(readBuffer.width, readBuffer.height, {
  79505. minFilter: LinearFilter,
  79506. magFilter: LinearFilter,
  79507. format: RGBAFormat
  79508. });
  79509. this.sampleRenderTarget.texture.name = "SSAARenderPass.sample";
  79510. }
  79511. var jitterOffsets = SSAARenderPass.JitterVectors[Math.max(0, Math.min(this.sampleLevel, 5))];
  79512. var autoClear = renderer.autoClear;
  79513. renderer.autoClear = false;
  79514. var oldClearColor = renderer.getClearColor(new Color()).getHex();
  79515. var oldClearAlpha = renderer.getClearAlpha();
  79516. renderer.setClearColor(this.clearColor, this.clearAlpha);
  79517. var baseSampleWeight = 1.0 / jitterOffsets.length;
  79518. var roundingRange = 1 / 32;
  79519. //this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
  79520. var oldTarget = renderer.getRenderTarget();
  79521. if (oldTarget) {
  79522. if (oldTarget.scissorTest) {
  79523. var width = oldTarget.scissor.w,
  79524. height = oldTarget.scissor.z;
  79525. } else {
  79526. var width = oldTarget.width,
  79527. height = oldTarget.height;
  79528. }
  79529. } else {
  79530. var width = readBuffer.width,
  79531. height = readBuffer.height;
  79532. }
  79533. // render the scene multiple times, each slightly jitter offset from the last and accumulate the results.
  79534. var opa = 0;
  79535. for (var i = 0; i < jitterOffsets.length; i++) {
  79536. var jitterOffset = jitterOffsets[i];
  79537. if (camera.setViewOffset) {
  79538. camera.setViewOffset(width, height, jitterOffset[0] * 0.0625, jitterOffset[1] * 0.0625,
  79539. // 0.0625 = 1 / 16
  79540. width, height);
  79541. }
  79542. var sampleWeight = baseSampleWeight;
  79543. if (this.unbiased) {
  79544. //更柔和
  79545. var uniformCenteredDistribution = -0.5 + (i + 0.5) / jitterOffsets.length;
  79546. sampleWeight += roundingRange * uniformCenteredDistribution;
  79547. }
  79548. renderer.setRenderTarget(this.sampleRenderTarget);
  79549. renderer.clear();
  79550. if (this.useCopy) {
  79551. this.copyPass.render(scene, camera, null, renderer, writeBuffer, readBuffer);
  79552. } else {
  79553. if (renderFun) {
  79554. renderFun({
  79555. target: this.sampleRenderTarget
  79556. });
  79557. } else {
  79558. renderer.render(scene, camera);
  79559. }
  79560. }
  79561. renderer.setRenderTarget(oldTarget);
  79562. //---------------------
  79563. //获取outline tex
  79564. var hasOutline = this.childPass && this.childPass.render(scene, camera, renderer, writeBuffer, readBuffer, null, renderFun);
  79565. //合成到该材质
  79566. this.renderUniforms["bgTex"].value = this.sampleRenderTarget.texture;
  79567. this.renderUniforms["outlineTex"].value = hasOutline ? readBuffer.texture : null;
  79568. this.renderUniforms["opacity"].value = sampleWeight;
  79569. /* console.log('sampleWeight', sampleWeight)
  79570. opa += sampleWeight */
  79571. if (!this.renderToScreen) {
  79572. renderer.setRenderTarget(writeBuffer);
  79573. }
  79574. if (i === 0) {
  79575. renderer.setClearColor(0x000000, 0); //叠加前颜色必须0
  79576. renderer.clear();
  79577. }
  79578. renderer.render(this.scene2, this.camera2); // , this.renderToScreen ? null : writeBuffer, ( i === 0 )
  79579. if (!this.renderToScreen) {
  79580. renderer.setRenderTarget(oldTarget);
  79581. }
  79582. //if(i==2)break;
  79583. }
  79584. //console.log('sum:',opa)
  79585. if (camera.clearViewOffset) camera.clearViewOffset();
  79586. //renderer.setRenderTarget(readBuffer)
  79587. //renderer.setClearColor( 0x000000, 0 );
  79588. //renderer.clear()
  79589. /* this.quad2.material = this.renderMat2
  79590. this.renderMat2.uniforms.tDiffuse.value = writeBuffer.texture;
  79591. renderer.render( this.scene2, this.camera2);
  79592. this.quad2.material = this.renderMat */
  79593. //renderer.setRenderTarget(oldTarget)
  79594. renderer.autoClear = autoClear;
  79595. renderer.setClearColor(oldClearColor, oldClearAlpha);
  79596. /* 试了好几次,测量线的透明度还是还原不了。 clearAlpha十分影响结果。
  79597. 因为绘制测量线需要背景透明。 或许可以先全部绘制完后,再 copyshader中 抗锯齿?
  79598. 另外会有黑边。
  79599. */
  79600. }
  79601. });
  79602. // These jitter vectors are specified in integers because it is easier.
  79603. // I am assuming a [-8,8) integer grid, but it needs to be mapped onto [-0.5,0.5)
  79604. // before being used, thus these integers need to be scaled by 1/16.
  79605. //
  79606. // Sample patterns reference: https://msdn.microsoft.com/en-us/library/windows/desktop/ff476218%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396
  79607. SSAARenderPass.JitterVectors = [[[0, 0]], [[4, 4], [-4, -4]], [[-2, -6], [6, -2], [-6, 2], [2, 6]], [[1, -3], [-1, 3], [5, 1], [-3, -5], [-5, 5], [-7, -1], [3, 7], [7, -7]], [[1, 1], [-1, -3], [-3, 2], [4, -1], [-5, -2], [2, 5], [5, 3], [3, -5], [-2, 6], [0, -7], [-4, -6], [-6, 4], [-8, 0], [7, -4], [6, 7], [-7, -8]], [[-4, -7], [-7, -5], [-3, -5], [-5, -4], [-1, -4], [-2, -2], [-6, -1], [-4, 0], [-7, 1], [-1, 2], [-6, 3], [-3, 3], [-7, 6], [-3, 6], [-5, 7], [-1, 7], [5, -7], [1, -6], [6, -5], [4, -4], [2, -3], [7, -2], [1, -1], [4, -1], [2, 1], [6, 2], [0, 4], [4, 4], [2, 5], [7, 5], [5, 6], [3, 7]]];
  79608. class MaskPass extends Pass {
  79609. constructor(scene, camera) {
  79610. super();
  79611. this.scene = scene;
  79612. this.camera = camera;
  79613. this.clear = true;
  79614. this.needsSwap = false;
  79615. this.inverse = false;
  79616. }
  79617. render(renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) {
  79618. var context = renderer.getContext();
  79619. var state = renderer.state;
  79620. // don't update color or depth
  79621. state.buffers.color.setMask(false);
  79622. state.buffers.depth.setMask(false);
  79623. // lock buffers
  79624. state.buffers.color.setLocked(true);
  79625. state.buffers.depth.setLocked(true);
  79626. // set up stencil
  79627. var writeValue, clearValue;
  79628. if (this.inverse) {
  79629. writeValue = 0;
  79630. clearValue = 1;
  79631. } else {
  79632. writeValue = 1;
  79633. clearValue = 0;
  79634. }
  79635. state.buffers.stencil.setTest(true);
  79636. state.buffers.stencil.setOp(context.REPLACE, context.REPLACE, context.REPLACE);
  79637. state.buffers.stencil.setFunc(context.ALWAYS, writeValue, 0xffffffff);
  79638. state.buffers.stencil.setClear(clearValue);
  79639. state.buffers.stencil.setLocked(true);
  79640. // draw into the stencil buffer
  79641. renderer.setRenderTarget(readBuffer);
  79642. if (this.clear) renderer.clear();
  79643. renderer.render(this.scene, this.camera);
  79644. renderer.setRenderTarget(writeBuffer);
  79645. if (this.clear) renderer.clear();
  79646. renderer.render(this.scene, this.camera);
  79647. // unlock color and depth buffer for subsequent rendering
  79648. state.buffers.color.setLocked(false);
  79649. state.buffers.depth.setLocked(false);
  79650. // only render where stencil is set to 1
  79651. state.buffers.stencil.setLocked(false);
  79652. state.buffers.stencil.setFunc(context.EQUAL, 1, 0xffffffff); // draw if == 1
  79653. state.buffers.stencil.setOp(context.KEEP, context.KEEP, context.KEEP);
  79654. state.buffers.stencil.setLocked(true);
  79655. }
  79656. }
  79657. class ClearMaskPass extends Pass {
  79658. constructor() {
  79659. super();
  79660. this.needsSwap = false;
  79661. }
  79662. render(renderer /*, writeBuffer, readBuffer, deltaTime, maskActive */) {
  79663. renderer.state.buffers.stencil.setLocked(false);
  79664. renderer.state.buffers.stencil.setTest(false);
  79665. }
  79666. }
  79667. /**
  79668. * @author alteredq / http://alteredqualia.com/
  79669. */
  79670. var EffectComposer = function EffectComposer(renderer, renderTarget) {
  79671. this.renderer = renderer;
  79672. if (renderTarget === undefined) {
  79673. var parameters = {
  79674. minFilter: LinearFilter,
  79675. magFilter: LinearFilter,
  79676. format: RGBAFormat,
  79677. stencilBuffer: false
  79678. };
  79679. var size = renderer.getDrawingBufferSize(new Vector2());
  79680. renderTarget = new WebGLRenderTarget(size.width, size.height, parameters);
  79681. renderTarget.texture.name = 'EffectComposer.rt1';
  79682. }
  79683. this.renderTarget1 = renderTarget;
  79684. this.renderTarget2 = renderTarget.clone();
  79685. this.renderTarget2.texture.name = 'EffectComposer.rt2';
  79686. this.writeBuffer = this.renderTarget1;
  79687. this.readBuffer = this.renderTarget2;
  79688. this.passes = [];
  79689. // dependencies
  79690. /* if ( THREE.CopyShader === undefined ) {
  79691. console.error( 'THREE.EffectComposer relies on THREE.CopyShader' );
  79692. }
  79693. if ( THREE.ShaderPass === undefined ) {
  79694. console.error( 'THREE.EffectComposer relies on THREE.ShaderPass' );
  79695. } */
  79696. this.copyPass = new ShaderPass(CopyShader);
  79697. viewer.addEventListener('resize', e => {
  79698. //readTarget的话是渲染一整张的,暂时无法一个个viewport渲染所以不用
  79699. this.readTarget || this.setSize(e.viewport.resolution2.x, e.viewport.resolution2.y); //暂时假设composer渲染的viewer的viewports.length == 1
  79700. });
  79701. };
  79702. Object.assign(EffectComposer.prototype, {
  79703. swapBuffers: function swapBuffers() {
  79704. var tmp = this.readBuffer;
  79705. this.readBuffer = this.writeBuffer;
  79706. this.writeBuffer = tmp;
  79707. },
  79708. addPass: function addPass(pass) {
  79709. this.passes.push(pass);
  79710. var size = this.renderer.getDrawingBufferSize(new Vector2());
  79711. pass.setSize(size.width, size.height);
  79712. },
  79713. removePass: function removePass(pass) {
  79714. //add
  79715. var index = this.passes.indexOf(pass);
  79716. index > -1 && this.passes.splice(index, 1);
  79717. },
  79718. insertPass: function insertPass(pass, index) {
  79719. this.passes.splice(index, 0, pass);
  79720. },
  79721. render: function render(scene, camera, viewports, renderFun) {
  79722. var maskActive = false;
  79723. var passes = this.passes.filter(e => e.enabled);
  79724. var pass,
  79725. i,
  79726. il = passes.length;
  79727. var oldTarget = this.renderer.getRenderTarget();
  79728. if (this.readTarget && oldTarget) {
  79729. //add 使用当前renderTarget中的像素
  79730. this.setSize(oldTarget.width, oldTarget.height); //所有viewports一起渲染,整个画面 因暂时没办法一个个copy
  79731. oldTarget.viewport.set(0, 0, oldTarget.width, oldTarget.height);
  79732. oldTarget.scissorTest = false;
  79733. this.copyPass.render(scene, camera, viewports, this.renderer, this.readBuffer, oldTarget);
  79734. }
  79735. for (i = 0; i < il; i++) {
  79736. pass = passes[i];
  79737. //if(i == il-1)pass.renderToScreen = true//
  79738. pass.render(scene, camera, viewports, this.renderer, this.writeBuffer, this.readBuffer, maskActive, renderFun);
  79739. if (pass.needsSwap) {
  79740. if (maskActive) {
  79741. var context = this.renderer.context;
  79742. context.stencilFunc(context.NOTEQUAL, 1, 0xffffffff);
  79743. this.copyPass.render(null, null, viewports, this.renderer, this.writeBuffer, this.readBuffer); // delta
  79744. context.stencilFunc(context.EQUAL, 1, 0xffffffff);
  79745. }
  79746. this.swapBuffers();
  79747. }
  79748. if (MaskPass !== undefined) {
  79749. if (pass instanceof MaskPass) {
  79750. maskActive = true;
  79751. } else if (pass instanceof ClearMaskPass) {
  79752. maskActive = false;
  79753. }
  79754. }
  79755. }
  79756. this.renderer.setRenderTarget(oldTarget);
  79757. //add
  79758. if (!pass.renderToScreen) {
  79759. //最后一个如果没有绘制到屏幕or target上
  79760. this.copyPass.renderToScreen = true;
  79761. this.copyPass.render(null, null, viewports, this.renderer, this.writeBuffer, this.readBuffer);
  79762. }
  79763. },
  79764. reset: function reset(renderTarget) {
  79765. if (renderTarget === undefined) {
  79766. var size = this.renderer.getDrawingBufferSize(new Vector2());
  79767. renderTarget = this.renderTarget1.clone();
  79768. renderTarget.setSize(size.width, size.height);
  79769. }
  79770. this.renderTarget1.dispose();
  79771. this.renderTarget2.dispose();
  79772. this.renderTarget1 = renderTarget;
  79773. this.renderTarget2 = renderTarget.clone();
  79774. this.writeBuffer = this.renderTarget1;
  79775. this.readBuffer = this.renderTarget2;
  79776. },
  79777. setSize: function setSize(width, height, scaleRatio) {
  79778. scaleRatio = scaleRatio || this.scaleRatio || 1;
  79779. //console.log('setSize', width * scaleRatio, height * scaleRatio)
  79780. var maxTexWidth = 4096;
  79781. var w = width * scaleRatio;
  79782. var h = height * scaleRatio;
  79783. if (w > maxTexWidth || h > maxTexWidth) {
  79784. //超出会崩溃
  79785. if (w > h) {
  79786. scaleRatio = maxTexWidth / width;
  79787. } else {
  79788. scaleRatio = maxTexWidth / height;
  79789. }
  79790. }
  79791. w = width * scaleRatio;
  79792. h = height * scaleRatio;
  79793. this.renderTarget1.setSize(w, h);
  79794. this.renderTarget2.setSize(w, h);
  79795. for (var i = 0; i < this.passes.length; i++) {
  79796. this.passes[i].setSize(w, h);
  79797. }
  79798. }
  79799. });
  79800. /**
  79801. * @author alteredq / http://alteredqualia.com/
  79802. */
  79803. class RenderPass extends Pass {
  79804. constructor(overrideMaterial, clearColor, clearAlpha) {
  79805. super();
  79806. /* this.scene = scene;
  79807. this.camera = camera; */
  79808. this.overrideMaterial = overrideMaterial;
  79809. this.clearColor = clearColor;
  79810. this.clearAlpha = clearAlpha !== undefined ? clearAlpha : 0;
  79811. this.clear = true;
  79812. this.clearDepth = false;
  79813. this.needsSwap = false;
  79814. this._oldClearColor = new Color();
  79815. }
  79816. render(scene, camera, viewports, renderer, writeBuffer, readBuffer /*, deltaTime, maskActive */) {
  79817. var oldAutoClear = renderer.autoClear;
  79818. renderer.autoClear = false;
  79819. var oldClearAlpha, oldOverrideMaterial;
  79820. if (this.overrideMaterial !== undefined) {
  79821. oldOverrideMaterial = this.scene.overrideMaterial;
  79822. scene.overrideMaterial = this.overrideMaterial;
  79823. }
  79824. if (this.clearColor) {
  79825. renderer.getClearColor(this._oldClearColor);
  79826. oldClearAlpha = renderer.getClearAlpha();
  79827. renderer.setClearColor(this.clearColor, this.clearAlpha);
  79828. }
  79829. if (this.clearDepth) {
  79830. renderer.clearDepth();
  79831. }
  79832. var oldTarget = renderer.getRenderTarget();
  79833. if (!this.renderToScreen) renderer.setRenderTarget(readBuffer);
  79834. // TODO: Avoid using autoClear properties, see https://github.com/mrdoob/three.js/pull/15571#issuecomment-465669600
  79835. if (this.clear) renderer.clear(renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil);
  79836. renderer.render(scene, camera);
  79837. if (!this.renderToScreen) renderer.setRenderTarget(oldTarget);
  79838. if (this.clearColor) {
  79839. renderer.setClearColor(this._oldClearColor, oldClearAlpha);
  79840. }
  79841. if (this.overrideMaterial !== undefined) {
  79842. scene.overrideMaterial = oldOverrideMaterial;
  79843. }
  79844. renderer.setRenderTarget(oldTarget);
  79845. renderer.autoClear = oldAutoClear;
  79846. }
  79847. }
  79848. /**
  79849. * NVIDIA FXAA by Timothy Lottes
  79850. * https://developer.download.nvidia.com/assets/gamedev/files/sdk/11/FXAA_WhitePaper.pdf
  79851. * - WebGL port by @supereggbert
  79852. * http://www.glge.org/demos/fxaa/
  79853. * Further improved by Daniel Sturk
  79854. */
  79855. var FXAAShader = {
  79856. uniforms: {
  79857. 'tDiffuse': {
  79858. value: null
  79859. },
  79860. 'resolution': {
  79861. value: new Vector2(1 / 1024, 1 / 512)
  79862. }
  79863. },
  79864. vertexShader: /* glsl */"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",
  79865. fragmentShader: "\n\tprecision highp float;\n\n\tuniform sampler2D tDiffuse;\n\n\tuniform vec2 resolution;\n\n\tvarying vec2 vUv;\n\n\t// FXAA 3.11 implementation by NVIDIA, ported to WebGL by Agost Biro (biro@archilogic.com)\n\n\t//----------------------------------------------------------------------------------\n\t// File: es3-keplerFXAAassetsshaders/FXAA_DefaultES.frag\n\t// SDK Version: v3.00\n\t// Email: gameworks@nvidia.com\n\t// Site: http://developer.nvidia.com/\n\t//\n\t// Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.\n\t//\n\t// Redistribution and use in source and binary forms, with or without\n\t// modification, are permitted provided that the following conditions\n\t// are met:\n\t// * Redistributions of source code must retain the above copyright\n\t// notice, this list of conditions and the following disclaimer.\n\t// * Redistributions in binary form must reproduce the above copyright\n\t// notice, this list of conditions and the following disclaimer in the\n\t// documentation and/or other materials provided with the distribution.\n\t// * Neither the name of NVIDIA CORPORATION nor the names of its\n\t// contributors may be used to endorse or promote products derived\n\t// from this software without specific prior written permission.\n\t//\n\t// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY\n\t// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\t// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\t// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\t// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\t// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\t// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\t// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n\t// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\t// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\t// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\t//\n\t//----------------------------------------------------------------------------------\n\n\t#ifndef FXAA_DISCARD\n\t\t\t//\n\t\t\t// Only valid for PC OpenGL currently.\n\t\t\t// Probably will not work when FXAA_GREEN_AS_LUMA = 1.\n\t\t\t//\n\t\t\t// 1 = Use discard on pixels which don't need AA.\n\t\t\t// For APIs which enable concurrent TEX+ROP from same surface.\n\t\t\t// 0 = Return unchanged color on pixels which don't need AA.\n\t\t\t//\n\t\t\t#define FXAA_DISCARD 0\n\t#endif\n\n\t/*--------------------------------------------------------------------------*/\n //\u7B2C\u4E09\u4E2A\u53C2\u6570\u52A0\u5165\u540E\u53EA\u80FD\u5728\u7247\u5143\u7740\u8272\u5668\u4E2D\u8C03\u7528\uFF0C\u4E14\u53EA\u5BF9\u91C7\u6837\u5668\u4E3Amipmap\u7C7B\u578B\u7EB9\u7406\u65F6\u6709\u6548\u3002\u4E0D\u660E\u767D\u4F5C\u7528\uFF1F\uFF1F\uFF1F \u4F46\u8B66\u544A\u8BF4\u8303\u56F4\u572816\u4E4B\u5185\n\t#define FxaaTexTop(t, p) texture2D(t, p, -15.0); //-100.0); \n\t#define FxaaTexOff(t, p, o, r) texture2D(t, p + (o * r), -15.0); //-100.0)\n\t/*--------------------------------------------------------------------------*/\n\n\t#define NUM_SAMPLES 5\n\n\t// assumes colors have premultipliedAlpha, so that the calculated color contrast is scaled by alpha\n\tfloat contrast( vec4 a, vec4 b ) {\n\t\t\tvec4 diff = abs( a - b );\n\t\t\treturn max( max( max( diff.r, diff.g ), diff.b ), diff.a );\n\t}\n\n\t/*============================================================================\n\n\t\t\t\t\t\t\t\t\tFXAA3 QUALITY - PC\n\n\t============================================================================*/\n\n\t/*--------------------------------------------------------------------------*/\n\tvec4 FxaaPixelShader(\n\t\t\tvec2 posM,\n\t\t\tsampler2D tex,\n\t\t\tvec2 fxaaQualityRcpFrame,\n\t\t\tfloat fxaaQualityEdgeThreshold,\n\t\t\tfloat fxaaQualityinvEdgeThreshold\n\t) {\n\t\t\tvec4 rgbaM = FxaaTexTop(tex, posM);\n\t\t\tvec4 rgbaS = FxaaTexOff(tex, posM, vec2( 0.0, 1.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaE = FxaaTexOff(tex, posM, vec2( 1.0, 0.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaN = FxaaTexOff(tex, posM, vec2( 0.0,-1.0), fxaaQualityRcpFrame.xy);\n\t\t\tvec4 rgbaW = FxaaTexOff(tex, posM, vec2(-1.0, 0.0), fxaaQualityRcpFrame.xy);\n\t\t\t// . S .\n\t\t\t// W M E\n\t\t\t// . N .\n\n\t\t\tbool earlyExit = max( max( max(\n\t\t\t\t\tcontrast( rgbaM, rgbaN ),\n\t\t\t\t\tcontrast( rgbaM, rgbaS ) ),\n\t\t\t\t\tcontrast( rgbaM, rgbaE ) ),\n\t\t\t\t\tcontrast( rgbaM, rgbaW ) )\n\t\t\t\t\t< fxaaQualityEdgeThreshold;\n\t\t\t// . 0 .\n\t\t\t// 0 0 0\n\t\t\t// . 0 .\n\n\t\t\t#if (FXAA_DISCARD == 1)\n\t\t\t\t\tif(earlyExit) FxaaDiscard;\n\t\t\t#else\n\t\t\t\t\tif(earlyExit) return rgbaM;\n\t\t\t#endif\n\n\t\t\tfloat contrastN = contrast( rgbaM, rgbaN );\n\t\t\tfloat contrastS = contrast( rgbaM, rgbaS );\n\t\t\tfloat contrastE = contrast( rgbaM, rgbaE );\n\t\t\tfloat contrastW = contrast( rgbaM, rgbaW );\n\n\t\t\tfloat relativeVContrast = ( contrastN + contrastS ) - ( contrastE + contrastW );\n\t\t\trelativeVContrast *= fxaaQualityinvEdgeThreshold;\n\n\t\t\tbool horzSpan = relativeVContrast > 0.;\n\t\t\t// . 1 .\n\t\t\t// 0 0 0\n\t\t\t// . 1 .\n\n\t\t\t// 45 deg edge detection and corners of objects, aka V/H contrast is too similar\n\t\t\tif( abs( relativeVContrast ) < .3 ) {\n\t\t\t\t\t// locate the edge\n\t\t\t\t\tvec2 dirToEdge;\n\t\t\t\t\tdirToEdge.x = contrastE > contrastW ? 1. : -1.;\n\t\t\t\t\tdirToEdge.y = contrastS > contrastN ? 1. : -1.;\n\t\t\t\t\t// . 2 . . 1 .\n\t\t\t\t\t// 1 0 2 ~= 0 0 1\n\t\t\t\t\t// . 1 . . 0 .\n\n\t\t\t\t\t// tap 2 pixels and see which ones are \"outside\" the edge, to\n\t\t\t\t\t// determine if the edge is vertical or horizontal\n\n\t\t\t\t\tvec4 rgbaAlongH = FxaaTexOff(tex, posM, vec2( dirToEdge.x, -dirToEdge.y ), fxaaQualityRcpFrame.xy);\n\t\t\t\t\tfloat matchAlongH = contrast( rgbaM, rgbaAlongH );\n\t\t\t\t\t// . 1 .\n\t\t\t\t\t// 0 0 1\n\t\t\t\t\t// . 0 H\n\n\t\t\t\t\tvec4 rgbaAlongV = FxaaTexOff(tex, posM, vec2( -dirToEdge.x, dirToEdge.y ), fxaaQualityRcpFrame.xy);\n\t\t\t\t\tfloat matchAlongV = contrast( rgbaM, rgbaAlongV );\n\t\t\t\t\t// V 1 .\n\t\t\t\t\t// 0 0 1\n\t\t\t\t\t// . 0 .\n\n\t\t\t\t\trelativeVContrast = matchAlongV - matchAlongH;\n\t\t\t\t\trelativeVContrast *= fxaaQualityinvEdgeThreshold;\n\n\t\t\t\t\tif( abs( relativeVContrast ) < .3 ) { // 45 deg edge\n\t\t\t\t\t\t\t// 1 1 .\n\t\t\t\t\t\t\t// 0 0 1\n\t\t\t\t\t\t\t// . 0 1\n\n\t\t\t\t\t\t\t// do a simple blur\n\t\t\t\t\t\t\treturn mix(\n\t\t\t\t\t\t\t\t\trgbaM,\n\t\t\t\t\t\t\t\t\t(rgbaN + rgbaS + rgbaE + rgbaW) * .25,\n\t\t\t\t\t\t\t\t\t.4\n\t\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\thorzSpan = relativeVContrast > 0.;\n\t\t\t}\n\n\t\t\tif(!horzSpan) rgbaN = rgbaW;\n\t\t\tif(!horzSpan) rgbaS = rgbaE;\n\t\t\t// . 0 . 1\n\t\t\t// 1 0 1 -> 0\n\t\t\t// . 0 . 1\n\n\t\t\tbool pairN = contrast( rgbaM, rgbaN ) > contrast( rgbaM, rgbaS );\n\t\t\tif(!pairN) rgbaN = rgbaS;\n\n\t\t\tvec2 offNP;\n\t\t\toffNP.x = (!horzSpan) ? 0.0 : fxaaQualityRcpFrame.x;\n\t\t\toffNP.y = ( horzSpan) ? 0.0 : fxaaQualityRcpFrame.y;\n\n\t\t\tbool doneN = false;\n\t\t\tbool doneP = false;\n\n\t\t\tfloat nDist = 0.;\n\t\t\tfloat pDist = 0.;\n\n\t\t\tvec2 posN = posM;\n\t\t\tvec2 posP = posM;\n\n\t\t\tint iterationsUsed = 0;\n\t\t\tint iterationsUsedN = 0;\n\t\t\tint iterationsUsedP = 0;\n\t\t\tfor( int i = 0; i < NUM_SAMPLES; i++ ) {\n\t\t\t\t\titerationsUsed = i;\n\n\t\t\t\t\tfloat increment = float(i + 1);\n\n\t\t\t\t\tif(!doneN) {\n\t\t\t\t\t\t\tnDist += increment;\n\t\t\t\t\t\t\tposN = posM + offNP * nDist;\n\t\t\t\t\t\t\tvec4 rgbaEndN = FxaaTexTop(tex, posN.xy);\n\t\t\t\t\t\t\tdoneN = contrast( rgbaEndN, rgbaM ) > contrast( rgbaEndN, rgbaN );\n\t\t\t\t\t\t\titerationsUsedN = i;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(!doneP) {\n\t\t\t\t\t\t\tpDist += increment;\n\t\t\t\t\t\t\tposP = posM - offNP * pDist;\n\t\t\t\t\t\t\tvec4 rgbaEndP = FxaaTexTop(tex, posP.xy);\n\t\t\t\t\t\t\tdoneP = contrast( rgbaEndP, rgbaM ) > contrast( rgbaEndP, rgbaN );\n\t\t\t\t\t\t\titerationsUsedP = i;\n\t\t\t\t\t}\n\n\t\t\t\t\tif(doneN || doneP) break;\n\t\t\t}\n\n\n\t\t\tif ( !doneP && !doneN ) return rgbaM; // failed to find end of edge\n\n\t\t\tfloat dist = min(\n\t\t\t\t\tdoneN ? float( iterationsUsedN ) / float( NUM_SAMPLES - 1 ) : 1.,\n\t\t\t\t\tdoneP ? float( iterationsUsedP ) / float( NUM_SAMPLES - 1 ) : 1.\n\t\t\t);\n\n\t\t\t// hacky way of reduces blurriness of mostly diagonal edges\n\t\t\t// but reduces AA quality\n\t\t\tdist = pow(dist, .5);\n\n\t\t\tdist = 1. - dist;\n\n\t\t\treturn mix(\n\t\t\t\t\trgbaM,\n\t\t\t\t\trgbaN,\n\t\t\t\t\tdist * .5\n\t\t\t);\n\t}\n\n\tvoid main() {\n\t\t\tconst float edgeDetectionQuality = 0.1 ;//.05 ; //\u8D8A\u9AD8\uFF0C\u8D8A\u4FDD\u7559\u7EC6\u8282\uFF1B\u8D8A\u4F4E\uFF0C\u8D8A\u5E73\u6ED1 \u4F46\u6A21\u7CCA \n\t\t\tconst float invEdgeDetectionQuality = 1. / edgeDetectionQuality;\n\n\t\t\tgl_FragColor = FxaaPixelShader(\n\t\t\t\t\tvUv,\n\t\t\t\t\ttDiffuse,\n\t\t\t\t\tresolution,\n\t\t\t\t\tedgeDetectionQuality, // [0,1] contrast needed, otherwise early discard\n\t\t\t\t\tinvEdgeDetectionQuality\n\t\t\t);\n //\u5355\u72EC\u6E32\u67D3\u6D4B\u91CF\u7EBF\u6709\u9ED1\u8FB9\uFF0C\u56E0\u4E3A\u900F\u660E\u533A\u57DF\u7684clearColor\u662F(0,0,0)\uFF0C\u6A21\u7CCA\u5316\u7684\u65F6\u5019\u91C7\u7528\u4E86\u8FD9\u4E9B\u9ED1\u8272\u56E0\u5B50\u6765\u6DF7\u8272\u3002\u56E0\u4E3A\u6D4B\u91CF\u7EBF\u989C\u8272\u53EF\u80FD\u591A\u79CD\uFF0C\u4E5F\u4E0D\u80FD\u76F4\u63A5\u4FEE\u6539clearColor\u4E3A\u5176\u989C\u8272\uFF0C\u4E14\u8FD8\u6709label\u3002\n //\u6545\u800C\u65E0\u6CD5\u5355\u72EC\u6E32\u67D3\u6D4B\u91CF\u7EBF\uFF0C\u800C\u9700\u8981\u5C06\u5E95\u56FE\u4E00\u8D77\u6E32\u67D3\u3002\n }\n\t"
  79866. };
  79867. /**
  79868. * @author spidersharma / http://eduperiment.com/
  79869. */
  79870. var OutlinePass = function OutlinePass(selectedObjects) {
  79871. /* scene = scene;
  79872. camera = camera; */
  79873. this.selectedObjects = selectedObjects !== undefined ? selectedObjects : [];
  79874. this.visibleEdgeColor = new Color(1, 1, 1);
  79875. this.hiddenEdgeColor = new Color(0.1, 0.04, 0.02);
  79876. this.edgeGlow = 0.0;
  79877. this.usePatternTexture = false;
  79878. //this.edgeThickness = 1.0;
  79879. this.edgeStrength = 50;
  79880. this.downSampleRatio = 1; //2; // 抗锯齿 值越低renderTarget size越大,抗锯齿越强,线条可越细(或许可以把模糊化去掉?)
  79881. this.pulsePeriod = 0;
  79882. this.showHiddenPart = false; //是否判断被遮住的部分,以设置hiddenEdgeColor。一般不需要
  79883. Pass.call(this);
  79884. this.resolution = new Vector2(256, 256);
  79885. var pars = {
  79886. minFilter: LinearFilter,
  79887. magFilter: LinearFilter,
  79888. format: RGBAFormat
  79889. };
  79890. var resx = Math.round(this.resolution.x / this.downSampleRatio);
  79891. var resy = Math.round(this.resolution.y / this.downSampleRatio);
  79892. this.renderTargetMaskBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, pars);
  79893. this.renderTargetMaskBuffer.texture.name = "OutlinePass.mask";
  79894. this.renderTargetMaskBuffer.texture.generateMipmaps = false;
  79895. this.depthMaterial = new MeshDepthMaterial();
  79896. this.depthMaterial.side = DoubleSide;
  79897. this.depthMaterial.depthPacking = RGBADepthPacking;
  79898. this.depthMaterial.blending = NoBlending;
  79899. this.prepareMaskMaterial = this.getPrepareMaskMaterial();
  79900. this.prepareMaskMaterial.side = DoubleSide;
  79901. this.renderTargetDepthBuffer = new WebGLRenderTarget(this.resolution.x, this.resolution.y, pars);
  79902. this.renderTargetDepthBuffer.texture.name = "OutlinePass.depth";
  79903. this.renderTargetDepthBuffer.texture.generateMipmaps = false;
  79904. this.edgeDetectionMaterial = this.getEdgeDetectionMaterial(this.edgeStrength);
  79905. this.renderTargetEdgeBuffer1 = new WebGLRenderTarget(resx, resy, pars);
  79906. this.renderTargetEdgeBuffer1.texture.name = "OutlinePass.edge1";
  79907. this.renderTargetEdgeBuffer1.texture.generateMipmaps = false;
  79908. // Overlay material
  79909. this.overlayMaterial = this.getOverlayMaterial();
  79910. // copy material
  79911. this.copyUniforms = UniformsUtils.clone(CopyShader.uniforms);
  79912. this.copyUniforms["opacity"].value = 1.0;
  79913. this.materialCopy = new ShaderMaterial({
  79914. uniforms: this.copyUniforms,
  79915. vertexShader: CopyShader.vertexShader,
  79916. fragmentShader: CopyShader.fragmentShader,
  79917. blending: NoBlending,
  79918. depthTest: false,
  79919. depthWrite: false,
  79920. transparent: true
  79921. });
  79922. this.enabled = true;
  79923. this.needsSwap = false;
  79924. this.oldClearColor = new Color();
  79925. this.oldClearAlpha = 1;
  79926. this.camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
  79927. this.scene = new Scene();
  79928. this.quad = new Mesh(new PlaneBufferGeometry(2, 2), null);
  79929. this.quad.frustumCulled = false; // Avoid getting clipped
  79930. this.scene.add(this.quad);
  79931. this.textureMatrix = new Matrix4();
  79932. viewer.addEventListener('viewerResize', e => {
  79933. var size = viewer.renderer.getSize(new Vector2());
  79934. this.renderTargetEdgeBuffer1.setSize(size.x, size.y);
  79935. this.renderTargetMaskBuffer.setSize(size.x, size.y);
  79936. this.resolution.set(size.x, size.y);
  79937. });
  79938. };
  79939. OutlinePass.prototype = Object.assign(Object.create(Pass.prototype), {
  79940. constructor: OutlinePass,
  79941. dispose: function dispose() {
  79942. this.renderTargetMaskBuffer.dispose();
  79943. this.renderTargetEdgeBuffer1.dispose();
  79944. this.renderTargetDepthBuffer.dispose();
  79945. },
  79946. replaceDepthToViewZ(camera) {
  79947. var type = camera.isPerspectiveCamera ? 'perspective' : 'orthographic';
  79948. if (type == this.lastCameraType) return;
  79949. this.lastCameraType = type;
  79950. this.prepareMaskMaterial.fragmentShader = this.prepareMaskMaterial.fragmentShader.replace(/DEPTH_TO_VIEW_Z/g, type + 'DepthToViewZ');
  79951. this.prepareMaskMaterial.needsUpdate = true;
  79952. },
  79953. setSize: function setSize(width, height) {},
  79954. changeVisibilityOfSelectedObjects: function changeVisibilityOfSelectedObjects(bVisible) {
  79955. function gatherSelectedMeshesCallBack(object) {
  79956. /* if ( object.isMesh ) { */
  79957. if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) {
  79958. /* if ( bVisible ) {
  79959. object.visible = object.userData.oldVisible;
  79960. delete object.userData.oldVisible;
  79961. } else {
  79962. object.userData.oldVisible = object.visible;
  79963. object.visible = bVisible;
  79964. } */
  79965. Potree.Utils.updateVisible(object, 'overlinePass', bVisible);
  79966. }
  79967. }
  79968. for (var i = 0; i < this.selectedObjects.length; i++) {
  79969. var selectedObject = this.selectedObjects[i];
  79970. selectedObject.traverse(gatherSelectedMeshesCallBack);
  79971. }
  79972. },
  79973. changeVisibilityOfNonSelectedObjects: function changeVisibilityOfNonSelectedObjects(bVisible, scenes) {
  79974. var selectedMeshes = [];
  79975. function gatherSelectedMeshesCallBack(object) {
  79976. //if ( object.isMesh ) selectedMeshes.push( object );
  79977. if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) {
  79978. selectedMeshes.push(object);
  79979. }
  79980. }
  79981. for (var i = 0; i < this.selectedObjects.length; i++) {
  79982. var selectedObject = this.selectedObjects[i];
  79983. selectedObject.traverse(gatherSelectedMeshesCallBack);
  79984. }
  79985. function VisibilityChangeCallBack(object) {
  79986. if (object.isPointcloud || object.isMesh || object.isLine || object.isSprite) {
  79987. var bFound = false;
  79988. for (var i = 0; i < selectedMeshes.length; i++) {
  79989. var selectedObjectId = selectedMeshes[i].id;
  79990. if (selectedObjectId === object.id) {
  79991. bFound = true;
  79992. break;
  79993. }
  79994. }
  79995. if (!bFound) {
  79996. var visibility = object.visible;
  79997. Potree.Utils.updateVisible(object, 'overlinePass', bVisible); //add
  79998. //但保不齐在设置为false后,渲染时又true了,所以在其他地方update时设置visible 得用updateVisible
  79999. if (!bVisible) {
  80000. object.visible = false;
  80001. } else {
  80002. object.visible = !!object.bVisible;
  80003. }
  80004. object.bVisible = visibility;
  80005. //这两种updateVisible 和 visible 设置都不能去掉, 第一块是为了防止有的visible不是通过updateVisible设置的; 第二块是为了防止渲染时updateVisible又修改了visible为true, 另外渲染时
  80006. return {
  80007. stopContinue: true
  80008. }; //for pointcloud
  80009. }
  80010. }
  80011. }
  80012. scenes.forEach(scene => scene.traverse(VisibilityChangeCallBack));
  80013. },
  80014. updateTextureMatrix: function updateTextureMatrix(camera) {
  80015. this.textureMatrix.set(0.5, 0.0, 0.0, 0.5, 0.0, 0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0);
  80016. this.textureMatrix.multiply(camera.projectionMatrix);
  80017. this.textureMatrix.multiply(camera.matrixWorldInverse);
  80018. },
  80019. render: function render(scenes, camera, viewports, renderer, writeBuffer, readBuffer, maskActive, renderFun) {
  80020. if (!(scenes instanceof Array)) scenes = [scenes];
  80021. if (this.selectedObjects.length > 0 && this.edgeStrength > 0) {
  80022. var render2 = function render2(target) {
  80023. var dontRenderRtEDL = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  80024. if (renderFun) {
  80025. renderFun({
  80026. target,
  80027. dontRenderRtEDL
  80028. });
  80029. } else {
  80030. renderer.setRenderTarget(target);
  80031. renderer.clear();
  80032. scenes.forEach(scene => renderer.render(scene, camera));
  80033. }
  80034. };
  80035. this.oldClearColor.copy(renderer.getClearColor(new Color()));
  80036. this.oldClearAlpha = renderer.getClearAlpha();
  80037. var oldAutoClear = renderer.autoClear;
  80038. var oldTarget = renderer.getRenderTarget();
  80039. renderer.autoClear = false;
  80040. if (maskActive) renderer.context.disable(renderer.context.STENCIL_TEST);
  80041. renderer.setClearColor(0xffffff, 1);
  80042. var oldBG = viewer.background,
  80043. oldBgOpacity = viewer.backgroundOpacity;
  80044. viewer.background = new Color(1, 1, 1);
  80045. viewer.backgroundOpacity = 1;
  80046. if (this.showHiddenPart) {
  80047. //几乎不会使用
  80048. viewports.forEach(e => {
  80049. e.oldBeforeRender = e.beforeRender;
  80050. e.beforeRender = () => {
  80051. e.oldBeforeRender && e.oldBeforeRender();
  80052. this.replaceDepthToViewZ(e.camera);
  80053. };
  80054. });
  80055. // Make selected objects invisible
  80056. this.changeVisibilityOfSelectedObjects(false);
  80057. scenes.forEach(scene => {
  80058. scene.currentBackground = scene.background;
  80059. scene.background = null;
  80060. // 1. Draw Non Selected objects in the depth buffer
  80061. scene.overrideMaterial = this.depthMaterial;
  80062. });
  80063. render2(this.renderTargetDepthBuffer);
  80064. // Make selected objects visible
  80065. this.changeVisibilityOfSelectedObjects(true);
  80066. viewports.forEach(e => {
  80067. e.beforeRender = () => {
  80068. e.oldBeforeRender && e.oldBeforeRender();
  80069. // Update Texture Matrix for Depth compare
  80070. this.updateTextureMatrix(e.camera);
  80071. this.prepareMaskMaterial.uniforms["cameraNearFar"].value = new Vector2(e.camera.near, e.camera.far);
  80072. };
  80073. });
  80074. } else {
  80075. //不渲染背景
  80076. scenes.forEach(scene => {
  80077. scene.currentBackground = scene.background;
  80078. scene.background = null;
  80079. });
  80080. }
  80081. var colorType,
  80082. colors = new Map(),
  80083. opas = new Map();
  80084. {
  80085. //绘制选中部分
  80086. // Make non selected objects invisible, and draw only the selected objects, by comparing the depth buffer of non selected objects
  80087. this.changeVisibilityOfNonSelectedObjects(false, scenes);
  80088. scenes.forEach(scene => {
  80089. scene.overrideMaterial = this.prepareMaskMaterial;
  80090. });
  80091. if (this.showHiddenPart) {
  80092. this.prepareMaskMaterial.uniforms["depthTexture"].value = this.renderTargetDepthBuffer.texture;
  80093. this.prepareMaskMaterial.uniforms["textureMatrix"].value = this.textureMatrix;
  80094. }
  80095. //因为点云不受prepareMaskMaterial作用,所以手动将他们变为黑色不透明
  80096. viewer.scene.pointclouds.forEach(e => {
  80097. //先将点云透明度变为1,因为点云透明度莫名其妙会影响其r值//
  80098. colorType = e.material.activeAttributeName;
  80099. e.material.activeAttributeName = 'color';
  80100. colors.set(e, e.material.color);
  80101. e.material.color = '#000000';
  80102. opas.set(e, e.material.opacity);
  80103. e.material.opacity = 1;
  80104. });
  80105. }
  80106. render2(this.renderTargetMaskBuffer);
  80107. {
  80108. //恢复
  80109. viewer.scene.pointclouds.forEach(e => {
  80110. e.material.activeAttributeName = colorType;
  80111. e.material.color = colors.get(e);
  80112. e.material.opacity = opas.get(e);
  80113. });
  80114. if (this.showHiddenPart) {
  80115. viewports.forEach(e => {
  80116. e.beforeRender = e.oldBeforeRender;
  80117. });
  80118. }
  80119. scenes.forEach(scene => {
  80120. scene.overrideMaterial = null;
  80121. scene.background = scene.currentBackground;
  80122. });
  80123. viewer.background = oldBG;
  80124. viewer.backgroundOpacity = oldBgOpacity;
  80125. this.changeVisibilityOfNonSelectedObjects(true, scenes);
  80126. }
  80127. //检测边缘并绘制
  80128. // 3. Apply Edge Detection Pass
  80129. this.quad.material = this.edgeDetectionMaterial;
  80130. this.edgeDetectionMaterial.uniforms["maskTexture"].value = this.renderTargetMaskBuffer.texture; //this.renderTargetMaskDownSampleBuffer.texture;
  80131. this.edgeDetectionMaterial.uniforms["texSize"].value = new Vector2(this.resolution.x, this.resolution.y); //new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  80132. //this.edgeDetectionMaterial.uniforms[ "texSize" ].value = new THREE.Vector2(this.renderTargetMaskBuffer.width, this.renderTargetMaskBuffer.height)//new THREE.Vector2( this.renderTargetMaskDownSampleBuffer.width, this.renderTargetMaskDownSampleBuffer.height );
  80133. this.edgeDetectionMaterial.uniforms["edgeStrength"].value = this.edgeStrength;
  80134. this.edgeDetectionMaterial.uniforms["visibleEdgeColor"].value = this.visibleEdgeColor; //this.tempPulseColor1;
  80135. this.edgeDetectionMaterial.uniforms["hiddenEdgeColor"].value = this.hiddenEdgeColor; //this.tempPulseColor2;
  80136. var buffer;
  80137. if (this.renderToScreen) {
  80138. this.quad.material.transparent = true;
  80139. buffer = null;
  80140. renderer.setClearColor(this.oldClearColor, this.oldClearAlpha);
  80141. render2(null, false); //普通绘制原场景
  80142. //绘制到全屏
  80143. var renderSize = renderer.getSize(new Vector2()); //是client大小
  80144. renderer.setViewport(0, 0, renderSize.x, renderSize.y); //规定视口,影响图形变换(画布的使用范围)
  80145. renderer.setScissorTest(false);
  80146. } else {
  80147. buffer = readBuffer;
  80148. renderer.setClearColor(0x000000, 0);
  80149. renderer.clear();
  80150. }
  80151. renderer.setRenderTarget(buffer);
  80152. renderer.render(this.scene, this.camera); //将边缘覆盖上去
  80153. renderer.setRenderTarget(oldTarget);
  80154. renderer.setClearColor(this.oldClearColor, this.oldClearAlpha);
  80155. renderer.autoClear = oldAutoClear;
  80156. return true;
  80157. }
  80158. },
  80159. getPrepareMaskMaterial: function getPrepareMaskMaterial() {
  80160. if (this.showHiddenPart) {
  80161. return new ShaderMaterial({
  80162. uniforms: {
  80163. "depthTexture": {
  80164. value: null
  80165. },
  80166. "cameraNearFar": {
  80167. value: new Vector2(0.5, 0.5)
  80168. },
  80169. "textureMatrix": {
  80170. value: new Matrix4()
  80171. }
  80172. },
  80173. vertexShader: ['varying vec4 projTexCoord;', 'varying vec4 vPosition;', 'uniform mat4 textureMatrix;', 'void main() {', ' vPosition = modelViewMatrix * vec4( position, 1.0 );', ' vec4 worldPosition = modelMatrix * vec4( position, 1.0 );', ' projTexCoord = textureMatrix * worldPosition;', ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n'),
  80174. fragmentShader: ['#include <packing>', 'varying vec4 vPosition;', 'varying vec4 projTexCoord;', 'uniform sampler2D depthTexture;', 'uniform vec2 cameraNearFar;', 'void main() {', ' float depth = unpackRGBAToDepth(texture2DProj( depthTexture, projTexCoord ));', ' float viewZ = - DEPTH_TO_VIEW_Z( depth, cameraNearFar.x, cameraNearFar.y );', ' float depthTest = (-vPosition.z > viewZ) ? 1.0 : 0.0;',
  80175. //决定是否为hiddenPart
  80176. ' gl_FragColor = vec4(0.0, depthTest, 1.0, 1.0);', '}'].join('\n')
  80177. }); //没有绘制部分的颜色是clearColor,255
  80178. } else {
  80179. return new MeshBasicMaterial({
  80180. color: '#000000'
  80181. }); //不检测深度,不判断遮挡
  80182. }
  80183. },
  80184. getEdgeDetectionMaterial: function getEdgeDetectionMaterial(edgeStrength) {
  80185. return new ShaderMaterial({
  80186. uniforms: {
  80187. "edgeStrength": {
  80188. value: edgeStrength
  80189. },
  80190. "maskTexture": {
  80191. value: null
  80192. },
  80193. "texSize": {
  80194. value: new Vector2(10, 10)
  80195. },
  80196. "visibleEdgeColor": {
  80197. value: new Vector3(1.0, 1.0, 1.0)
  80198. },
  80199. "hiddenEdgeColor": {
  80200. value: new Vector3(1.0, 1.0, 1.0)
  80201. }
  80202. },
  80203. vertexShader: "varying vec2 vUv;\n\
  80204. void main() {\n\
  80205. vUv = uv;\n\
  80206. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  80207. }",
  80208. /* fragmentShader:
  80209. "varying vec2 vUv;\
  80210. uniform sampler2D maskTexture;\
  80211. uniform vec2 texSize;\
  80212. uniform vec3 visibleEdgeColor;\
  80213. uniform vec3 hiddenEdgeColor;\
  80214. \
  80215. void main() {\n\
  80216. vec2 invSize = 1.0 / texSize;\
  80217. vec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\
  80218. vec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\
  80219. vec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\
  80220. vec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\
  80221. vec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\
  80222. float diff1 = (c1.r - c2.r)*0.5;\
  80223. float diff2 = (c3.r - c4.r)*0.5;\
  80224. float d = length( vec2(diff1, diff2) );\
  80225. float a1 = min(c1.g, c2.g);\
  80226. float a2 = min(c3.g, c4.g);\
  80227. float visibilityFactor = min(a1, a2);\
  80228. vec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\
  80229. gl_FragColor = vec4(edgeColor, 1.0) * vec4(d);\
  80230. }" */
  80231. fragmentShader: "varying vec2 vUv;\n\t\t\t\tuniform sampler2D maskTexture;\n uniform float edgeStrength;\n\t\t\t\tuniform vec2 texSize;\n\t\t\t\tuniform vec3 visibleEdgeColor;\n\t\t\t\tuniform vec3 hiddenEdgeColor;\n\t\t\t\t\n\t\t\t\tvoid main() { \n const float thickness = 1.0;\n vec2 invSize = thickness / texSize;\n\t\t\t\t\tvec4 uvOffset = vec4(1.0, 0.0, 0.0, 1.0) * vec4(invSize, invSize);\n\t\t\t\t\tvec4 c1 = texture2D( maskTexture, vUv + uvOffset.xy);\n\t\t\t\t\tvec4 c2 = texture2D( maskTexture, vUv - uvOffset.xy);\n\t\t\t\t\tvec4 c3 = texture2D( maskTexture, vUv + uvOffset.yw);\n\t\t\t\t\tvec4 c4 = texture2D( maskTexture, vUv - uvOffset.yw);\n\t\t\t\t\tfloat diff1 = (c1.r - c2.r)*0.5; //\u68C0\u6D4B\u8FB9\u7F18\uFF0C\n\t\t\t\t\tfloat diff2 = (c3.r - c4.r)*0.5;\n\t\t\t\t\tfloat d = length( vec2(diff1, diff2) ) * edgeStrength;\n\t\t\t\t\tfloat a1 = min(c1.g, c2.g);\n\t\t\t\t\tfloat a2 = min(c3.g, c4.g);\n\t\t\t\t\tfloat visibilityFactor = min(a1, a2); //\u68C0\u6D4B\u6DF1\u5EA6\u503C\uFF0C\u662F\u5426\u88AB\u906E\u6321\n\t\t\t\t\tvec3 edgeColor = 1.0 - visibilityFactor > 0.001 ? visibleEdgeColor : hiddenEdgeColor;\n\t\t\t\t\t//gl_FragColor = vec4(0.0,1.0,0.0,1.0); \n gl_FragColor = vec4(edgeColor, 1.0) * vec4(d); \n\t\t\t\t}"
  80232. });
  80233. //为什么vec4(0.0,1.0,1.0,1.0); 显示出来的是rgb(109,255,255) ? 几乎只有绿色通道会影响红色通道
  80234. },
  80235. getSeperableBlurMaterial: function getSeperableBlurMaterial(maxRadius) {
  80236. return new ShaderMaterial({
  80237. defines: {
  80238. "MAX_RADIUS": maxRadius
  80239. },
  80240. uniforms: {
  80241. "colorTexture": {
  80242. value: null
  80243. },
  80244. "texSize": {
  80245. value: new Vector2(0.5, 0.5)
  80246. },
  80247. "direction": {
  80248. value: new Vector2(0.5, 0.5)
  80249. },
  80250. "kernelRadius": {
  80251. value: 1.0
  80252. }
  80253. },
  80254. vertexShader: "varying vec2 vUv;\n\
  80255. void main() {\n\
  80256. vUv = uv;\n\
  80257. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  80258. }",
  80259. fragmentShader: "#include <common>\
  80260. varying vec2 vUv;\
  80261. uniform sampler2D colorTexture;\
  80262. uniform vec2 texSize;\
  80263. uniform vec2 direction;\
  80264. uniform float kernelRadius;\
  80265. \
  80266. float gaussianPdf(in float x, in float sigma) {\
  80267. return 0.39894 * exp( -0.5 * x * x/( sigma * sigma))/sigma;\
  80268. }\
  80269. void main() {\
  80270. vec2 invSize = 1.0 / texSize;\
  80271. float weightSum = gaussianPdf(0.0, kernelRadius);\
  80272. vec3 diffuseSum = texture2D( colorTexture, vUv).rgb * weightSum;\
  80273. vec2 delta = direction * invSize * kernelRadius/float(MAX_RADIUS);\
  80274. vec2 uvOffset = delta;\
  80275. for( int i = 1; i <= MAX_RADIUS; i ++ ) {\
  80276. float w = gaussianPdf(uvOffset.x, kernelRadius);\
  80277. vec3 sample1 = texture2D( colorTexture, vUv + uvOffset).rgb;\
  80278. vec3 sample2 = texture2D( colorTexture, vUv - uvOffset).rgb;\
  80279. diffuseSum += ((sample1 + sample2) * w);\
  80280. weightSum += (2.0 * w);\
  80281. uvOffset += delta;\
  80282. }\
  80283. gl_FragColor = vec4(diffuseSum/weightSum, 1.0);\
  80284. }"
  80285. });
  80286. },
  80287. getOverlayMaterial: function getOverlayMaterial() {
  80288. //对边缘线进一步处理,已被废弃
  80289. return new ShaderMaterial({
  80290. uniforms: {
  80291. "maskTexture": {
  80292. value: null
  80293. },
  80294. "edgeTexture1": {
  80295. value: null
  80296. },
  80297. "edgeTexture2": {
  80298. value: null
  80299. },
  80300. "patternTexture": {
  80301. value: null
  80302. },
  80303. "edgeStrength": {
  80304. value: 1.0
  80305. },
  80306. "edgeGlow": {
  80307. value: 1.0
  80308. },
  80309. "usePatternTexture": {
  80310. value: 0.0
  80311. }
  80312. },
  80313. vertexShader: "varying vec2 vUv;\n\
  80314. void main() {\n\
  80315. vUv = uv;\n\
  80316. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\
  80317. }",
  80318. /* fragmentShader:
  80319. "varying vec2 vUv;\
  80320. uniform sampler2D maskTexture;\
  80321. uniform sampler2D edgeTexture1;\
  80322. uniform sampler2D edgeTexture2;\
  80323. uniform sampler2D patternTexture;\
  80324. uniform float edgeStrength;\
  80325. uniform float edgeGlow;\
  80326. uniform bool usePatternTexture;\
  80327. \
  80328. void main() {\
  80329. vec4 edgeValue1 = texture2D(edgeTexture1, vUv);\
  80330. vec4 edgeValue2 = texture2D(edgeTexture2, vUv);\
  80331. vec4 maskColor = texture2D(maskTexture, vUv);\
  80332. vec4 patternColor = texture2D(patternTexture, 6.0 * vUv);\
  80333. float visibilityFactor = 1.0 - maskColor.g > 0.0 ? 1.0 : 0.5;\
  80334. vec4 edgeValue = edgeValue1 + edgeValue2 * edgeGlow;\
  80335. vec4 finalColor = edgeStrength * maskColor.r * edgeValue;\ // 删除 * maskColor.r 也就是去掉遮罩,使模型部分也有outline
  80336. if(usePatternTexture)\
  80337. finalColor += + visibilityFactor * (1.0 - maskColor.r) * (1.0 - patternColor.r);\
  80338. gl_FragColor = finalColor;\
  80339. }", */
  80340. fragmentShader: "varying vec2 vUv; \n\t\t\t\tuniform sampler2D edgeTexture1; \n\t\t\t\tuniform float edgeStrength; \n\t\t\t\t \n\t\t\t\tvoid main() { \n\t\t\t\t\tgl_FragColor = edgeStrength * texture2D(edgeTexture1, vUv); \n\t\t\t\t}",
  80341. blending: AdditiveBlending,
  80342. depthTest: false,
  80343. depthWrite: false,
  80344. transparent: true
  80345. });
  80346. }
  80347. });
  80348. OutlinePass.BlurDirectionX = new Vector2(1.0, 0.0);
  80349. OutlinePass.BlurDirectionY = new Vector2(0.0, 1.0);
  80350. /*
  80351. 渲染步骤:(没有showHiddenPart时)
  80352. 仅绘制选中部分,材质为普通的单色材质,颜色是黑色不透明。未绘制部分的clearColor是白色不透明。
  80353. (详见prepareMaskMaterial,输出的r要为0)
  80354. 然后在上面绘制的图中,根据r的差值,得到边缘线。
  80355. 正常绘制场景之后,将上面的边缘线覆盖于其上。
  80356. (如果showHiddenPart,最开始还要先隐藏选中部分,这是为了得到非选中部分的深度值,然后再绘制选中部分时去比较选中和非选中部分之间的深度差异。以判断是否被遮挡。)
  80357. */
  80358. /**
  80359. * @author mschuetz / http://mschuetz.at
  80360. *
  80361. * adapted from THREE.OrbitControls by
  80362. *
  80363. * @author qiao / https://github.com/qiao
  80364. * @author mrdoob / http://mrdoob.com
  80365. * @author alteredq / http://alteredqualia.com/
  80366. * @author WestLangley / http://github.com/WestLangley
  80367. * @author erich666 / http://erichaines.com
  80368. *
  80369. *
  80370. *
  80371. */
  80372. var minRadius = 2;
  80373. class OrbitControls$1 extends EventDispatcher {
  80374. constructor(viewer, viewport) {
  80375. super();
  80376. this.viewer = viewer;
  80377. this.renderer = viewer.renderer;
  80378. this.scene = null;
  80379. this.sceneControls = new Scene();
  80380. this.rotationSpeed = 3; //旋转速度
  80381. viewport = viewport || viewer.viewports[0];
  80382. this.setCurrentViewport({
  80383. hoverViewport: viewport,
  80384. force: true
  80385. }); //this.currentViewport = viewport
  80386. this.fadeFactor = 20;
  80387. this.yawDelta = 0;
  80388. this.pitchDelta = 0;
  80389. this.panDelta = new Vector2(0, 0);
  80390. this.radiusDelta = 0;
  80391. this.doubleClockZoomEnabled = true;
  80392. this.tweens = [];
  80393. this.dollyStart = new Vector2();
  80394. this.dollyEnd = new Vector2();
  80395. this.keys = {
  80396. FORWARD: ['W'.charCodeAt(0), 38],
  80397. BACKWARD: ['S'.charCodeAt(0), 40],
  80398. LEFT: ['A'.charCodeAt(0), 37],
  80399. RIGHT: ['D'.charCodeAt(0), 39],
  80400. UP: ['Q'.charCodeAt(0)],
  80401. DOWN: ['E'.charCodeAt(0)]
  80402. };
  80403. var drag = e => {
  80404. if (!this.enabled) return;
  80405. var viewport = e.dragViewport;
  80406. if (!viewport /* || viewport.camera.type == "OrthographicCamera" */) return;
  80407. //let camera = viewport.camera
  80408. if (e.drag.object !== null) {
  80409. return;
  80410. }
  80411. var mode;
  80412. if (e.isTouch) {
  80413. if (e.touches.length == 1) {
  80414. mode = 'rotate';
  80415. } else {
  80416. mode = 'scale-pan';
  80417. }
  80418. } else {
  80419. mode = e.buttons === Potree.defines.Buttons.LEFT ? 'rotate' : 'pan';
  80420. }
  80421. if (e.drag.startHandled === undefined) {
  80422. e.drag.startHandled = true;
  80423. this.dispatchEvent({
  80424. type: 'start'
  80425. });
  80426. }
  80427. var ndrag = e.drag.pointerDelta.clone(); //.add(new THREE.Vector2(1,1)).multiplyScalar(0.5)
  80428. ndrag.y *= -1;
  80429. if (mode == 'rotate') {
  80430. this.yawDelta += ndrag.x * this.rotationSpeed;
  80431. this.pitchDelta += ndrag.y * this.rotationSpeed;
  80432. } else if (mode == 'pan') {
  80433. this.panDelta.x += ndrag.x;
  80434. this.panDelta.y += ndrag.y;
  80435. } else if (mode == 'scale-pan') {
  80436. //add
  80437. this.dollyEnd.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  80438. var scale = this.dollyEnd.length() / this.dollyStart.length();
  80439. this.dollyStart.copy(this.dollyEnd);
  80440. this.radiusDelta = (1 - scale) * this.currentViewport.view.radius;
  80441. //------------------------
  80442. //平移
  80443. var pointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点
  80444. var delta = new Vector2().subVectors(pointer, this.lastScalePointer);
  80445. delta.y *= -1;
  80446. this.panDelta.add(delta);
  80447. this.lastScalePointer = pointer.clone();
  80448. //console.log('scale ',scale, this.radiusDelta)
  80449. }
  80450. this.stopTweens();
  80451. };
  80452. var drop = e => {
  80453. if (!this.enabled) return;
  80454. this.dispatchEvent({
  80455. type: 'end'
  80456. });
  80457. };
  80458. var scroll = e => {
  80459. if (!this.enabled) return;
  80460. var resolvedRadius = this.currentViewport.view.radius + this.radiusDelta;
  80461. if (resolvedRadius < 0.1 && e.delta > 0) return; //防止缩放太小,导致很慢
  80462. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  80463. this.stopTweens();
  80464. };
  80465. var dblclick = e => {
  80466. if (!this.enabled) return;
  80467. if (this.doubleClockZoomEnabled) {
  80468. this.zoomToLocation(e.mouse);
  80469. }
  80470. };
  80471. var previousTouch = null;
  80472. var touchStart = e => {
  80473. previousTouch = e;
  80474. };
  80475. var touchEnd = e => {
  80476. previousTouch = e;
  80477. };
  80478. var touchMove = e => {
  80479. if (!this.enabled) return;
  80480. if (e.touches.length === 2 && previousTouch.touches.length === 2) {
  80481. var prev = previousTouch;
  80482. var curr = e;
  80483. var prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  80484. var prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  80485. var prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  80486. var currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  80487. var currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  80488. var currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  80489. var delta = currDist / prevDist;
  80490. var resolvedRadius = this.currentViewport.view.radius + this.radiusDelta;
  80491. var newRadius = resolvedRadius / delta;
  80492. this.radiusDelta = newRadius - resolvedRadius;
  80493. this.stopTweens();
  80494. } else if (e.touches.length === 3 && previousTouch.touches.length === 3) {
  80495. var _prev = previousTouch;
  80496. var _curr = e;
  80497. var prevMeanX = (_prev.touches[0].pageX + _prev.touches[1].pageX + _prev.touches[2].pageX) / 3;
  80498. var prevMeanY = (_prev.touches[0].pageY + _prev.touches[1].pageY + _prev.touches[2].pageY) / 3;
  80499. var currMeanX = (_curr.touches[0].pageX + _curr.touches[1].pageX + _curr.touches[2].pageX) / 3;
  80500. var currMeanY = (_curr.touches[0].pageY + _curr.touches[1].pageY + _curr.touches[2].pageY) / 3;
  80501. var _delta = {
  80502. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  80503. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  80504. };
  80505. this.panDelta.x += _delta.x;
  80506. this.panDelta.y += _delta.y;
  80507. this.stopTweens();
  80508. }
  80509. previousTouch = e;
  80510. };
  80511. this.addEventListener('touchstart', touchStart);
  80512. this.addEventListener('touchend', touchEnd);
  80513. this.addEventListener('touchmove', touchMove);
  80514. this.viewer.addEventListener('global_drag', drag);
  80515. this.viewer.addEventListener('global_drop', drop);
  80516. this.viewer.addEventListener('global_mousewheel', scroll);
  80517. this.viewer.addEventListener('global_dblclick', dblclick);
  80518. this.viewer.addEventListener('global_touchmove', e => {
  80519. if (e.touches.length > 1) {
  80520. //单指的就触发上一句
  80521. //console.log('global_touchmove' )
  80522. drag(e);
  80523. }
  80524. });
  80525. var prepareScale = e => {
  80526. //触屏的scale
  80527. this.dollyStart.subVectors(e.touches[0].pointer, e.touches[1].pointer);
  80528. this.lastScalePointer = new Vector2().addVectors(e.touches[0].pointer, e.touches[1].pointer).multiplyScalar(0.5); //两个指头的中心点
  80529. };
  80530. this.viewer.addEventListener('global_touchstart', e => {
  80531. if (this.enabled && e.touches.length == 2) {
  80532. //只监听开头两个指头
  80533. prepareScale(e);
  80534. }
  80535. });
  80536. /* this.viewer.addEventListener('global_touchend', (e)=>{
  80537. if(!this.enabled)return
  80538. if(e.touches.length==1){//停止scale,开始rotate
  80539. prepareRotate(e)
  80540. //this.pointerDragStart = null
  80541. //console.log('只剩一个', e.pointer.toArray())
  80542. }
  80543. }) */
  80544. this.viewer.addEventListener('focusOnObject', o => {
  80545. if (o.position && o.CamTarget) {
  80546. var distance = o.position.distanceTo(o.CamTarget);
  80547. if (distance < minRadius) minRadius = distance * 0.5; //融合页面当focus一个很小的物体时,需要将minRadius也调小
  80548. }
  80549. });
  80550. }
  80551. setScene(scene) {
  80552. this.scene = scene;
  80553. }
  80554. setCurrentViewport() {
  80555. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  80556. //add
  80557. if (!this.enabled && !o.force) return;
  80558. if (o.hoverViewport && this.currentViewport != o.hoverViewport) {
  80559. this.currentViewport = o.hoverViewport;
  80560. }
  80561. }
  80562. setEnable(enabled) {
  80563. this.enabled = enabled;
  80564. }
  80565. stop() {
  80566. this.yawDelta = 0;
  80567. this.pitchDelta = 0;
  80568. this.radiusDelta = 0;
  80569. this.panDelta.set(0, 0);
  80570. }
  80571. /* zoomToLocation(mouse){
  80572. if(!this.enabled)return
  80573. let camera = this.scene.getActiveCamera();
  80574. let I = Utils.getMousePointCloudIntersection(
  80575. null, mouse, this.viewer.inputHandler.pointer,
  80576. camera,
  80577. this.viewer,
  80578. this.scene.pointclouds,
  80579. {pickClipped: true});
  80580. if (I === null) {
  80581. return;
  80582. }
  80583. let targetRadius = 0;
  80584. {
  80585. let minimumJumpDistance = 0.2;
  80586. let domElement = this.renderer.domElement;
  80587. let ray = Utils.mouseToRay(this.viewer.inputHandler.pointer , camera, domElement.clientWidth, domElement.clientHeight);
  80588. let nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  80589. let lastNode = nodes[nodes.length - 1];
  80590. let radius = lastNode.getBoundingSphere(new THREE.Sphere()).radius;
  80591. targetRadius = Math.min(this.currentViewport.view.radius, radius);
  80592. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  80593. }
  80594. let d = this.currentViewport.view.direction.multiplyScalar(-1);
  80595. let cameraTargetPosition = new THREE.Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  80596. // TODO Unused: let controlsTargetPosition = I.location;
  80597. let animationDuration = 600;
  80598. let easing = TWEEN.Easing.Quartic.Out;
  80599. { // animate
  80600. let value = {x: 0};
  80601. let tween = new TWEEN.Tween(value).to({x: 1}, animationDuration);
  80602. tween.easing(easing);
  80603. this.tweens.push(tween);
  80604. let startPos = this.currentViewport.view.position.clone();
  80605. let targetPos = cameraTargetPosition.clone();
  80606. let startRadius = this.currentViewport.view.radius;
  80607. let targetRadius = cameraTargetPosition.distanceTo(I.location);
  80608. tween.onUpdate(() => {
  80609. let t = value.x;
  80610. this.currentViewport.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  80611. this.currentViewport.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  80612. this.currentViewport.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  80613. this.currentViewport.view.radius = (1 - t) * startRadius + t * targetRadius;
  80614. this.viewer.setMoveSpeed(this.currentViewport.view.radius);
  80615. });
  80616. tween.onComplete(() => {
  80617. this.tweens = this.tweens.filter(e => e !== tween);
  80618. });
  80619. tween.start();
  80620. }
  80621. } */
  80622. zoomToLocation(mouse) {
  80623. var I = viewer.inputHandler.intersect;
  80624. if (!I) return;
  80625. var object = I.object || I.pointcloud;
  80626. I = I.location;
  80627. if (!I || !object) return;
  80628. var dis = this.currentViewport.view.position.distanceTo(I);
  80629. var bound = object.boundingBox.clone().applyMatrix4(object.matrixWorld);
  80630. var size = bound.getSize(new Vector3());
  80631. var len = size.length();
  80632. var distance = MathUtils.clamp(dis, 0.1, Math.max(len * 0.1, 3));
  80633. minRadius = distance;
  80634. viewer.focusOnObject({
  80635. position: I
  80636. }, 'point', null, {
  80637. distance
  80638. });
  80639. }
  80640. stopTweens() {
  80641. this.tweens.forEach(e => e.stop());
  80642. this.tweens = [];
  80643. }
  80644. update(delta) {
  80645. if (!this.enabled) return;
  80646. var view = this.currentViewport.view; //this.currentViewport.view;
  80647. var camera = this.currentViewport.camera;
  80648. {
  80649. // accelerate while input is given
  80650. var ih = this.viewer.inputHandler;
  80651. var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  80652. var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  80653. var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  80654. var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  80655. var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  80656. var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  80657. var moveSpeed = this.currentViewport.getMoveSpeed() / 20;
  80658. var px = 0,
  80659. py = 0,
  80660. pz = 0;
  80661. if (moveForward) {
  80662. py = 1 * moveSpeed;
  80663. } else if (moveBackward) {
  80664. py = -1 * moveSpeed;
  80665. }
  80666. if (moveLeft) {
  80667. px = -1 * moveSpeed;
  80668. } else if (moveRight) {
  80669. px = 1 * moveSpeed;
  80670. }
  80671. if (moveUp) {
  80672. pz = 1 * moveSpeed;
  80673. } else if (moveDown) {
  80674. pz = -1 * moveSpeed;
  80675. }
  80676. (px != 0 || py != 0 || pz != 0) && view.translate(px, py, pz, true);
  80677. }
  80678. {
  80679. // apply rotation
  80680. var progression = Math.min(1, this.fadeFactor * delta);
  80681. var yaw = view.yaw;
  80682. var pitch = view.pitch;
  80683. var pivot = view.getPivot();
  80684. yaw -= progression * this.yawDelta;
  80685. pitch -= progression * this.pitchDelta;
  80686. view.yaw = yaw;
  80687. view.pitch = pitch;
  80688. var V = this.currentViewport.view.direction.multiplyScalar(-view.radius);
  80689. var position = new Vector3().addVectors(pivot, V);
  80690. view.position.copy(position);
  80691. }
  80692. if (camera.type != 'OrthographicCamera') {
  80693. // apply pan
  80694. /* let progression = Math.min(1, this.fadeFactor * delta);
  80695. let panDistance = progression * view.radius * 3; */
  80696. var panDistance = 2 * view.radius * Math.tan(MathUtils.degToRad(camera.fov / 2)); //参照4dkk。 平移target(也就是平移镜头位置),但还是难以保证跟手(navvis也不一定跟手,但是很奇怪在居中时中心点居然是跟手的,可能计算方式不同)
  80697. //计算了下确实是这么算的。 平移pivot。
  80698. var _px = -this.panDelta.x * panDistance;
  80699. var _py = this.panDelta.y * panDistance;
  80700. view.pan(_px, _py);
  80701. }
  80702. {
  80703. // apply zoom
  80704. var _progression = 1; //Math.min(1, this.fadeFactor * delta);
  80705. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  80706. var radius = view.radius + _progression * this.radiusDelta;
  80707. var _V = view.direction.multiplyScalar(-radius);
  80708. var _position = new Vector3().addVectors(view.getPivot(), _V);
  80709. if (this.constantlyForward) {
  80710. // 到达中心点后还能继续向前移动,也就是能推进中心点
  80711. if (radius < minRadius) {
  80712. radius = minRadius;
  80713. }
  80714. }
  80715. view.radius = radius;
  80716. view.position.copy(_position);
  80717. }
  80718. {
  80719. var speed = view.radius;
  80720. this.viewer.setMoveSpeed && this.viewer.setMoveSpeed(speed);
  80721. }
  80722. {
  80723. // decelerate over time
  80724. /* let progression = Math.min(1, this.fadeFactor * delta);
  80725. let attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  80726. this.yawDelta *= attenuation;
  80727. this.pitchDelta *= attenuation;
  80728. this.panDelta.multiplyScalar(attenuation);
  80729. // this.radiusDelta *= attenuation;
  80730. this.radiusDelta -= progression * this.radiusDelta; */
  80731. //取消衰减,直接stop
  80732. this.stop();
  80733. }
  80734. }
  80735. }
  80736. ;
  80737. // Adapted from three.js VRButton
  80738. class VRButton$1 {
  80739. constructor() {
  80740. this.onStartListeners = [];
  80741. this.onEndListeners = [];
  80742. this.element = null;
  80743. }
  80744. onStart(callback) {
  80745. this.onStartListeners.push(callback);
  80746. }
  80747. onEnd(callback) {
  80748. this.onEndListeners.push(callback);
  80749. }
  80750. static createButton(renderer, options) {
  80751. return _asyncToGenerator(function* () {
  80752. if (options) {
  80753. console.error('THREE.VRButton: The "options" parameter has been removed. Please set the reference space type via renderer.xr.setReferenceSpaceType() instead.');
  80754. }
  80755. var button = new VRButton$1();
  80756. var element = document.createElement('button');
  80757. button.element = element;
  80758. function setEnter() {
  80759. button.element.innerHTML = "\n\t\t\t\t<div style=\"font-size: 0.5em;\">ENTER</div>\n\t\t\t\t<div style=\"font-weight: bold;\">VR</div>\n\t\t\t";
  80760. }
  80761. function setExit() {
  80762. button.element.innerHTML = "\n\t\t\t\t<div style=\"font-size: 0.5em;\">EXIT</div>\n\t\t\t\t<div style=\"font-weight: bold;\">VR</div>\n\t\t\t";
  80763. }
  80764. function showEnterVR( /*device*/
  80765. ) {
  80766. var currentSession = null;
  80767. function onSessionStarted(session) {
  80768. session.addEventListener('end', onSessionEnded);
  80769. for (var listener of button.onStartListeners) {
  80770. listener();
  80771. }
  80772. renderer.xr.setSession(session);
  80773. setExit();
  80774. currentSession = session;
  80775. }
  80776. function onSessionEnded( /*event*/
  80777. ) {
  80778. currentSession.removeEventListener('end', onSessionEnded);
  80779. for (var listener of button.onEndListeners) {
  80780. listener();
  80781. }
  80782. setEnter();
  80783. currentSession = null;
  80784. }
  80785. //
  80786. button.element.style.display = '';
  80787. button.element.style.cursor = 'pointer';
  80788. setEnter();
  80789. button.element.onmouseenter = function () {
  80790. button.element.style.opacity = '1.0';
  80791. };
  80792. button.element.onmouseleave = function () {
  80793. button.element.style.opacity = '0.7';
  80794. };
  80795. button.element.onclick = function () {
  80796. if (currentSession === null) {
  80797. // WebXR's requestReferenceSpace only works if the corresponding feature
  80798. // was requested at session creation time. For simplicity, just ask for
  80799. // the interesting ones as optional features, but be aware that the
  80800. // requestReferenceSpace call will fail if it turns out to be unavailable.
  80801. // ('local' is always available for immersive sessions and doesn't need to
  80802. // be requested separately.)
  80803. var sessionInit = {
  80804. optionalFeatures: ['local-floor', 'bounded-floor', 'hand-tracking']
  80805. };
  80806. navigator.xr.requestSession('immersive-vr', sessionInit).then(onSessionStarted);
  80807. } else {
  80808. currentSession.end();
  80809. }
  80810. };
  80811. }
  80812. function stylizeElement(element) {
  80813. element.style.position = 'absolute';
  80814. element.style.bottom = '20px';
  80815. element.style.padding = '12px 6px';
  80816. element.style.border = '1px solid #fff';
  80817. element.style.borderRadius = '4px';
  80818. element.style.background = 'rgba(0,0,0,0.1)';
  80819. element.style.color = '#fff';
  80820. element.style.font = 'normal 13px sans-serif';
  80821. element.style.textAlign = 'center';
  80822. element.style.opacity = '0.7';
  80823. element.style.outline = 'none';
  80824. element.style.zIndex = '999';
  80825. }
  80826. if ('xr' in navigator) {
  80827. button.element.id = 'VRButton';
  80828. button.element.style.display = 'none';
  80829. stylizeElement(button.element);
  80830. var supported = yield navigator.xr.isSessionSupported('immersive-vr');
  80831. if (supported) {
  80832. showEnterVR();
  80833. return button;
  80834. } else {
  80835. return null;
  80836. }
  80837. } else {
  80838. if (window.isSecureContext === false) {
  80839. console.log("WEBXR NEEDS HTTPS");
  80840. } else {
  80841. console.log("WEBXR not available");
  80842. }
  80843. return null;
  80844. }
  80845. })();
  80846. }
  80847. }
  80848. !function (e, a) {
  80849. "object" == typeof exports && "object" == typeof module ? module.exports = a() : "function" == typeof define && define.amd ? define([], a) : "object" == typeof exports ? exports.DxfParser = a() : e.DxfParser = a();
  80850. }("undefined" != typeof self ? self : undefined, function () {
  80851. return function (e) {
  80852. var a = {};
  80853. function t(r) {
  80854. if (a[r]) return a[r].exports;
  80855. var n = a[r] = {
  80856. i: r,
  80857. l: !1,
  80858. exports: {}
  80859. };
  80860. return e[r].call(n.exports, n, n.exports, t), n.l = !0, n.exports;
  80861. }
  80862. return t.m = e, t.c = a, t.d = function (e, a, r) {
  80863. t.o(e, a) || Object.defineProperty(e, a, {
  80864. enumerable: !0,
  80865. get: r
  80866. });
  80867. }, t.r = function (e) {
  80868. "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, {
  80869. value: "Module"
  80870. }), Object.defineProperty(e, "__esModule", {
  80871. value: !0
  80872. });
  80873. }, t.t = function (e, a) {
  80874. if (1 & a && (e = t(e)), 8 & a) return e;
  80875. if (4 & a && "object" == typeof e && e && e.__esModule) return e;
  80876. var r = Object.create(null);
  80877. if (t.r(r), Object.defineProperty(r, "default", {
  80878. enumerable: !0,
  80879. value: e
  80880. }), 2 & a && "string" != typeof e) for (var n in e) t.d(r, n, function (a) {
  80881. return e[a];
  80882. }.bind(null, n));
  80883. return r;
  80884. }, t.n = function (e) {
  80885. var a = e && e.__esModule ? function () {
  80886. return e.default;
  80887. } : function () {
  80888. return e;
  80889. };
  80890. return t.d(a, "a", a), a;
  80891. }, t.o = function (e, a) {
  80892. return Object.prototype.hasOwnProperty.call(e, a);
  80893. }, t.p = "", t(t.s = 1);
  80894. }([function (e, a, t) {
  80895. var r, n;
  80896. !function (o, c) {
  80897. "use strict";
  80898. void 0 === (n = "function" == typeof (r = function r() {
  80899. var e = function e() {},
  80900. a = "undefined",
  80901. t = ["trace", "debug", "info", "warn", "error"];
  80902. function r(e, a) {
  80903. var t = e[a];
  80904. if ("function" == typeof t.bind) return t.bind(e);
  80905. try {
  80906. return Function.prototype.bind.call(t, e);
  80907. } catch (a) {
  80908. return function () {
  80909. return Function.prototype.apply.apply(t, [e, arguments]);
  80910. };
  80911. }
  80912. }
  80913. function n(a, r) {
  80914. for (var n = 0; n < t.length; n++) {
  80915. var o = t[n];
  80916. this[o] = n < a ? e : this.methodFactory(o, a, r);
  80917. }
  80918. this.log = this.debug;
  80919. }
  80920. function o(t, o, c) {
  80921. return function (t) {
  80922. "debug" === t && (t = "log");
  80923. return typeof console !== a && (void 0 !== console[t] ? r(console, t) : void 0 !== console.log ? r(console, "log") : e);
  80924. }(t) || function (e, t, r) {
  80925. return function () {
  80926. typeof console !== a && (n.call(this, t, r), this[e].apply(this, arguments));
  80927. };
  80928. }.apply(this, arguments);
  80929. }
  80930. function c(e, r, c) {
  80931. var i,
  80932. u = this,
  80933. s = "loglevel";
  80934. function l() {
  80935. var e;
  80936. if (typeof window !== a) {
  80937. try {
  80938. e = window.localStorage[s];
  80939. } catch (e) {}
  80940. if (typeof e === a) try {
  80941. var t = window.document.cookie,
  80942. r = t.indexOf(encodeURIComponent(s) + "=");
  80943. -1 !== r && (e = /^([^;]+)/.exec(t.slice(r))[1]);
  80944. } catch (e) {}
  80945. return void 0 === u.levels[e] && (e = void 0), e;
  80946. }
  80947. }
  80948. e && (s += ":" + e), u.name = e, u.levels = {
  80949. TRACE: 0,
  80950. DEBUG: 1,
  80951. INFO: 2,
  80952. WARN: 3,
  80953. ERROR: 4,
  80954. SILENT: 5
  80955. }, u.methodFactory = c || o, u.getLevel = function () {
  80956. return i;
  80957. }, u.setLevel = function (r, o) {
  80958. if ("string" == typeof r && void 0 !== u.levels[r.toUpperCase()] && (r = u.levels[r.toUpperCase()]), !("number" == typeof r && r >= 0 && r <= u.levels.SILENT)) throw "log.setLevel() called with invalid level: " + r;
  80959. if (i = r, !1 !== o && function (e) {
  80960. var r = (t[e] || "silent").toUpperCase();
  80961. if (typeof window === a) return;
  80962. try {
  80963. return void (window.localStorage[s] = r);
  80964. } catch (e) {}
  80965. try {
  80966. window.document.cookie = encodeURIComponent(s) + "=" + r + ";";
  80967. } catch (e) {}
  80968. }(r), n.call(u, r, e), typeof console === a && r < u.levels.SILENT) return "No console available for logging";
  80969. }, u.setDefaultLevel = function (e) {
  80970. l() || u.setLevel(e, !1);
  80971. }, u.enableAll = function (e) {
  80972. u.setLevel(u.levels.TRACE, e);
  80973. }, u.disableAll = function (e) {
  80974. u.setLevel(u.levels.SILENT, e);
  80975. };
  80976. var v = l();
  80977. null == v && (v = null == r ? "WARN" : r), u.setLevel(v, !1);
  80978. }
  80979. var i = new c(),
  80980. u = {};
  80981. i.getLogger = function (e) {
  80982. if ("string" != typeof e || "" === e) throw new TypeError("You must supply a name when creating a logger.");
  80983. var a = u[e];
  80984. return a || (a = u[e] = new c(e, i.getLevel(), i.methodFactory)), a;
  80985. };
  80986. var s = typeof window !== a ? window.log : void 0;
  80987. return i.noConflict = function () {
  80988. return typeof window !== a && window.log === i && (window.log = s), i;
  80989. }, i.getLoggers = function () {
  80990. return u;
  80991. }, i;
  80992. }) ? r.call(a, t, a, e) : r) || (e.exports = n);
  80993. }();
  80994. }, function (e, a, t) {
  80995. "use strict";
  80996. function r(e) {
  80997. this._pointer = 0, this._data = e, this._eof = !1;
  80998. }
  80999. function n(e, a) {
  81000. return e <= 9 ? a : e >= 10 && e <= 59 ? parseFloat(a) : e >= 60 && e <= 99 ? parseInt(a) : e >= 100 && e <= 109 ? a : e >= 110 && e <= 149 ? parseFloat(a) : e >= 160 && e <= 179 ? parseInt(a) : e >= 210 && e <= 239 ? parseFloat(a) : e >= 270 && e <= 289 ? parseInt(a) : e >= 290 && e <= 299 ? function (e) {
  81001. if ("0" === e) return !1;
  81002. if ("1" === e) return !0;
  81003. throw TypeError("String '" + e + "' cannot be cast to Boolean type");
  81004. }(a) : e >= 300 && e <= 369 ? a : e >= 370 && e <= 389 ? parseInt(a) : e >= 390 && e <= 399 ? a : e >= 400 && e <= 409 ? parseInt(a) : e >= 410 && e <= 419 ? a : e >= 420 && e <= 429 ? parseInt(a) : e >= 430 && e <= 439 ? a : e >= 440 && e <= 459 ? parseInt(a) : e >= 460 && e <= 469 ? parseFloat(a) : e >= 470 && e <= 481 ? a : 999 === e ? a : e >= 1e3 && e <= 1009 ? a : e >= 1010 && e <= 1059 ? parseFloat(a) : e >= 1060 && e <= 1071 ? parseInt(a) : (console.log("WARNING: Group code does not have a defined type: %j", {
  81005. code: e,
  81006. value: a
  81007. }), a);
  81008. }
  81009. t.r(a), r.prototype.next = function () {
  81010. var e;
  81011. if (!this.hasNext()) throw this._eof ? new Error("Cannot call 'next' after EOF group has been read") : new Error("Unexpected end of input: EOF group not read before end of file. Ended on code " + this._data[this._pointer]);
  81012. return e = {
  81013. code: parseInt(this._data[this._pointer])
  81014. }, this._pointer++, e.value = n(e.code, this._data[this._pointer].trim()), this._pointer++, 0 === e.code && "EOF" === e.value && (this._eof = !0), this.lastReadGroup = e, e;
  81015. }, r.prototype.peek = function () {
  81016. if (!this.hasNext()) throw this._eof ? new Error("Cannot call 'next' after EOF group has been read") : new Error("Unexpected end of input: EOF group not read before end of file. Ended on code " + this._data[this._pointer]);
  81017. var e = {
  81018. code: parseInt(this._data[this._pointer])
  81019. };
  81020. return e.value = n(e.code, this._data[this._pointer + 1].trim()), e;
  81021. }, r.prototype.rewind = function (e) {
  81022. e = e || 1, this._pointer = this._pointer - 2 * e;
  81023. }, r.prototype.hasNext = function () {
  81024. return !this._eof && !(this._pointer > this._data.length - 2);
  81025. }, r.prototype.isEOF = function () {
  81026. return this._eof;
  81027. };
  81028. var o = [0, 16711680, 16776960, 65280, 65535, 255, 16711935, 16777215, 8421504, 12632256, 16711680, 16744319, 13369344, 13395558, 10027008, 10046540, 8323072, 8339263, 4980736, 4990502, 16727808, 16752511, 13382400, 13401958, 10036736, 10051404, 8331008, 8343359, 4985600, 4992806, 16744192, 16760703, 13395456, 13408614, 10046464, 10056268, 8339200, 8347455, 4990464, 4995366, 16760576, 16768895, 13408512, 13415014, 10056192, 10061132, 8347392, 8351551, 4995328, 4997670, 16776960, 16777087, 13421568, 13421670, 10000384, 10000460, 8355584, 8355647, 5000192, 5000230, 12582656, 14679935, 10079232, 11717734, 7510016, 8755276, 6258432, 7307071, 3755008, 4344870, 8388352, 12582783, 6736896, 10079334, 5019648, 7510092, 4161280, 6258495, 2509824, 3755046, 4194048, 10485631, 3394560, 8375398, 2529280, 6264908, 2064128, 5209919, 1264640, 3099686, 65280, 8388479, 52224, 6736998, 38912, 5019724, 32512, 4161343, 19456, 2509862, 65343, 8388511, 52275, 6737023, 38950, 5019743, 32543, 4161359, 19475, 2509871, 65407, 8388543, 52326, 6737049, 38988, 5019762, 32575, 4161375, 19494, 2509881, 65471, 8388575, 52377, 6737074, 39026, 5019781, 32607, 4161391, 19513, 2509890, 65535, 8388607, 52428, 6737100, 39064, 5019800, 32639, 4161407, 19532, 2509900, 49151, 8380415, 39372, 6730444, 29336, 5014936, 24447, 4157311, 14668, 2507340, 32767, 8372223, 26316, 6724044, 19608, 5010072, 16255, 4153215, 9804, 2505036, 16383, 8364031, 13260, 6717388, 9880, 5005208, 8063, 4149119, 4940, 2502476, 255, 8355839, 204, 6710988, 152, 5000344, 127, 4145023, 76, 2500172, 4129023, 10452991, 3342540, 8349388, 2490520, 6245528, 2031743, 5193599, 1245260, 3089996, 8323327, 12550143, 6684876, 10053324, 4980888, 7490712, 4128895, 6242175, 2490444, 3745356, 12517631, 14647295, 10027212, 11691724, 7471256, 8735896, 6226047, 7290751, 3735628, 4335180, 16711935, 16744447, 13369548, 13395660, 9961624, 9981080, 8323199, 8339327, 4980812, 4990540, 16711871, 16744415, 13369497, 13395634, 9961586, 9981061, 8323167, 8339311, 4980793, 4990530, 16711807, 16744383, 13369446, 13395609, 9961548, 9981042, 8323135, 8339295, 4980774, 4990521, 16711743, 16744351, 13369395, 13395583, 9961510, 9981023, 8323103, 8339279, 4980755, 4990511, 3355443, 5987163, 8684676, 11382189, 14079702, 16777215];
  81029. function c(e) {
  81030. var a = {};
  81031. e.rewind();
  81032. var t = e.next(),
  81033. r = t.code;
  81034. if (a.x = t.value, r += 10, (t = e.next()).code != r) throw new Error("Expected code for point value to be " + r + " but got " + t.code + ".");
  81035. return a.y = t.value, r += 10, (t = e.next()).code != r ? (e.rewind(), a) : (a.z = t.value, a);
  81036. }
  81037. function i(e, a) {
  81038. switch (a.code) {
  81039. case 0:
  81040. e.type = a.value;
  81041. break;
  81042. case 5:
  81043. e.handle = a.value;
  81044. /* if(e.handle == "2FDDB"){
  81045. console.log(1)
  81046. } */
  81047. break;
  81048. case 6:
  81049. e.lineType = a.value;
  81050. break;
  81051. case 8:
  81052. e.layer = a.value;
  81053. break;
  81054. case 48:
  81055. e.lineTypeScale = a.value;
  81056. break;
  81057. case 60:
  81058. e.visible = 0 === a.value;
  81059. break;
  81060. case 62:
  81061. e.colorIndex = a.value, e.color = (t = Math.abs(a.value), o[t]);
  81062. break;
  81063. case 67:
  81064. e.inPaperSpace = 0 !== a.value;
  81065. break;
  81066. case 100:
  81067. break;
  81068. case 330:
  81069. e.ownerHandle = a.value;
  81070. break;
  81071. case 347:
  81072. e.materialObjectHandle = a.value;
  81073. break;
  81074. case 370:
  81075. e.lineweight = a.value;
  81076. break;
  81077. case 420:
  81078. e.color = a.value;
  81079. break;
  81080. case 1e3:
  81081. e.extendedData = e.extendedData || {}, e.extendedData.customStrings = e.extendedData.customStrings || [], e.extendedData.customStrings.push(a.value);
  81082. break;
  81083. case 1001:
  81084. e.extendedData = e.extendedData || {}, e.extendedData.applicationName = a.value;
  81085. break;
  81086. default:
  81087. return !1;
  81088. }
  81089. var t;
  81090. return !0;
  81091. }
  81092. function u() {}
  81093. function s(e, a) {
  81094. var t,
  81095. r = [],
  81096. n = !1,
  81097. o = !1;
  81098. for (t = 0; t <= 4; t++) {
  81099. for (var c = {}; "EOF" !== a && 0 !== a.code && !o;) {
  81100. switch (a.code) {
  81101. case 10:
  81102. case 11:
  81103. case 12:
  81104. case 13:
  81105. if (n) {
  81106. o = !0;
  81107. continue;
  81108. }
  81109. c.x = a.value, n = !0;
  81110. break;
  81111. case 20:
  81112. case 21:
  81113. case 22:
  81114. case 23:
  81115. c.y = a.value;
  81116. break;
  81117. case 30:
  81118. case 31:
  81119. case 32:
  81120. case 33:
  81121. c.z = a.value;
  81122. break;
  81123. default:
  81124. return r;
  81125. }
  81126. a = e.next();
  81127. }
  81128. r.push(c), n = !1, o = !1;
  81129. }
  81130. return e.rewind(), r;
  81131. }
  81132. function l() {}
  81133. function v() {}
  81134. function d() {}
  81135. function b() {}
  81136. function p() {}
  81137. function f() {}
  81138. function k() {}
  81139. function y() {}
  81140. function x(e, a) {
  81141. if (!e || e <= 0) throw Error("n must be greater than 0 verticies");
  81142. var t,
  81143. r = [],
  81144. n = !1,
  81145. o = !1,
  81146. c = a.lastReadGroup;
  81147. for (t = 0; t < e; t++) {
  81148. for (var i = {}; "EOF" !== c && 0 !== c.code && !o;) {
  81149. switch (c.code) {
  81150. case 10:
  81151. if (n) {
  81152. o = !0;
  81153. continue;
  81154. }
  81155. i.x = c.value, n = !0;
  81156. break;
  81157. case 20:
  81158. i.y = c.value;
  81159. break;
  81160. case 30:
  81161. i.z = c.value;
  81162. break;
  81163. case 40:
  81164. i.startWidth = c.value;
  81165. break;
  81166. case 41:
  81167. i.endWidth = c.value;
  81168. break;
  81169. case 42:
  81170. 0 != c.value && (i.bulge = c.value);
  81171. break;
  81172. default:
  81173. return n && r.push(i), r;
  81174. }
  81175. c = a.next();
  81176. }
  81177. r.push(i), n = !1, o = !1;
  81178. }
  81179. return a.rewind(), r;
  81180. }
  81181. function h() {}
  81182. function g() {}
  81183. function E() {}
  81184. function w() {}
  81185. function m(e, a) {
  81186. var t = {
  81187. type: a.value
  81188. };
  81189. for (a = e.next(); "EOF" != a && 0 != a.code;) i(t, a), a = e.next();
  81190. return t;
  81191. }
  81192. function P() {}
  81193. function F() {}
  81194. function O() {}
  81195. u.ForEntityName = "3DFACE", u.prototype.parseEntity = function (e, a) {
  81196. var t = {
  81197. type: a.value,
  81198. vertices: []
  81199. };
  81200. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81201. switch (a.code) {
  81202. case 70:
  81203. t.shape = 1 == (1 & a.value), t.hasContinuousLinetypePattern = 128 == (128 & a.value);
  81204. break;
  81205. case 10:
  81206. t.vertices = s(e, a), a = e.lastReadGroup;
  81207. break;
  81208. default:
  81209. i(t, a);
  81210. }
  81211. a = e.next();
  81212. }
  81213. return t;
  81214. }, l.ForEntityName = "ARC", l.prototype.parseEntity = function (e, a) {
  81215. var t;
  81216. for (t = {
  81217. type: a.value
  81218. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81219. switch (a.code) {
  81220. case 10:
  81221. t.center = c(e);
  81222. break;
  81223. case 40:
  81224. t.radius = a.value;
  81225. break;
  81226. case 50:
  81227. t.startAngle = Math.PI / 180 * a.value;
  81228. break;
  81229. case 51:
  81230. t.endAngle = Math.PI / 180 * a.value, t.angleLength = t.endAngle - t.startAngle;
  81231. break;
  81232. default:
  81233. i(t, a);
  81234. }
  81235. a = e.next();
  81236. }
  81237. return t;
  81238. }, v.ForEntityName = "ATTDEF", v.prototype.parseEntity = function (e, a) {
  81239. var t = {
  81240. type: a.value,
  81241. scale: 1,
  81242. textStyle: "STANDARD"
  81243. };
  81244. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81245. switch (a.code) {
  81246. case 1:
  81247. t.text = a.value;
  81248. break;
  81249. case 2:
  81250. t.tag = a.value;
  81251. break;
  81252. case 3:
  81253. t.prompt = a.value;
  81254. break;
  81255. case 7:
  81256. t.textStyle = a.value;
  81257. break;
  81258. case 10:
  81259. t.startPoint = c(e);
  81260. break;
  81261. case 11:
  81262. t.endPoint = c(e);
  81263. break;
  81264. case 39:
  81265. t.thickness = a.value;
  81266. break;
  81267. case 40:
  81268. t.textHeight = a.value;
  81269. break;
  81270. case 41:
  81271. t.scale = a.value;
  81272. break;
  81273. case 50:
  81274. t.rotation = a.value;
  81275. break;
  81276. case 51:
  81277. t.obliqueAngle = a.value;
  81278. break;
  81279. case 70:
  81280. t.invisible = !!(1 & a.value), t.constant = !!(2 & a.value), t.verificationRequired = !!(4 & a.value), t.preset = !!(8 & a.value);
  81281. break;
  81282. case 71:
  81283. t.backwards = !!(2 & a.value), t.mirrored = !!(4 & a.value);
  81284. break;
  81285. case 72:
  81286. t.horizontalJustification = a.value;
  81287. break;
  81288. case 73:
  81289. t.fieldLength = a.value;
  81290. break;
  81291. case 74:
  81292. t.verticalJustification = a.value;
  81293. break;
  81294. case 100:
  81295. break;
  81296. case 210:
  81297. t.extrusionDirectionX = a.value;
  81298. break;
  81299. case 220:
  81300. t.extrusionDirectionY = a.value;
  81301. break;
  81302. case 230:
  81303. t.extrusionDirectionZ = a.value;
  81304. break;
  81305. default:
  81306. i(t, a);
  81307. }
  81308. a = e.next();
  81309. }
  81310. return t;
  81311. }, d.ForEntityName = "CIRCLE", d.prototype.parseEntity = function (e, a) {
  81312. var t, r;
  81313. for (t = {
  81314. type: a.value
  81315. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81316. switch (a.code) {
  81317. case 10:
  81318. t.center = c(e);
  81319. break;
  81320. case 40:
  81321. t.radius = a.value;
  81322. break;
  81323. case 50:
  81324. t.startAngle = Math.PI / 180 * a.value;
  81325. break;
  81326. case 51:
  81327. (r = Math.PI / 180 * a.value) < t.startAngle ? t.angleLength = r + 2 * Math.PI - t.startAngle : t.angleLength = r - t.startAngle, t.endAngle = r;
  81328. break;
  81329. default:
  81330. i(t, a);
  81331. }
  81332. a = e.next();
  81333. }
  81334. return t;
  81335. }, b.ForEntityName = "DIMENSION", b.prototype.parseEntity = function (e, a) {
  81336. var t;
  81337. for (t = {
  81338. type: a.value
  81339. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81340. switch (a.code) {
  81341. case 2:
  81342. t.block = a.value;
  81343. break;
  81344. case 10:
  81345. t.anchorPoint = c(e);
  81346. break;
  81347. case 11:
  81348. t.middleOfText = c(e);
  81349. break;
  81350. case 12:
  81351. t.insertionPoint = c(e);
  81352. break;
  81353. case 13:
  81354. t.linearOrAngularPoint1 = c(e);
  81355. break;
  81356. case 14:
  81357. t.linearOrAngularPoint2 = c(e);
  81358. break;
  81359. case 15:
  81360. t.diameterOrRadiusPoint = c(e);
  81361. break;
  81362. case 16:
  81363. t.arcPoint = c(e);
  81364. break;
  81365. case 70:
  81366. t.dimensionType = a.value;
  81367. break;
  81368. case 71:
  81369. t.attachmentPoint = a.value;
  81370. break;
  81371. case 42:
  81372. t.actualMeasurement = a.value;
  81373. break;
  81374. case 1:
  81375. t.text = a.value;
  81376. break;
  81377. case 50:
  81378. t.angle = a.value;
  81379. break;
  81380. default:
  81381. i(t, a);
  81382. }
  81383. a = e.next();
  81384. }
  81385. return t;
  81386. }, p.ForEntityName = "ELLIPSE", p.prototype.parseEntity = function (e, a) {
  81387. var t;
  81388. for (t = {
  81389. type: a.value
  81390. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81391. switch (a.code) {
  81392. case 10:
  81393. t.center = c(e);
  81394. break;
  81395. case 11:
  81396. t.majorAxisEndPoint = c(e);
  81397. break;
  81398. case 40:
  81399. t.axisRatio = a.value;
  81400. break;
  81401. case 41:
  81402. t.startAngle = a.value;
  81403. break;
  81404. case 42:
  81405. t.endAngle = a.value;
  81406. break;
  81407. case 2:
  81408. t.name = a.value;
  81409. break;
  81410. default:
  81411. i(t, a);
  81412. }
  81413. a = e.next();
  81414. }
  81415. return t;
  81416. }, f.ForEntityName = "INSERT", f.prototype.parseEntity = function (e, a) {
  81417. var t;
  81418. for (t = {
  81419. type: a.value
  81420. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81421. switch (a.code) {
  81422. case 2:
  81423. t.name = a.value;
  81424. break;
  81425. case 41:
  81426. t.xScale = a.value;
  81427. break;
  81428. case 42:
  81429. t.yScale = a.value;
  81430. break;
  81431. case 43:
  81432. t.zScale = a.value;
  81433. break;
  81434. case 10:
  81435. t.position = c(e);
  81436. break;
  81437. case 50:
  81438. t.rotation = a.value;
  81439. break;
  81440. case 70:
  81441. t.columnCount = a.value;
  81442. break;
  81443. case 71:
  81444. t.rowCount = a.value;
  81445. break;
  81446. case 44:
  81447. t.columnSpacing = a.value;
  81448. break;
  81449. case 45:
  81450. t.rowSpacing = a.value;
  81451. break;
  81452. case 210:
  81453. t.extrusionDirection = c(e);
  81454. break;
  81455. default:
  81456. i(t, a);
  81457. }
  81458. a = e.next();
  81459. }
  81460. return t;
  81461. }, k.ForEntityName = "LINE", k.prototype.parseEntity = function (e, a) {
  81462. var t = {
  81463. type: a.value,
  81464. vertices: []
  81465. };
  81466. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81467. switch (a.code) {
  81468. case 10:
  81469. t.vertices.unshift(c(e));
  81470. break;
  81471. case 11:
  81472. t.vertices.push(c(e));
  81473. break;
  81474. case 210:
  81475. t.extrusionDirection = c(e);
  81476. break;
  81477. case 100:
  81478. break;
  81479. default:
  81480. i(t, a);
  81481. }
  81482. a = e.next();
  81483. }
  81484. return t;
  81485. }, y.ForEntityName = "LWPOLYLINE", y.prototype.parseEntity = function (e, a) {
  81486. var t = {
  81487. type: a.value,
  81488. vertices: []
  81489. },
  81490. r = 0;
  81491. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81492. switch (a.code) {
  81493. case 38:
  81494. t.elevation = a.value;
  81495. break;
  81496. case 39:
  81497. t.depth = a.value;
  81498. break;
  81499. case 70:
  81500. t.shape = 1 == (1 & a.value), t.hasContinuousLinetypePattern = 128 == (128 & a.value);
  81501. break;
  81502. case 90:
  81503. r = a.value;
  81504. break;
  81505. case 10:
  81506. //t.vertices = x(r, e);
  81507. //改,因有的文件有点问题,可能版本原因
  81508. t.vertices.push(...x(r, e)); //有的文件同一个entity需要多次执行到这里,所以不能直接覆盖,要push
  81509. t.vertices = t.vertices.filter(e => e.x != void 0); //而且会出现空的vertix:{},所以排除下
  81510. break;
  81511. case 43:
  81512. 0 !== a.value && (t.width = a.value);
  81513. break;
  81514. case 210:
  81515. t.extrusionDirectionX = a.value;
  81516. break;
  81517. case 220:
  81518. t.extrusionDirectionY = a.value;
  81519. break;
  81520. case 230:
  81521. t.extrusionDirectionZ = a.value;
  81522. break;
  81523. default:
  81524. i(t, a);
  81525. }
  81526. a = e.next();
  81527. }
  81528. return t;
  81529. }, h.ForEntityName = "MTEXT", h.prototype.parseEntity = function (e, a) {
  81530. var t = {
  81531. type: a.value
  81532. };
  81533. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81534. switch (a.code) {
  81535. case 3:
  81536. case 1:
  81537. t.text ? t.text += a.value : t.text = a.value;
  81538. break;
  81539. case 10:
  81540. t.position = c(e);
  81541. break;
  81542. case 40:
  81543. t.height = a.value;
  81544. break;
  81545. case 41:
  81546. t.width = a.value;
  81547. break;
  81548. case 50:
  81549. t.rotation = a.value;
  81550. break;
  81551. case 71:
  81552. t.attachmentPoint = a.value;
  81553. break;
  81554. case 72:
  81555. t.drawingDirection = a.value;
  81556. break;
  81557. default:
  81558. i(t, a);
  81559. }
  81560. a = e.next();
  81561. }
  81562. return t;
  81563. }, g.ForEntityName = "POINT", g.prototype.parseEntity = function (e, a) {
  81564. var t;
  81565. for (t = {
  81566. type: a.value
  81567. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81568. switch (a.code) {
  81569. case 10:
  81570. t.position = c(e);
  81571. break;
  81572. case 39:
  81573. t.thickness = a.value;
  81574. break;
  81575. case 210:
  81576. t.extrusionDirection = c(e);
  81577. break;
  81578. case 100:
  81579. break;
  81580. default:
  81581. i(t, a);
  81582. }
  81583. a = e.next();
  81584. }
  81585. return t;
  81586. }, E.ForEntityName = "VERTEX", E.prototype.parseEntity = function (e, a) {
  81587. var t = {
  81588. type: a.value
  81589. };
  81590. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81591. switch (a.code) {
  81592. case 10:
  81593. t.x = a.value;
  81594. break;
  81595. case 20:
  81596. t.y = a.value;
  81597. break;
  81598. case 30:
  81599. t.z = a.value;
  81600. break;
  81601. case 40:
  81602. case 41:
  81603. case 42:
  81604. 0 != a.value && (t.bulge = a.value);
  81605. break;
  81606. case 70:
  81607. t.curveFittingVertex = 0 != (1 & a.value), t.curveFitTangent = 0 != (2 & a.value), t.splineVertex = 0 != (8 & a.value), t.splineControlPoint = 0 != (16 & a.value), t.threeDPolylineVertex = 0 != (32 & a.value), t.threeDPolylineMesh = 0 != (64 & a.value), t.polyfaceMeshVertex = 0 != (128 & a.value);
  81608. break;
  81609. case 50:
  81610. case 71:
  81611. t.faceA = a.value;
  81612. break;
  81613. case 72:
  81614. t.faceB = a.value;
  81615. break;
  81616. case 73:
  81617. t.faceC = a.value;
  81618. break;
  81619. case 74:
  81620. t.faceD = a.value;
  81621. break;
  81622. default:
  81623. i(t, a);
  81624. }
  81625. a = e.next();
  81626. }
  81627. return t;
  81628. }, w.ForEntityName = "POLYLINE", w.prototype.parseEntity = function (e, a) {
  81629. var t = {
  81630. type: a.value,
  81631. vertices: []
  81632. };
  81633. for (a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81634. switch (a.code) {
  81635. case 10:
  81636. case 20:
  81637. case 30:
  81638. case 39:
  81639. t.thickness = a.value;
  81640. break;
  81641. case 40:
  81642. case 41:
  81643. break;
  81644. case 70:
  81645. t.shape = 0 != (1 & a.value), t.includesCurveFitVertices = 0 != (2 & a.value), t.includesSplineFitVertices = 0 != (4 & a.value), t.is3dPolyline = 0 != (8 & a.value), t.is3dPolygonMesh = 0 != (16 & a.value), t.is3dPolygonMeshClosed = 0 != (32 & a.value), t.isPolyfaceMesh = 0 != (64 & a.value), t.hasContinuousLinetypePattern = 0 != (128 & a.value);
  81646. break;
  81647. case 71:
  81648. case 72:
  81649. case 73:
  81650. case 74:
  81651. case 75:
  81652. break;
  81653. case 210:
  81654. t.extrusionDirection = c(e);
  81655. break;
  81656. default:
  81657. i(t, a);
  81658. }
  81659. a = e.next();
  81660. }
  81661. return t.vertices = function (e, a) {
  81662. var t = new E(),
  81663. r = [];
  81664. for (; !e.isEOF();) if (0 === a.code) if ("VERTEX" === a.value) r.push(t.parseEntity(e, a)), a = e.lastReadGroup;else if ("SEQEND" === a.value) {
  81665. m(e, a);
  81666. break;
  81667. }
  81668. return r;
  81669. }(e, a), t;
  81670. }, P.ForEntityName = "SOLID", P.prototype.parseEntity = function (e, a) {
  81671. var t;
  81672. for ((t = {
  81673. type: a.value
  81674. }).points = [], a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81675. switch (a.code) {
  81676. case 10:
  81677. t.points[0] = c(e);
  81678. break;
  81679. case 11:
  81680. t.points[1] = c(e);
  81681. break;
  81682. case 12:
  81683. t.points[2] = c(e);
  81684. break;
  81685. case 13:
  81686. t.points[3] = c(e);
  81687. break;
  81688. case 210:
  81689. t.extrusionDirection = c(e);
  81690. break;
  81691. default:
  81692. i(t, a);
  81693. }
  81694. a = e.next();
  81695. }
  81696. return t;
  81697. }, F.ForEntityName = "SPLINE", F.prototype.parseEntity = function (e, a) {
  81698. var t;
  81699. for (t = {
  81700. type: a.value
  81701. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81702. switch (a.code) {
  81703. case 10:
  81704. t.controlPoints || (t.controlPoints = []), t.controlPoints.push(c(e));
  81705. break;
  81706. case 11:
  81707. t.fitPoints || (t.fitPoints = []), t.fitPoints.push(c(e));
  81708. break;
  81709. case 12:
  81710. t.startTangent = c(e);
  81711. break;
  81712. case 13:
  81713. t.endTangent = c(e);
  81714. break;
  81715. case 40:
  81716. t.knotValues || (t.knotValues = []), t.knotValues.push(a.value);
  81717. break;
  81718. case 70:
  81719. 0 != (1 & a.value) && (t.closed = !0), 0 != (2 & a.value) && (t.periodic = !0), 0 != (4 & a.value) && (t.rational = !0), 0 != (8 & a.value) && (t.planar = !0), 0 != (16 & a.value) && (t.planar = !0, t.linear = !0);
  81720. break;
  81721. case 71:
  81722. t.degreeOfSplineCurve = a.value;
  81723. break;
  81724. case 72:
  81725. t.numberOfKnots = a.value;
  81726. break;
  81727. case 73:
  81728. t.numberOfControlPoints = a.value;
  81729. break;
  81730. case 74:
  81731. t.numberOfFitPoints = a.value;
  81732. break;
  81733. case 210:
  81734. t.normalVector = c(e);
  81735. break;
  81736. default:
  81737. i(t, a);
  81738. }
  81739. a = e.next();
  81740. }
  81741. return t;
  81742. }, O.ForEntityName = "TEXT", O.prototype.parseEntity = function (e, a) {
  81743. var t;
  81744. for (t = {
  81745. type: a.value
  81746. }, a = e.next(); "EOF" !== a && 0 !== a.code;) {
  81747. switch (a.code) {
  81748. case 10:
  81749. t.startPoint = c(e);
  81750. break;
  81751. case 11:
  81752. t.endPoint = c(e);
  81753. break;
  81754. case 40:
  81755. t.textHeight = a.value;
  81756. break;
  81757. case 41:
  81758. t.xScale = a.value;
  81759. break;
  81760. case 50:
  81761. t.rotation = a.value;
  81762. break;
  81763. case 1:
  81764. t.text = a.value;
  81765. break;
  81766. case 72:
  81767. t.halign = a.value;
  81768. break;
  81769. case 73:
  81770. t.valign = a.value;
  81771. break;
  81772. default:
  81773. i(t, a);
  81774. }
  81775. a = e.next();
  81776. }
  81777. return t;
  81778. };
  81779. var N = t(0);
  81780. function T() {
  81781. var e;
  81782. this._entityHandlers = {}, (e = this).registerEntityHandler(u), e.registerEntityHandler(l), e.registerEntityHandler(v), e.registerEntityHandler(d), e.registerEntityHandler(b), e.registerEntityHandler(p), e.registerEntityHandler(f), e.registerEntityHandler(k), e.registerEntityHandler(y), e.registerEntityHandler(h), e.registerEntityHandler(g), e.registerEntityHandler(w), e.registerEntityHandler(P), e.registerEntityHandler(F), e.registerEntityHandler(O);
  81783. }
  81784. function S(e) {
  81785. N.debug("unhandled group " + L(e));
  81786. }
  81787. function L(e) {
  81788. return e.code + ":" + e.value;
  81789. }
  81790. N.setLevel("error"), T.prototype.parse = function (e, a) {
  81791. throw new Error("read() not implemented. Use readSync()");
  81792. }, T.prototype.registerEntityHandler = function (e) {
  81793. var a = new e();
  81794. this._entityHandlers[e.ForEntityName] = a;
  81795. }, T.prototype.parseSync = function (e) {
  81796. return "string" == typeof e ? this._parse(e) : (console.error("Cannot read dxf source of type `" + typeof e), null);
  81797. }, T.prototype.parseStream = function (e, a) {
  81798. var t = "",
  81799. r = this;
  81800. e.on("data", function (e) {
  81801. t += e;
  81802. }), e.on("end", function () {
  81803. try {
  81804. var e = r._parse(t);
  81805. } catch (e) {
  81806. return a(e);
  81807. }
  81808. a(null, e);
  81809. }), e.on("error", function (e) {
  81810. a(e);
  81811. });
  81812. }, T.prototype._parse = function (e) {
  81813. var a,
  81814. t,
  81815. n = {},
  81816. c = 0,
  81817. i = e.split(/\r\n|\r|\n/g);
  81818. if (!(a = new r(i)).hasNext()) throw Error("Empty file");
  81819. var u = this,
  81820. s = function s(e, a) {
  81821. return t.code === e && t.value === a;
  81822. },
  81823. l = function l() {
  81824. var e = null,
  81825. r = null,
  81826. n = {};
  81827. for (t = a.next();;) {
  81828. if (s(0, "ENDSEC")) {
  81829. e && (n[e] = r);
  81830. break;
  81831. }
  81832. 9 === t.code ? (e && (n[e] = r), e = t.value) : 10 === t.code ? r = {
  81833. x: t.value
  81834. } : 20 === t.code ? r.y = t.value : 30 === t.code ? r.z = t.value : r = t.value, t = a.next();
  81835. }
  81836. return t = a.next(), n;
  81837. },
  81838. v = function v() {
  81839. var e,
  81840. r = {};
  81841. for (t = a.next(); "EOF" !== t.value && !s(0, "ENDSEC");) s(0, "BLOCK") ? (N.debug("block {"), e = d(), N.debug("}"), x(e), e.name ? r[e.name] = e : N.error('block with handle "' + e.handle + '" is missing a name.')) : (S(t), t = a.next());
  81842. return r;
  81843. },
  81844. d = function d() {
  81845. var e = {};
  81846. for (t = a.next(); "EOF" !== t.value;) {
  81847. switch (t.code) {
  81848. case 1:
  81849. e.xrefPath = t.value, t = a.next();
  81850. break;
  81851. case 2:
  81852. e.name = t.value, t = a.next();
  81853. break;
  81854. case 3:
  81855. e.name2 = t.value, t = a.next();
  81856. break;
  81857. case 5:
  81858. e.handle = t.value, t = a.next();
  81859. break;
  81860. case 8:
  81861. e.layer = t.value, t = a.next();
  81862. break;
  81863. case 10:
  81864. e.position = y(), t = a.next();
  81865. break;
  81866. case 67:
  81867. e.paperSpace = !(!t.value || 1 != t.value), t = a.next();
  81868. break;
  81869. case 70:
  81870. 0 != t.value && (e.type = t.value), t = a.next();
  81871. break;
  81872. case 100:
  81873. t = a.next();
  81874. break;
  81875. case 330:
  81876. e.ownerHandle = t.value, t = a.next();
  81877. break;
  81878. case 0:
  81879. if ("ENDBLK" == t.value) break;
  81880. e.entities = k(!0);
  81881. break;
  81882. default:
  81883. S(t), t = a.next();
  81884. }
  81885. if (s(0, "ENDBLK")) {
  81886. t = a.next();
  81887. break;
  81888. }
  81889. }
  81890. return e;
  81891. },
  81892. b = function b() {
  81893. var e = {};
  81894. for (t = a.next(); "EOF" !== t.value && !s(0, "ENDSEC");) {
  81895. s(0, "TABLE") ? (t = a.next(), f[t.value] ? (N.debug(t.value + " Table {"), e[f[t.value].tableName] = p(), N.debug("}")) : N.debug("Unhandled Table " + t.value)) : t = a.next();
  81896. }
  81897. return t = a.next(), e;
  81898. };
  81899. var p = function p() {
  81900. var e,
  81901. r = f[t.value],
  81902. n = {},
  81903. o = 0;
  81904. for (t = a.next(); !s(0, "ENDTAB");) switch (t.code) {
  81905. case 5:
  81906. n.handle = t.value, t = a.next();
  81907. break;
  81908. case 330:
  81909. n.ownerHandle = t.value, t = a.next();
  81910. break;
  81911. case 100:
  81912. "AcDbSymbolTable" === t.value ? t = a.next() : (S(t), t = a.next());
  81913. break;
  81914. case 70:
  81915. o = t.value, t = a.next();
  81916. break;
  81917. case 0:
  81918. t.value === r.dxfSymbolName ? n[r.tableRecordsProperty] = r.parseTableRecords() : (S(t), t = a.next());
  81919. break;
  81920. default:
  81921. S(t), t = a.next();
  81922. }
  81923. var c = n[r.tableRecordsProperty];
  81924. return c && (c.constructor === Array ? e = c.length : "object" == typeof c && (e = Object.keys(c).length), o !== e && N.warn("Parsed " + e + " " + r.dxfSymbolName + "'s but expected " + o)), t = a.next(), n;
  81925. },
  81926. f = {
  81927. VPORT: {
  81928. tableRecordsProperty: "viewPorts",
  81929. tableName: "viewPort",
  81930. dxfSymbolName: "VPORT",
  81931. parseTableRecords: function parseTableRecords() {
  81932. var e = [],
  81933. r = {};
  81934. for (N.debug("ViewPort {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) {
  81935. case 2:
  81936. r.name = t.value, t = a.next();
  81937. break;
  81938. case 10:
  81939. r.lowerLeftCorner = y(), t = a.next();
  81940. break;
  81941. case 11:
  81942. r.upperRightCorner = y(), t = a.next();
  81943. break;
  81944. case 12:
  81945. r.center = y(), t = a.next();
  81946. break;
  81947. case 13:
  81948. r.snapBasePoint = y(), t = a.next();
  81949. break;
  81950. case 14:
  81951. r.snapSpacing = y(), t = a.next();
  81952. break;
  81953. case 15:
  81954. r.gridSpacing = y(), t = a.next();
  81955. break;
  81956. case 16:
  81957. r.viewDirectionFromTarget = y(), t = a.next();
  81958. break;
  81959. case 17:
  81960. r.viewTarget = y(), t = a.next();
  81961. break;
  81962. case 42:
  81963. r.lensLength = t.value, t = a.next();
  81964. break;
  81965. case 43:
  81966. r.frontClippingPlane = t.value, t = a.next();
  81967. break;
  81968. case 44:
  81969. r.backClippingPlane = t.value, t = a.next();
  81970. break;
  81971. case 45:
  81972. r.viewHeight = t.value, t = a.next();
  81973. break;
  81974. case 50:
  81975. r.snapRotationAngle = t.value, t = a.next();
  81976. break;
  81977. case 51:
  81978. r.viewTwistAngle = t.value, t = a.next();
  81979. break;
  81980. case 79:
  81981. r.orthographicType = t.value, t = a.next();
  81982. break;
  81983. case 110:
  81984. r.ucsOrigin = y(), t = a.next();
  81985. break;
  81986. case 111:
  81987. r.ucsXAxis = y(), t = a.next();
  81988. break;
  81989. case 112:
  81990. r.ucsYAxis = y(), t = a.next();
  81991. break;
  81992. case 110:
  81993. r.ucsOrigin = y(), t = a.next();
  81994. break;
  81995. case 281:
  81996. r.renderMode = t.value, t = a.next();
  81997. break;
  81998. case 281:
  81999. r.defaultLightingType = t.value, t = a.next();
  82000. break;
  82001. case 292:
  82002. r.defaultLightingOn = t.value, t = a.next();
  82003. break;
  82004. case 330:
  82005. r.ownerHandle = t.value, t = a.next();
  82006. break;
  82007. case 63:
  82008. case 421:
  82009. case 431:
  82010. r.ambientColor = t.value, t = a.next();
  82011. break;
  82012. case 0:
  82013. "VPORT" === t.value && (N.debug("}"), e.push(r), N.debug("ViewPort {"), r = {}, t = a.next());
  82014. break;
  82015. default:
  82016. S(t), t = a.next();
  82017. }
  82018. return N.debug("}"), e.push(r), e;
  82019. }
  82020. },
  82021. LTYPE: {
  82022. tableRecordsProperty: "lineTypes",
  82023. tableName: "lineType",
  82024. dxfSymbolName: "LTYPE",
  82025. parseTableRecords: function parseTableRecords() {
  82026. var e,
  82027. r,
  82028. n = {},
  82029. o = {};
  82030. for (N.debug("LType {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) {
  82031. case 2:
  82032. o.name = t.value, e = t.value, t = a.next();
  82033. break;
  82034. case 3:
  82035. o.description = t.value, t = a.next();
  82036. break;
  82037. case 73:
  82038. (r = t.value) > 0 && (o.pattern = []), t = a.next();
  82039. break;
  82040. case 40:
  82041. o.patternLength = t.value, t = a.next();
  82042. break;
  82043. case 49:
  82044. o.pattern.push(t.value), t = a.next();
  82045. break;
  82046. case 0:
  82047. N.debug("}"), r > 0 && r !== o.pattern.length && N.warn("lengths do not match on LTYPE pattern"), n[e] = o, o = {}, N.debug("LType {"), t = a.next();
  82048. break;
  82049. default:
  82050. t = a.next();
  82051. }
  82052. return N.debug("}"), n[e] = o, n;
  82053. }
  82054. },
  82055. LAYER: {
  82056. tableRecordsProperty: "layers",
  82057. tableName: "layer",
  82058. dxfSymbolName: "LAYER",
  82059. parseTableRecords: function parseTableRecords() {
  82060. var e,
  82061. r,
  82062. n = {},
  82063. c = {};
  82064. for (N.debug("Layer {"), t = a.next(); !s(0, "ENDTAB");) switch (t.code) {
  82065. case 2:
  82066. c.name = t.value, e = t.value, t = a.next();
  82067. break;
  82068. case 62:
  82069. c.visible = t.value >= 0, c.colorIndex = Math.abs(t.value), c.color = (r = c.colorIndex, o[r]), t = a.next();
  82070. break;
  82071. case 70:
  82072. c.frozen = 0 != (1 & t.value) || 0 != (2 & t.value), t = a.next();
  82073. break;
  82074. case 0:
  82075. "LAYER" === t.value && (N.debug("}"), n[e] = c, N.debug("Layer {"), c = {}, e = void 0, t = a.next());
  82076. break;
  82077. default:
  82078. S(t), t = a.next();
  82079. }
  82080. return N.debug("}"), n[e] = c, n;
  82081. }
  82082. }
  82083. },
  82084. k = function k(e) {
  82085. var r = [],
  82086. n = e ? "ENDBLK" : "ENDSEC";
  82087. for (e || (t = a.next());;) if (0 === t.code) {
  82088. if (t.value === n) break;
  82089. var o,
  82090. c = u._entityHandlers[t.value];
  82091. if (null == c) {
  82092. N.warn("Unhandled entity " + t.value), t = a.next();
  82093. continue;
  82094. }
  82095. N.debug(t.value + " {"), o = c.parseEntity(a, t), t = a.lastReadGroup, N.debug("}"), x(o), r.push(o);
  82096. } else t = a.next();
  82097. return "ENDSEC" == n && (t = a.next()), r;
  82098. },
  82099. y = function y() {
  82100. var e = {},
  82101. r = t.code;
  82102. if (e.x = t.value, r += 10, (t = a.next()).code != r) throw new Error("Expected code for point value to be " + r + " but got " + t.code + ".");
  82103. return e.y = t.value, r += 10, (t = a.next()).code != r ? (a.rewind(), e) : (e.z = t.value, e);
  82104. },
  82105. x = function x(e) {
  82106. if (!e) throw new TypeError("entity cannot be undefined or null");
  82107. e.handle || (e.handle = c++);
  82108. };
  82109. return function () {
  82110. for (t = a.next(); !a.isEOF();) if (0 === t.code && "SECTION" === t.value) {
  82111. if (2 !== (t = a.next()).code) {
  82112. console.error("Unexpected code %s after 0:SECTION", L(t)), t = a.next();
  82113. continue;
  82114. }
  82115. "HEADER" === t.value ? (N.debug("> HEADER"), n.header = l(), N.debug("<")) : "BLOCKS" === t.value ? (N.debug("> BLOCKS"), n.blocks = v(), N.debug("<")) : "ENTITIES" === t.value ? (N.debug("> ENTITIES"), n.entities = k(!1), N.debug("<")) : "TABLES" === t.value ? (N.debug("> TABLES"), n.tables = b(), N.debug("<")) : "EOF" === t.value ? N.debug("EOF") : N.warn("Skipping section '%s'", t.value);
  82116. } else t = a.next();
  82117. }(), n;
  82118. };
  82119. a.default = T;
  82120. }]).default;
  82121. });
  82122. class DxfLoader extends EventDispatcher {
  82123. constructor() {
  82124. super();
  82125. this.parser = new Potree.DxfParser();
  82126. }
  82127. load(url, done) {
  82128. var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  82129. Potree.loadFile(url, {
  82130. returnText: true
  82131. }, data => {
  82132. var dxfJson = this.parser.parseSync(data);
  82133. console.log(dxfJson);
  82134. var model = this.createModel(dxfJson, options);
  82135. done(model);
  82136. });
  82137. }
  82138. createModel(data) {
  82139. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  82140. var root = new Object3D();
  82141. var i, entity, obj, min_x, min_y, min_z, max_x, max_y, max_z;
  82142. /* var dims = {
  82143. min: { x: false, y: false, z: false},
  82144. max: { x: false, y: false, z: false}
  82145. }; */
  82146. //let bound = THREE.Box3
  82147. for (i = 0; i < data.entities.length; i++) {
  82148. entity = data.entities[i];
  82149. obj = drawEntity(entity, data, options.unsupportTypes);
  82150. if (obj) {
  82151. var bbox = new Box3().setFromObject(obj);
  82152. /* if (bbox.min.x && ((dims.min.x === false) || (dims.min.x > bbox.min.x))) dims.min.x = bbox.min.x;
  82153. if (bbox.min.y && ((dims.min.y === false) || (dims.min.y > bbox.min.y))) dims.min.y = bbox.min.y;
  82154. if (bbox.min.z && ((dims.min.z === false) || (dims.min.z > bbox.min.z))) dims.min.z = bbox.min.z;
  82155. if (bbox.max.x && ((dims.max.x === false) || (dims.max.x < bbox.max.x))) dims.max.x = bbox.max.x;
  82156. if (bbox.max.y && ((dims.max.y === false) || (dims.max.y < bbox.max.y))) dims.max.y = bbox.max.y;
  82157. if (bbox.max.z && ((dims.max.z === false) || (dims.max.z < bbox.max.z))) dims.max.z = bbox.max.z; */
  82158. root.add(obj);
  82159. }
  82160. obj = null;
  82161. }
  82162. return root;
  82163. }
  82164. }
  82165. function drawEntity(entity, data, unsupportTypes, group) {
  82166. var mesh;
  82167. if (unsupportTypes && unsupportTypes.includes(entity.type)) {
  82168. console.warn('����һ��dxf������Ƶ�type��', entity.type);
  82169. return; //add �����Ƹ���
  82170. }
  82171. if (entity.type === 'CIRCLE' || entity.type === 'ARC') {
  82172. mesh = drawArc(entity, data, unsupportTypes, group);
  82173. } else if (entity.type === 'LWPOLYLINE' || entity.type === 'LINE' || entity.type === 'POLYLINE') {
  82174. mesh = drawLine(entity, data, unsupportTypes, group);
  82175. } else if (entity.type === 'TEXT') {
  82176. //"MTEXT" text: "{\fKaiTi|b0|i0|c134|p49;�������̨}"
  82177. mesh = drawText(entity, data, unsupportTypes, group);
  82178. } else if (entity.type === 'SOLID') {
  82179. mesh = drawSolid(entity, data);
  82180. } else if (entity.type === 'POINT') {
  82181. mesh = drawPoint(entity, data);
  82182. } else if (entity.type === 'INSERT') {
  82183. //Ƕ������group
  82184. mesh = drawBlock(entity, data, unsupportTypes, group);
  82185. } else if (entity.type === 'SPLINE') {
  82186. mesh = drawSpline(entity, data);
  82187. } else if (entity.type === 'MTEXT') {
  82188. mesh = drawMtext(entity, data, unsupportTypes, group);
  82189. } else if (entity.type === 'ELLIPSE') {
  82190. mesh = drawEllipse(entity, data, unsupportTypes, group);
  82191. } else if (entity.type === 'DIMENSION') {
  82192. var dimTypeEnum = entity.dimensionType & 7;
  82193. if (dimTypeEnum === 0) {
  82194. mesh = drawDimension(entity, data);
  82195. } else {
  82196. console.log("Unsupported Dimension type: " + dimTypeEnum);
  82197. }
  82198. } else {
  82199. console.log("Unsupported Entity Type: " + entity.type);
  82200. }
  82201. if (entity.type === 'LWPOLYLINE' || entity.type === 'LINE' || entity.type === 'POLYLINE') {
  82202. mesh = drawLine(entity, data);
  82203. }
  82204. /* if(entity.type === 'INSERT') {
  82205. mesh = drawBlock(entity, data); //group
  82206. } */
  82207. /*
  82208. �Ŷ���arc
  82209. �ƺ�ǽ�ڶ��Dz���insert���ͣ���������
  82210. */
  82211. mesh && (mesh.dxfInfo = entity); //add
  82212. return mesh;
  82213. }
  82214. function drawEllipse(entity, data) {
  82215. var color = getColor$2(entity, data);
  82216. var xrad = Math.sqrt(Math.pow(entity.majorAxisEndPoint.x, 2) + Math.pow(entity.majorAxisEndPoint.y, 2));
  82217. var yrad = xrad * entity.axisRatio;
  82218. var rotation = Math.atan2(entity.majorAxisEndPoint.y, entity.majorAxisEndPoint.x);
  82219. var curve = new EllipseCurve(entity.center.x, entity.center.y, xrad, yrad, entity.startAngle, entity.endAngle, false,
  82220. // Always counterclockwise
  82221. rotation);
  82222. var points = curve.getPoints(50);
  82223. var geometry = new BufferGeometry().setFromPoints(points);
  82224. var material = new LineBasicMaterial({
  82225. linewidth: 1,
  82226. color: color
  82227. });
  82228. // Create the final object to add to the scene
  82229. var ellipse = new Line(geometry, material);
  82230. return ellipse;
  82231. }
  82232. function drawMtext(entity, data) {
  82233. var color = getColor$2(entity, data);
  82234. //if (!font) { return console.log('font parameter not set. Ignoring text entity.')}
  82235. var geometry = new TextGeometry(entity.text, {
  82236. //font: font,
  82237. size: entity.height * (4 / 5),
  82238. height: 1
  82239. });
  82240. var material = new MeshBasicMaterial({
  82241. color: color
  82242. });
  82243. var text = new Mesh(geometry, material);
  82244. // Measure what we rendered.
  82245. var measure = new Box3();
  82246. measure.setFromObject(text);
  82247. var textWidth = measure.max.x - measure.min.x;
  82248. // If the text ends up being wider than the box, it's supposed
  82249. // to be multiline. Doing that in threeJS is overkill.
  82250. if (textWidth > entity.width) {
  82251. console.log("Can't render this multipline MTEXT entity, sorry.", entity);
  82252. return undefined;
  82253. }
  82254. text.position.z = 0;
  82255. switch (entity.attachmentPoint) {
  82256. case 1:
  82257. // Top Left
  82258. text.position.x = entity.position.x;
  82259. text.position.y = entity.position.y - entity.height;
  82260. break;
  82261. case 2:
  82262. // Top Center
  82263. text.position.x = entity.position.x - textWidth / 2;
  82264. text.position.y = entity.position.y - entity.height;
  82265. break;
  82266. case 3:
  82267. // Top Right
  82268. text.position.x = entity.position.x - textWidth;
  82269. text.position.y = entity.position.y - entity.height;
  82270. break;
  82271. case 4:
  82272. // Middle Left
  82273. text.position.x = entity.position.x;
  82274. text.position.y = entity.position.y - entity.height / 2;
  82275. break;
  82276. case 5:
  82277. // Middle Center
  82278. text.position.x = entity.position.x - textWidth / 2;
  82279. text.position.y = entity.position.y - entity.height / 2;
  82280. break;
  82281. case 6:
  82282. // Middle Right
  82283. text.position.x = entity.position.x - textWidth;
  82284. text.position.y = entity.position.y - entity.height / 2;
  82285. break;
  82286. case 7:
  82287. // Bottom Left
  82288. text.position.x = entity.position.x;
  82289. text.position.y = entity.position.y;
  82290. break;
  82291. case 8:
  82292. // Bottom Center
  82293. text.position.x = entity.position.x - textWidth / 2;
  82294. text.position.y = entity.position.y;
  82295. break;
  82296. case 9:
  82297. // Bottom Right
  82298. text.position.x = entity.position.x - textWidth;
  82299. text.position.y = entity.position.y;
  82300. break;
  82301. default:
  82302. return undefined;
  82303. }
  82304. ;
  82305. return text;
  82306. }
  82307. function drawSpline(entity, data) {
  82308. var color = getColor$2(entity, data);
  82309. var points = entity.controlPoints.map(function (vec) {
  82310. return new Vector2(vec.x, vec.y);
  82311. });
  82312. var interpolatedPoints = [];
  82313. var curve;
  82314. if (entity.degreeOfSplineCurve === 2 || entity.degreeOfSplineCurve === 3) {
  82315. for (var i = 0; i + 2 < points.length; i = i + 2) {
  82316. if (entity.degreeOfSplineCurve === 2) {
  82317. curve = new QuadraticBezierCurve(points[i], points[i + 1], points[i + 2]);
  82318. } else {
  82319. curve = new QuadraticBezierCurve3(points[i], points[i + 1], points[i + 2]);
  82320. }
  82321. interpolatedPoints.push.apply(interpolatedPoints, curve.getPoints(50));
  82322. }
  82323. } else {
  82324. curve = new SplineCurve(points);
  82325. interpolatedPoints = curve.getPoints(100);
  82326. }
  82327. var geometry = new BufferGeometry().setFromPoints(interpolatedPoints);
  82328. var material = new LineBasicMaterial({
  82329. linewidth: 1,
  82330. color: color
  82331. });
  82332. var splineObject = new Line(geometry, material);
  82333. return splineObject;
  82334. }
  82335. function drawLine(entity, data) {
  82336. var geometry = new Geometry(),
  82337. color = getColor$2(entity, data),
  82338. material,
  82339. lineType,
  82340. vertex,
  82341. startPoint,
  82342. endPoint,
  82343. bulgeGeometry,
  82344. bulge,
  82345. i,
  82346. line;
  82347. if (!entity.vertices) return console.log('entity missing vertices.');
  82348. // create geometry
  82349. for (i = 0; i < entity.vertices.length; i++) {
  82350. if (entity.vertices[i].bulge) {
  82351. bulge = entity.vertices[i].bulge;
  82352. startPoint = entity.vertices[i];
  82353. endPoint = i + 1 < entity.vertices.length ? entity.vertices[i + 1] : geometry.vertices[0];
  82354. bulgeGeometry = new THREEx.BulgeGeometry(startPoint, endPoint, bulge);
  82355. geometry.vertices.push.apply(geometry.vertices, bulgeGeometry.vertices);
  82356. } else {
  82357. vertex = entity.vertices[i];
  82358. geometry.vertices.push(new Vector3(vertex.x, vertex.y, 0));
  82359. }
  82360. }
  82361. if (entity.shape) geometry.vertices.push(geometry.vertices[0]);
  82362. // set material
  82363. if (entity.lineType) {
  82364. lineType = data.tables.lineType.lineTypes[entity.lineType];
  82365. }
  82366. if (lineType && lineType.pattern && lineType.pattern.length !== 0) {
  82367. material = new LineDashedMaterial({
  82368. color: color,
  82369. gapSize: 4,
  82370. dashSize: 4
  82371. });
  82372. } else {
  82373. material = new LineBasicMaterial({
  82374. linewidth: 1,
  82375. color: color
  82376. });
  82377. }
  82378. // if(lineType && lineType.pattern && lineType.pattern.length !== 0) {
  82379. // geometry.computeLineDistances();
  82380. // // Ugly hack to add diffuse to this. Maybe copy the uniforms object so we
  82381. // // don't add diffuse to a material.
  82382. // lineType.material.uniforms.diffuse = { type: 'c', value: new THREE.Color(color) };
  82383. // material = new THREE.ShaderMaterial({
  82384. // uniforms: lineType.material.uniforms,
  82385. // vertexShader: lineType.material.vertexShader,
  82386. // fragmentShader: lineType.material.fragmentShader
  82387. // });
  82388. // }else {
  82389. // material = new THREE.LineBasicMaterial({ linewidth: 1, color: color });
  82390. // }
  82391. line = new Line(geometry, material);
  82392. return line;
  82393. }
  82394. function drawArc(entity, data) {
  82395. var startAngle, endAngle;
  82396. if (entity.type === 'CIRCLE') {
  82397. startAngle = entity.startAngle || 0;
  82398. endAngle = startAngle + 2 * Math.PI;
  82399. } else {
  82400. startAngle = entity.startAngle;
  82401. endAngle = entity.endAngle;
  82402. }
  82403. var curve = new ArcCurve(0, 0, entity.radius, startAngle, endAngle);
  82404. var points = curve.getPoints(32);
  82405. var geometry = new BufferGeometry().setFromPoints(points);
  82406. var material = new LineBasicMaterial({
  82407. color: getColor$2(entity, data)
  82408. });
  82409. var arc = new Line(geometry, material);
  82410. arc.position.x = entity.center.x;
  82411. arc.position.y = entity.center.y;
  82412. arc.position.z = entity.center.z;
  82413. return arc;
  82414. }
  82415. function drawSolid(entity, data) {
  82416. var material,
  82417. mesh,
  82418. verts,
  82419. geometry = new Geometry();
  82420. verts = geometry.vertices;
  82421. verts.push(new Vector3(entity.points[0].x, entity.points[0].y, entity.points[0].z));
  82422. verts.push(new Vector3(entity.points[1].x, entity.points[1].y, entity.points[1].z));
  82423. verts.push(new Vector3(entity.points[2].x, entity.points[2].y, entity.points[2].z));
  82424. verts.push(new Vector3(entity.points[3].x, entity.points[3].y, entity.points[3].z));
  82425. // Calculate which direction the points are facing (clockwise or counter-clockwise)
  82426. var vector1 = new Vector3();
  82427. var vector2 = new Vector3();
  82428. vector1.subVectors(verts[1], verts[0]);
  82429. vector2.subVectors(verts[2], verts[0]);
  82430. vector1.cross(vector2);
  82431. // If z < 0 then we must draw these in reverse order
  82432. if (vector1.z < 0) {
  82433. geometry.faces.push(new Face3(2, 1, 0));
  82434. geometry.faces.push(new Face3(2, 3, 1));
  82435. } else {
  82436. geometry.faces.push(new Face3(0, 1, 2));
  82437. geometry.faces.push(new Face3(1, 3, 2));
  82438. }
  82439. material = new MeshBasicMaterial({
  82440. color: getColor$2(entity, data)
  82441. });
  82442. return new Mesh(geometry, material);
  82443. }
  82444. function drawText(entity, data) {
  82445. var geometry, material, text;
  82446. //����Ҫfont���ܻ�������
  82447. /* if(!font)
  82448. return console.warn('Text is not supported without a Three.js font loaded with THREE.FontLoader! Load a font of your choice and pass this into the constructor. See the sample for this repository or Three.js examples at http://threejs.org/examples/?q=text#webgl_geometry_text for more details.');
  82449. */
  82450. geometry = new TextGeometry(entity.text, {
  82451. /* font: font, */height: 0,
  82452. size: entity.textHeight || 12
  82453. });
  82454. if (entity.rotation) {
  82455. var zRotation = entity.rotation * Math.PI / 180;
  82456. geometry.rotateZ(zRotation);
  82457. }
  82458. material = new MeshBasicMaterial({
  82459. color: getColor$2(entity, data)
  82460. });
  82461. text = new Mesh(geometry, material);
  82462. text.position.x = entity.startPoint.x;
  82463. text.position.y = entity.startPoint.y;
  82464. text.position.z = entity.startPoint.z;
  82465. return text;
  82466. }
  82467. function drawPoint(entity, data) {
  82468. var geometry, material, point;
  82469. geometry = new Geometry();
  82470. geometry.vertices.push(new Vector3(entity.position.x, entity.position.y, entity.position.z));
  82471. // TODO: could be more efficient. PointCloud per layer?
  82472. var numPoints = 1;
  82473. var color = getColor$2(entity, data);
  82474. var colors = new Float32Array(numPoints * 3);
  82475. colors[0] = color.r;
  82476. colors[1] = color.g;
  82477. colors[2] = color.b;
  82478. geometry.colors = colors;
  82479. geometry.computeBoundingBox();
  82480. material = new PointsMaterial({
  82481. size: 0.05,
  82482. vertexColors: VertexColors
  82483. });
  82484. point = new Points(geometry, material);
  82485. //scene.add(point);
  82486. return point;
  82487. }
  82488. function drawDimension(entity, data, unsupportTypes, parentGroup) {
  82489. return drawBlock(entity, data, unsupportTypes, parentGroup, true);
  82490. //��
  82491. /* var block = data.blocks[entity.block];
  82492. if (!block || !block.entities) return null;
  82493. var group = new THREE.Object3D();
  82494. // if(entity.anchorPoint) {
  82495. // group.position.x = entity.anchorPoint.x;
  82496. // group.position.y = entity.anchorPoint.y;
  82497. // group.position.z = entity.anchorPoint.z;
  82498. // }
  82499. for(var i = 0; i < block.entities.length; i++) {
  82500. var childEntity = drawEntity(block.entities[i], data, group);
  82501. if(childEntity && !group.children.includes(childEntity)) group.add(childEntity);
  82502. }
  82503. return group; */
  82504. }
  82505. function drawBlock(entity, data, unsupportTypes, parentGroup, isDimension) {
  82506. var block = data.blocks[entity.name];
  82507. if (!block.entities) return null;
  82508. var group = new Object3D();
  82509. parentGroup && parentGroup.add(group); //��ǰ���� Ϊ�˻��matrixWorld
  82510. if (!isDimension) {
  82511. if (entity.position) {
  82512. group.position.x = entity.position.x;
  82513. group.position.y = entity.position.y;
  82514. group.position.z = entity.position.z;
  82515. }
  82516. if (entity.xScale) {
  82517. group.scale.x = entity.xScale;
  82518. }
  82519. if (entity.yScale) {
  82520. group.scale.y = entity.yScale;
  82521. }
  82522. if (entity.rotation) {
  82523. group.rotation.z = entity.rotation * Math.PI / 180;
  82524. }
  82525. //add: ���������еĻ������������Զ add zScale
  82526. var flag;
  82527. if (entity.zScale != void 0 && entity.extrusionDirection) {
  82528. //see (005.dxf�� others/01.dxf) extrusionDirection ={x:0,y:0,z:-1}
  82529. group.position.x *= Math.sign(entity.zScale);
  82530. group.scale.x *= Math.sign(entity.zScale);
  82531. group.rotation.z *= Math.sign(entity.zScale);
  82532. flag = 1;
  82533. //�����������extrusionDirection
  82534. }
  82535. } else {
  82536. /* if(entity.anchorPoint) {
  82537. group.position.x = entity.anchorPoint.x;
  82538. group.position.y = entity.anchorPoint.y;
  82539. group.position.z = entity.anchorPoint.z;
  82540. } */
  82541. }
  82542. //add:
  82543. group.updateMatrixWorld();
  82544. var visiEntities = block.entities.filter(e => e.visible !== false);
  82545. //console.log("block�Ŀɼ�children����"+block.entities.length)
  82546. for (var i = 0; i < visiEntities.length; i++) {
  82547. var childEntity = drawEntity(visiEntities[i], data, unsupportTypes, group);
  82548. if (childEntity && !group.children.includes(childEntity)) group.add(childEntity);
  82549. }
  82550. return group;
  82551. }
  82552. function getColor$2(entity, data) {
  82553. var color = 0x000000; //default
  82554. if (entity.color) color = entity.color;else if (data.tables && data.tables.layer && data.tables.layer.layers[entity.layer]) color = data.tables.layer.layers[entity.layer].color;
  82555. if (color == null || color === 0xffffff) {
  82556. color = 0x000000;
  82557. }
  82558. return color;
  82559. }
  82560. function createLineTypeShaders(data) {
  82561. var ltype, type;
  82562. if (!data.tables || !data.tables.lineType) return;
  82563. var ltypes = data.tables.lineType.lineTypes;
  82564. for (type in ltypes) {
  82565. ltype = ltypes[type];
  82566. if (!ltype.pattern) continue;
  82567. ltype.material = createDashedLineShader(ltype.pattern);
  82568. }
  82569. }
  82570. function createDashedLineShader(pattern) {
  82571. var i,
  82572. dashedLineShader = {},
  82573. totalLength = 0.0;
  82574. for (i = 0; i < pattern.length; i++) {
  82575. totalLength += Math.abs(pattern[i]);
  82576. }
  82577. dashedLineShader.uniforms = UniformsUtils.merge([UniformsLib['common'], UniformsLib['fog'], {
  82578. 'pattern': {
  82579. type: 'fv1',
  82580. value: pattern
  82581. },
  82582. 'patternLength': {
  82583. type: 'f',
  82584. value: totalLength
  82585. }
  82586. }]);
  82587. dashedLineShader.vertexShader = ['attribute float lineDistance;', 'varying float vLineDistance;', ShaderChunk['color_pars_vertex'], 'void main() {', ShaderChunk['color_vertex'], 'vLineDistance = lineDistance;', 'gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );', '}'].join('\n');
  82588. dashedLineShader.fragmentShader = ['uniform vec3 diffuse;', 'uniform float opacity;', 'uniform float pattern[' + pattern.length + '];', 'uniform float patternLength;', 'varying float vLineDistance;', ShaderChunk['color_pars_fragment'], ShaderChunk['fog_pars_fragment'], 'void main() {', 'float pos = mod(vLineDistance, patternLength);', 'for ( int i = 0; i < ' + pattern.length + '; i++ ) {', 'pos = pos - abs(pattern[i]);', 'if( pos < 0.0 ) {', 'if( pattern[i] > 0.0 ) {', 'gl_FragColor = vec4(1.0, 0.0, 0.0, opacity );', 'break;', '}', 'discard;', '}', '}', ShaderChunk['color_fragment'], ShaderChunk['fog_fragment'], '}'].join('\n');
  82589. return dashedLineShader;
  82590. }
  82591. function findExtents(scene) {
  82592. for (var child of scene.children) {
  82593. var minX, maxX, minY, maxY;
  82594. if (child.position) {
  82595. minX = Math.min(child.position.x, minX);
  82596. minY = Math.min(child.position.y, minY);
  82597. maxX = Math.max(child.position.x, maxX);
  82598. maxY = Math.max(child.position.y, maxY);
  82599. }
  82600. }
  82601. return {
  82602. min: {
  82603. x: minX,
  82604. y: minY
  82605. },
  82606. max: {
  82607. x: maxX,
  82608. y: maxY
  82609. }
  82610. };
  82611. }
  82612. // Three.js extension functions. Webpack doesn't seem to like it if we modify the THREE object directly.
  82613. var THREEx = {
  82614. Math: {}
  82615. };
  82616. /**
  82617. * Returns the angle in radians of the vector (p1,p2). In other words, imagine
  82618. * putting the base of the vector at coordinates (0,0) and finding the angle
  82619. * from vector (1,0) to (p1,p2).
  82620. * @param {Object} p1 start point of the vector
  82621. * @param {Object} p2 end point of the vector
  82622. * @return {Number} the angle
  82623. */
  82624. THREEx.Math.angle2 = function (p1, p2) {
  82625. var v1 = new Vector2(p1.x, p1.y);
  82626. var v2 = new Vector2(p2.x, p2.y);
  82627. v2.sub(v1); // sets v2 to be our chord
  82628. v2.normalize();
  82629. if (v2.y < 0) return -Math.acos(v2.x);
  82630. return Math.acos(v2.x);
  82631. };
  82632. THREEx.Math.polar = function (point, distance, angle) {
  82633. var result = {};
  82634. result.x = point.x + distance * Math.cos(angle);
  82635. result.y = point.y + distance * Math.sin(angle);
  82636. return result;
  82637. };
  82638. /**
  82639. * Calculates points for a curve between two points
  82640. * @param startPoint - the starting point of the curve
  82641. * @param endPoint - the ending point of the curve
  82642. * @param bulge - a value indicating how much to curve
  82643. * @param segments - number of segments between the two given points
  82644. */
  82645. THREEx.BulgeGeometry = function (startPoint, endPoint, bulge, segments) {
  82646. var vertex, i, center, p0, p1, angle, radius, startAngle, thetaAngle;
  82647. Geometry.call(this);
  82648. this.startPoint = p0 = startPoint ? new Vector2(startPoint.x, startPoint.y) : new Vector2(0, 0);
  82649. this.endPoint = p1 = endPoint ? new Vector2(endPoint.x, endPoint.y) : new Vector2(1, 0);
  82650. this.bulge = bulge = bulge || 1;
  82651. angle = 4 * Math.atan(bulge);
  82652. radius = p0.distanceTo(p1) / 2 / Math.sin(angle / 2);
  82653. center = THREEx.Math.polar(startPoint, radius, THREEx.Math.angle2(p0, p1) + (Math.PI / 2 - angle / 2));
  82654. this.segments = segments = segments || Math.max(Math.abs(Math.ceil(angle / (Math.PI / 18))), 6); // By default want a segment roughly every 10 degrees
  82655. startAngle = THREEx.Math.angle2(center, p0);
  82656. thetaAngle = angle / segments;
  82657. this.vertices.push(new Vector3(p0.x, p0.y, 0));
  82658. for (i = 1; i <= segments - 1; i++) {
  82659. vertex = THREEx.Math.polar(center, Math.abs(radius), startAngle + thetaAngle * i);
  82660. this.vertices.push(new Vector3(vertex.x, vertex.y, 0));
  82661. }
  82662. };
  82663. THREEx.BulgeGeometry.prototype = Object.create(Geometry.prototype);
  82664. /* -----note--------------
  82665. */
  82666. console.log(GAS);
  82667. console.log(GAS);
  82668. var manager = new LoadingManager();
  82669. var loaders = {};
  82670. var mapArea;
  82671. var shelterHistory = [];
  82672. Potree.isIframeChild = window.parent != window; //子页面
  82673. /* if(Potree.isIframeChild){
  82674. let rootWin = Common.getRootWindow()
  82675. rootWin && rootWin.viewer.dispatchEvent({type:'createIframe', window}) //给祖先页面发送信息,得不到可能跨域了或无viewer
  82676. } */
  82677. /* window.addEventListener('focus',()=>{
  82678. console.log('focus',window.winIndex)
  82679. })
  82680. window.addEventListener('blur',()=>{
  82681. console.log('blur',window.winIndex)
  82682. }) */
  82683. class Viewer$1 extends ViewerBase {
  82684. constructor(domElement, mapArea_) {
  82685. var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  82686. super(domElement, $.extend(args, {
  82687. name: 'mainViewer',
  82688. antialias: true,
  82689. preserveDrawingBuffer: true
  82690. }));
  82691. //注:viewer因为要分屏,尤其是四屏,preserveDrawingBuffer需要为true, 否则无法局部clear
  82692. window.viewer = this;
  82693. mapArea = mapArea_;
  82694. if (Potree.settings.editType == "pano" || Potree.settings.editType == "merge") {
  82695. this.modules = {
  82696. Alignment,
  82697. SiteModel,
  82698. volumeComputer: new VolumeComputer() //暂时
  82699. };
  82700. Potree.settings.useDepthTex = false;
  82701. if (Potree.settings.editType == "pano") {
  82702. this.modules.PanoEditor = PanoEditor$1;
  82703. } else if (Potree.settings.editType == "merge") {
  82704. this.modules.MergeEditor = MergeEditor;
  82705. this.modules.CamAniEditor = CamAniEditor;
  82706. }
  82707. } else {
  82708. this.modules = {
  82709. Clip,
  82710. Alignment,
  82711. SiteModel,
  82712. RouteGuider: new RouteGuider(),
  82713. clipping: new Clipping(),
  82714. ParticleEditor,
  82715. CamAniEditor,
  82716. volumeComputer: new VolumeComputer(),
  82717. MergeEditor
  82718. };
  82719. }
  82720. {
  82721. Potree.timeCollect = {
  82722. //median预置一个中等值,以防止cpu过低的设备首次卡顿
  82723. //depthSampler : {minCount:400, median: 1}, //旧的 实时从图片中获取色值的用时,但是现在直接从data中取
  82724. depthSamChangeImg: {
  82725. minCount: 200,
  82726. median: 25
  82727. } //换图的用时。 需要一开始就start
  82728. };
  82729. for (var i in Potree.timeCollect) {
  82730. Potree.timeCollect[i].measures = [];
  82731. Potree.timeCollect[i].sum = 0;
  82732. }
  82733. setTimeout(() => {
  82734. for (var _i in Potree.timeCollect) {
  82735. Potree.timeCollect[_i].start = true;
  82736. }
  82737. /* setTimeout(()=>{
  82738. console.log('timeCollect', Potree.timeCollect.depthSampler.median, Potree.timeCollect.depthSampler.ave, Potree.timeCollect.depthSampler.measures.length)
  82739. },10000) */
  82740. }, 2000);
  82741. }
  82742. this.navigateMode = 'free'; // 'panorama'; 'free'自由模式是只显示点云或者未进入到漫游点,
  82743. this.isEdit = true;
  82744. this.waitQueue = [];
  82745. this.unitConvert = new UoMService();
  82746. this.visible = true;
  82747. this.fpVisiDatasets = [];
  82748. this.atDatasets = [];
  82749. this.objs = new Object3D();
  82750. this.testMaxNodeCount = 0;
  82751. this.tiles3dVisiVCount = 0;
  82752. //this.lastPos = new THREE.Vector3(Infinity,Infinity,Infinity)
  82753. //-------------
  82754. var supportExtFragDepth = !!Potree.Features.EXT_DEPTH.isSupported(this.renderer.getContext()); //iphoneX居然不支持
  82755. //这意味着边缘增强和测量线遮挡失效
  82756. if (!supportExtFragDepth) console.error('ExtFragDepth unsupported! 边缘增强和测量线遮挡失效');
  82757. this.guiLoaded = false;
  82758. this.guiLoadTasks = [];
  82759. this.onVrListeners = [];
  82760. this.messages = [];
  82761. this.elMessages = $("\n\t\t<div id=\"message_listing\" \n\t\t\tstyle=\"position: absolute; z-index: 1000; left: 10px; bottom: 10px\">\n\t\t</div>");
  82762. $(domElement).append(this.elMessages);
  82763. this.fakeMeasure = {};
  82764. try {
  82765. if (!Potree.settings.isOfficial) {
  82766. // generate missing dom hierarchy
  82767. if ($(domElement).find('#potree_map').length === 0) {
  82768. var potreeMap = $("\n <div id=\"potree_map\" class=\"mapBox\" style=\"position: absolute; left: 50px; top: 50px; width: 400px; height: 400px; display: none\">\n <div id=\"potree_map_header\" style=\"position: absolute; width: 100%; height: 25px; top: 0px; background-color: rgba(0,0,0,0.5); z-index: 1000; border-top-left-radius: 3px; border-top-right-radius: 3px;\">\n </div>\n <div id=\"potree_map_content\" class=\"map\" style=\"position: absolute; z-index: 100; top: 25px; width: 100%; height: calc(100% - 25px); border: 2px solid rgba(0,0,0,0.5); box-sizing: border-box;\"></div>\n </div>\n ");
  82769. $(domElement).append(potreeMap);
  82770. }
  82771. if ($(domElement).find('#potree_description').length === 0) {
  82772. var potreeDescription = $("<div id=\"potree_description\" class=\"potree_info_text\"></div>");
  82773. $(domElement).append(potreeDescription);
  82774. }
  82775. if ($(domElement).find('#potree_annotations').length === 0) {
  82776. var potreeAnnotationContainer = $("\n <div id=\"potree_annotation_container\" \n style=\"position: absolute; z-index: 100000; width: 100%; height: 100%; pointer-events: none;\"></div>");
  82777. $(domElement).append(potreeAnnotationContainer);
  82778. }
  82779. if ($(domElement).find('#potree_quick_buttons').length === 0) {
  82780. var _potreeMap = $("\n <div id=\"potree_quick_buttons\" class=\"quick_buttons_container\" style=\"\">\n </div>\n ");
  82781. $(domElement).append(_potreeMap);
  82782. }
  82783. //add
  82784. {
  82785. $(domElement).append($("<div id='potree_labels'></div>"));
  82786. if (!mapArea && Potree.settings.editType != 'merge' /* || Potree.settings.showObjectsOnMap */) {
  82787. mapArea = $("<div id='mapGaode'></div>");
  82788. $(domElement).append(mapArea);
  82789. mapArea = mapArea[0];
  82790. }
  82791. }
  82792. /* let domRoot = this.renderer.domElement.parentElement;
  82793. let elAttach = $("<input type='button' value='test'></input>");
  82794. elAttach.css({
  82795. position : "absolute",
  82796. right : '10%',
  82797. bottom: '20px',
  82798. zIndex: "10000",
  82799. fontSize:'1em', color:"black",
  82800. background:'rgba(255,255,255,0.8)',
  82801. })
  82802. let state = false
  82803. elAttach.on("click", () => {
  82804. window.buttonFunction && window.buttonFunction()
  82805. });
  82806. domRoot.appendChild(elAttach[0]); */
  82807. }
  82808. this.tiles3dMemoryUsage = 0;
  82809. this.pointCloudLoadedCallback = args.onPointCloudLoaded || function () {};
  82810. // if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
  82811. // defaultSettings.navigation = "Orbit";
  82812. // }
  82813. this.server = null;
  82814. this.fov = 60;
  82815. this.isFlipYZ = false;
  82816. this.useDEMCollisions = false;
  82817. this.generateDEM = false;
  82818. this.minNodeSize = 30; //允许加载的node的最小可见像素宽度。越大越省性能
  82819. this.edlStrength = 1.0;
  82820. this.edlRadius = 1.4;
  82821. this.edlOpacity = 1.0;
  82822. this.useEDL = false;
  82823. this.description = "";
  82824. this.classifications = ClassificationScheme.DEFAULT;
  82825. this.moveSpeed = 1;
  82826. this.lengthUnit = LengthUnits.METER;
  82827. this.lengthUnitDisplay = LengthUnits.METER;
  82828. this.showBoundingBox = false;
  82829. this.showAnnotations = true;
  82830. this.freeze = false;
  82831. this.elevationGradientRepeat = ElevationGradientRepeat.CLAMP;
  82832. this.filterReturnNumberRange = [0, 7];
  82833. this.filterNumberOfReturnsRange = [0, 7];
  82834. this.filterGPSTimeRange = [-Infinity, Infinity];
  82835. this.filterPointSourceIDRange = [0, 65535];
  82836. this.potreeRenderer = null;
  82837. this.edlRenderer = null;
  82838. this.pRenderer = null;
  82839. this.scene = null;
  82840. this.sceneVR = null;
  82841. this.overlay = null;
  82842. this.overlayCamera = null;
  82843. this.inputHandler = null;
  82844. this.controls = null;
  82845. this.clippingTool = null;
  82846. this.transformationTool = null;
  82847. this.navigationCube = null;
  82848. this.compass = null;
  82849. this.skybox = null;
  82850. this.clock = new Clock();
  82851. this.background = null;
  82852. this.buffers = new Map();
  82853. if (args.noDragAndDrop) {} else {
  82854. this.initDragAndDrop();
  82855. }
  82856. if (typeof Stats !== "undefined") {
  82857. this.stats = new Stats();
  82858. this.stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom
  82859. document.body.appendChild(this.stats.dom);
  82860. }
  82861. {
  82862. this.overlay = new Scene();
  82863. this.overlayCamera = new OrthographicCamera(0, 1, 1, 0, -1000, 1000);
  82864. }
  82865. this.pRenderer = new Renderer$1(this.renderer);
  82866. {
  82867. var near = 2.5;
  82868. var far = 10.0;
  82869. var fov = 90;
  82870. this.shadowTestCam = new PerspectiveCamera(90, 1, near, far);
  82871. this.shadowTestCam.position.set(3.50, -2.80, 8.561);
  82872. this.shadowTestCam.lookAt(new Vector3(0, 0, 4.87));
  82873. }
  82874. var scene = new ExtendScene(this.renderer);
  82875. {
  82876. // create VR scene
  82877. this.sceneVR = new Scene();
  82878. // let texture = new THREE.TextureLoader().load(`${Potree.resourcePath}/images/vr_controller_help.jpg`);
  82879. // let plane = new THREE.PlaneBufferGeometry(1, 1, 1, 1);
  82880. // let infoMaterial = new THREE.MeshBasicMaterial({map: texture});
  82881. // let infoNode = new THREE.Mesh(plane, infoMaterial);
  82882. // infoNode.position.set(-0.5, 1, 0);
  82883. // infoNode.scale.set(0.4, 0.3, 1);
  82884. // infoNode.lookAt(0, 1, 0)
  82885. // this.sceneVR.add(infoNode);
  82886. // window.infoNode = infoNode;
  82887. }
  82888. this.setScene(scene);
  82889. //add: for 截图时抗锯齿
  82890. {
  82891. /* this.composer = new EffectComposer( this.renderer );
  82892. this.ssaaRenderPass = new SSAARenderPass(0x000000, 0);
  82893. this.composer.addPass( this.ssaaRenderPass );
  82894. */
  82895. //this.ssaaRenderPass.useCopy = true
  82896. //this.ssaaRenderPass.renderToScreen = true;
  82897. //this.ssaaRenderPass.needsSwap = false
  82898. //见 https://threejs.org/examples/?q=AA#webgl_postprocessing_fxaa 效果和SSAA差不多,都对透明不太友好。
  82899. /* let outlinePass = this.outlinePass = new OutlinePass( );
  82900. this.ssaaRenderPass.addPass(outlinePass)
  82901. */
  82902. //ssaa有透明度、发黑的问题所以不用了
  82903. //--------------------------
  82904. this.composer = new EffectComposer(this.renderer);
  82905. this.composer.scaleRatio = 4; //将底图和测量线绘制在一张高倍贴图上,for测量线不模糊
  82906. this.composer.readTarget = true; //把底图和测量线一起fxaa
  82907. /* const renderPass = new RenderPass();
  82908. //renderPass.clearColor = new THREE.Color( 0,0,0 );
  82909. //renderPass.clearAlpha = 0;
  82910. renderPass.clear = !this.composer.readTarget
  82911. this.composer.addPass( renderPass );
  82912. */
  82913. //for 融合页面
  82914. var outlinePass = this.outlinePass = new OutlinePass();
  82915. outlinePass.renderToScreen = true; //这样更流畅,不用ssaa了,缺点是outline有锯齿
  82916. outlinePass.enabled = false;
  82917. this.composer.addPass(outlinePass);
  82918. outlinePass.edgeStrength = 4;
  82919. outlinePass.edgeGlow = 0;
  82920. outlinePass.visibleEdgeColor = new Color("#09a1b3");
  82921. /* this.fxaaPass = new ShaderPass( FXAAShader );
  82922. this.fxaaPass.readTarget = true //add
  82923. this.fxaaPass.setSize = function(width, height){
  82924. this.material.uniforms[ 'resolution' ].value.x = 1 / ( width ) ;
  82925. this.material.uniforms[ 'resolution' ].value.y = 1 / ( height ) ;
  82926. }
  82927. this.fxaaPass.renderToScreen = true;
  82928. this.composer.addPass( this.fxaaPass ); */
  82929. //抗锯齿截图 效果时而好时而不好,文字比较模糊
  82930. //这两个暂时不能一起用。目前刚好不需要一起用
  82931. /* this.images360.fastTranMaskPass = new FastTranPass( this.renderer )
  82932. this.composer.addPass(this.images360.fastTranMaskPass)//add */
  82933. }
  82934. {
  82935. this.mainViewport = new Viewport(this.scene.view, this.scene.cameraP, {
  82936. left: 0,
  82937. bottom: 0,
  82938. width: 1,
  82939. height: 1,
  82940. name: 'MainView'
  82941. });
  82942. this.viewports = [this.mainViewport];
  82943. Potree.settings.showCompass && (this.compass = new Compass(Potree.settings.compassDom, this.mainViewport));
  82944. //this.axis = new AxisViewer(this.mainViewport, this.renderArea )
  82945. this.magnifier = new Magnifier(this);
  82946. this.reticule = new Reticule(this);
  82947. this.scene.scene.add(this.magnifier);
  82948. this.scene.scene.add(this.reticule);
  82949. if (Potree.settings.editType != "pano" && Potree.settings.editType != 'merge' /* || Potree.settings.showObjectsOnMap */) {
  82950. this.mapViewer = new MapViewer(mapArea /* $('#mapGaode')[0] */);
  82951. }
  82952. this.inputHandler = new InputHandler(this, this.scene.scene);
  82953. this.inputHandler.containsMouse = true; //初始化,使键盘事件在mainViewer有效
  82954. //this.inputHandler.setScene(this.scene);
  82955. //this.inputHandler.addInputListener(this);//add
  82956. this.clippingTool = new ClippingTool(this);
  82957. this.transformationTool = new TransformationTool(this);
  82958. this.navigationCube = new NavigationCube(this);
  82959. this.navigationCube.visible = false;
  82960. this.createControls();
  82961. this.clippingTool.setScene(this.scene);
  82962. var onPointcloudAdded = e => {
  82963. if (this.scene.pointclouds.length === 1) {
  82964. var speed = e.pointcloud.boundingBox.getSize(new Vector3()).length();
  82965. speed = speed / 2000;
  82966. this.setMoveSpeed(speed);
  82967. }
  82968. };
  82969. var onVolumeRemoved = e => {
  82970. this.inputHandler.deselect(e.volume);
  82971. };
  82972. this.addEventListener('scene_changed', e => {
  82973. this.inputHandler.setScene(e.scene);
  82974. this.clippingTool.setScene(this.scene);
  82975. if (!e.scene.hasEventListener("pointcloud_added", onPointcloudAdded)) {
  82976. e.scene.addEventListener("pointcloud_added", onPointcloudAdded);
  82977. }
  82978. if (!e.scene.hasEventListener("volume_removed", onPointcloudAdded)) {
  82979. e.scene.addEventListener("volume_removed", onVolumeRemoved);
  82980. }
  82981. });
  82982. this.scene.addEventListener("volume_removed", onVolumeRemoved);
  82983. this.scene.addEventListener('pointcloud_added', onPointcloudAdded);
  82984. }
  82985. {
  82986. // set defaults
  82987. this.setFOV(60);
  82988. this.setEDLEnabled(false);
  82989. this.setEDLRadius(3);
  82990. this.setEDLStrength(0.01);
  82991. this.setEDLOpacity(1.0);
  82992. this.setPointBudget(1 * 1000 * 1000);
  82993. this.setShowBoundingBox(false);
  82994. this.setFreeze(false);
  82995. this.setControls(this.fpControls /* orbitControls */);
  82996. this.setBackground(new Color(Potree.config.background), 1 /* 'gradient' */);
  82997. this.scaleFactor = 1;
  82998. this.loadSettingsFromURL();
  82999. }
  83000. // start rendering!
  83001. //if(args.useDefaultRenderLoop === undefined || args.useDefaultRenderLoop === true){
  83002. //requestAnimationFrame(this.loop.bind(this));
  83003. //}
  83004. this.renderer.setAnimationLoop(this.loop.bind(this));
  83005. this.loadGUI = this.loadGUI.bind(this);
  83006. this.annotationTool = new AnnotationTool(this);
  83007. this.measuringTool = new MeasuringTool(this);
  83008. //this.profileTool = new ProfileTool(this);
  83009. this.volumeTool = new VolumeTool(this);
  83010. this.tagTool = new TagTool(this);
  83011. //-----------
  83012. CursorDeal.init(this, this.mapViewer ? [this, this.mapViewer] : [this]); //ADD
  83013. if (Potree.settings.editType == "pano") {
  83014. this.modules.PanoEditor.init();
  83015. } else if (Potree.settings.editType == "merge") {
  83016. this.modules.MergeEditor.init();
  83017. } else {
  83018. this.modules.SiteModel.init();
  83019. this.modules.ParticleEditor.init();
  83020. }
  83021. this.modules.Alignment.init();
  83022. this.images360 = new Images360(this);
  83023. this.scene.scene.add(this.objs);
  83024. loaders = {
  83025. objLoader: new OBJLoader(manager),
  83026. mtlLoader: new MTLLoader(manager),
  83027. glbLoader: new GLTFLoader(undefined, this.renderer, Potree.settings.libsUrl),
  83028. plyLoader: new PLYLoader(manager),
  83029. dxfLoader: new DxfLoader(),
  83030. shapeLoader: new Potree.ShapefileLoader()
  83031. };
  83032. //add test
  83033. /* const environment = new RoomEnvironment();
  83034. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  83035. this.scene.scene.environment = pmremGenerator.fromScene( environment ).texture;
  83036. */
  83037. //-----------
  83038. this.modules.volumeComputer && this.modules.volumeComputer.init();
  83039. } catch (e) {
  83040. this.onCrash(e);
  83041. }
  83042. //-----------------------add----------------------------------------------------
  83043. /* {
  83044. let ratio
  83045. this.addEventListener('resize',(e)=>{
  83046. if(ratio != e.deviceRatio){ //因为devicePixelRatio会影响到点云大小,所以改变时计算下点云大小
  83047. viewer.scene.pointclouds.forEach(p => {
  83048. p.changePointSize()
  83049. })
  83050. }
  83051. ratio = e.deviceRatio
  83052. })
  83053. } */
  83054. {
  83055. var pointDensity = '';
  83056. Object.defineProperty(Potree.settings, "pointDensity", {
  83057. get: function get() {
  83058. return pointDensity;
  83059. },
  83060. set: density => {
  83061. if (density) {
  83062. var config = Potree.config.pointDensity[density];
  83063. var pointBudget = config.pointBudget;
  83064. if (density == 'magnifier') {
  83065. //尽可能不变pointBudget,否则点云可能会闪烁,因点云被释放又加载,如SS-t-7DUfWAUZ3V
  83066. pointBudget = Math.max(Potree.pointBudget, Potree.config.pointDensity['magnifier'].pointBudget);
  83067. } else if (this.magnifier.visible) {
  83068. //放大镜打开时要保证最低点云数量(全景模式没点)
  83069. pointBudget = Math.max(pointBudget, Potree.config.pointDensity['magnifier'].pointBudget);
  83070. }
  83071. viewer.setMinNodeSize(config.minNodeSize || Potree.config.minNodeSize);
  83072. viewer.setPointBudget(pointBudget);
  83073. pointDensity = density;
  83074. this.setPointLevels();
  83075. this.dispatchEvent('pointDensityChanged');
  83076. }
  83077. }
  83078. });
  83079. var UserPointDensity = '';
  83080. Object.defineProperty(Potree.settings, "UserPointDensity", {
  83081. get: function get() {
  83082. return UserPointDensity;
  83083. },
  83084. set: density => {
  83085. if (UserPointDensity != density) {
  83086. if (Potree.settings.displayMode == 'showPointCloud' && this.viewports.length != 4) {
  83087. //漫游模式和四屏时都有自己的pointDensity
  83088. Potree.settings.pointDensity = density;
  83089. }
  83090. UserPointDensity = density;
  83091. this.dispatchEvent('UserPointDensityChanged');
  83092. }
  83093. }
  83094. });
  83095. }
  83096. {
  83097. var cameraFar = Potree.settings.cameraFar;
  83098. Object.defineProperty(Potree.settings, "cameraFar", {
  83099. get: function get() {
  83100. return cameraFar;
  83101. },
  83102. set: far => {
  83103. if (far != cameraFar) {
  83104. if (Potree.settings.displayMode != 'showPanos' && !this.fixCamFar) {
  83105. this.mainViewport.camera.far = far;
  83106. this.mainViewport.camera.updateProjectionMatrix();
  83107. }
  83108. cameraFar = far;
  83109. }
  83110. }
  83111. });
  83112. }
  83113. /* this.reticule.addEventListener('update',(e)=>{
  83114. this.needRender = true
  83115. if(this.mapViewer && this.mapViewer.attachedToViewer)this.mapViewer.needRender = true //分屏时mapViewer也有reticule
  83116. }) */
  83117. this.reticule.addEventListener('update', e => {
  83118. this.reticule.hoverViewport && (this.reticule.hoverViewport.needRender = true);
  83119. this.lazyRenderViewports();
  83120. if (this.mapViewer && this.mapViewer.attachedToViewer && (this.mapViewer.viewports[0].needRender || this.needRender)) this.mapViewer.needRender = true; //分屏时mapViewer也有reticule
  83121. });
  83122. this.addEventListener('pointcloud_changed', e => {
  83123. if (this.screenshoting) {
  83124. this.viewports.filter(e => !e.noPointcloud).forEach(e => e.needRender = true);
  83125. } else this.lazyRenderViewports();
  83126. });
  83127. this.addEventListener('allLoaded', () => {
  83128. setTimeout(this.testPointcloudsMaxLevel.bind(this), 1000); //延迟一丢丢,等画面出现
  83129. this.scene.pointclouds.forEach(pointcloud => {
  83130. pointcloud.addEventListener('isVisible', e => {
  83131. //是否显示该点的mesh(不显示也能走)
  83132. //console.log('pointcloud isVisible', this.id, e.visible)
  83133. if (e.reason != 'displayMode' && e.reason != 'overlinePass') {
  83134. this.updateModelBound('visibleChanged');
  83135. }
  83136. this.dispatchEvent('pointcloud_changed');
  83137. });
  83138. pointcloud.material.addEventListener('material_property_changed', () => {
  83139. this.dispatchEvent('pointcloud_changed');
  83140. });
  83141. });
  83142. window.addEventListener('unfocusPage', e => {
  83143. console.log('unfocusPage', document.title);
  83144. this.setDisplay(false);
  83145. });
  83146. window.addEventListener('focusPage', e => {
  83147. console.log('focusPage', document.title);
  83148. this.setDisplay(true);
  83149. });
  83150. });
  83151. if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') {
  83152. this.addEventListener('switchFloorplanSelect', e => {
  83153. //进入平面图设置后 切换选中的数据集
  83154. this.selectedFloorplan = e.pointcloud; //绝对显示
  83155. this.updateFpVisiDatasets();
  83156. var pointclouds;
  83157. if (e.pointcloud) {
  83158. pointclouds = [e.pointcloud];
  83159. } else if (this.fpVisiDatasets.length) {
  83160. pointclouds = this.fpVisiDatasets;
  83161. }
  83162. pointclouds && this.mapViewer.fitToDatasets(pointclouds);
  83163. });
  83164. this.modules.SiteModel.bus.addEventListener('FloorChange', e => {
  83165. this.updateFpVisiDatasets();
  83166. this.updatePanosVisibles(e.currentFloor); //问:编辑空间模型时,需不需要改为显示当前选择的楼层。因为若所在楼层和选中的不一致,修改选中楼层的轮廓却改不了marker显示很奇怪,尤其刚好在一个建筑内时。
  83167. });
  83168. this.mapViewer.mapLayer.addEventListener('floorplanLoaded', () => {
  83169. this.updateCadVisibles(this.fpVisiDatasets, true); //加载完成后重新更新下
  83170. });
  83171. /* this.modules.Clip.bus.addEventListener('updateSelectedDatasets',()=>{
  83172. this.updateFpVisiDatasets()
  83173. }) */
  83174. }
  83175. {
  83176. var updated, zoomLevel;
  83177. var update = e => {
  83178. if (e.type == 'updateModelBound' || e.viewport == this.mainViewport && (e.changeInfo.positionChanged || zoomLevel != this.images360.zoomLevel)) {
  83179. zoomLevel = this.images360.zoomLevel; //对updateMarkerVisibles有影响
  83180. //e.changeInfo.positionChanged && shelterHistory.clear() //清空
  83181. (e.type == 'updateModelBound' || e.changeInfo.positionChanged) && this.updateDatasetAt(); //更新所在数据集
  83182. if (Potree.settings.ifShowMarker && Potree.settings.editType != 'merge') {
  83183. Common.intervalTool.isWaiting('updateMarkerVisibles', () => {
  83184. if (!this.mainViewport.view.isFlying()) {
  83185. this.updateMarkerVisibles();
  83186. }
  83187. }, 500);
  83188. }
  83189. }
  83190. };
  83191. this.addEventListener('camera_changed', update);
  83192. this.addEventListener('updateModelBound', update);
  83193. this.addEventListener('showMarkerChanged', () => {
  83194. this.updatePanosVisibles(this.modules.SiteModel.currentFloor);
  83195. this.updateMarkerVisibles();
  83196. });
  83197. /* if(!Potree.Features.EXT_DEPTH.isSupported()){
  83198. this.images360.addEventListener('endChangeMode',(e)=>{
  83199. if(e.mode == 'showPanos'){
  83200. this.updateMarkerVisibles()
  83201. }
  83202. }) */
  83203. this.images360.addEventListener('getNeighbourAuto', e => {
  83204. if ( /* Potree.settings.displayMode == 'showPanos' && */e.panos.includes(this.images360.currentPano)) {
  83205. Common.intervalTool.isWaiting('updateMarkerVisibles', () => {
  83206. this.updateMarkerVisibles();
  83207. }, 500);
  83208. }
  83209. });
  83210. /* } */
  83211. }
  83212. {
  83213. var interval;
  83214. document.addEventListener('visibilitychange', e => {
  83215. var v = !document.hidden;
  83216. //console.warn('visibilitychange', v )
  83217. this.dispatchEvent({
  83218. type: 'pageVisible',
  83219. v
  83220. });
  83221. if (this.screenshoting && !v) {
  83222. //截图过程中离开页面需要照常loop。但是尽量别离开页面,效果只能达到90%
  83223. interval = setInterval(() => {
  83224. //console.log('force loop', Date.now())
  83225. if (this.screenshoting) {
  83226. //截图完成时如果还没回来就不loop
  83227. this.loop(Date.now());
  83228. }
  83229. }, 50); //实际>1000, 浏览器会放慢定时器,放慢多少不确定
  83230. } else if (v && interval) {
  83231. clearInterval(interval);
  83232. }
  83233. });
  83234. }
  83235. /* if(!Potree.isIframeChild){
  83236. window.winIndex = 0;
  83237. let index = 1;
  83238. this.addEventListener('createIframe',(e)=>{//创建了子页面
  83239. let child = e.window;
  83240. child.winIndex = index ++;
  83241. })
  83242. //不知道删除iframe时是否那些模型还在内存里,需要释放吗? 如果要需要加一个事件
  83243. } */
  83244. /* {
  83245. let setInteract = ()=>{
  83246. this.interacted = true //标记这一帧用户有操作屏幕
  83247. }
  83248. this.addEventListener('global_mousedown', setInteract)
  83249. this.addEventListener('global_touchmove', setInteract)
  83250. this.addEventListener('global_mousewheel', setInteract)
  83251. }
  83252. {//针对数据集偏离中心很远后产生的精度损失而抖动
  83253. this.addEventListener('camera_changed', e => {
  83254. if(e.viewport == this.mainViewport && (e.changeInfo.positionChanged)){
  83255. if(Potree.settings.editType != 'merge' && Potree.settings.editType != 'pano'){
  83256. if(!this.mainViewport.view.isFlying() ){
  83257. let pos = this.mainViewport.view.position.clone() // this.mainViewport.camera.getWorldPosition(new THREE.Vector3)
  83258. if(pos.lengthSq() > 25000000){
  83259. Common.intervalTool.isWaiting('moveWorldCenter', ()=>{
  83260. pos = this.mainViewport.view.position.clone()
  83261. this.mainViewport.view.translateWorld(-pos.x, -pos.y, -pos.z)
  83262. this.scene.scene.position.sub(pos)
  83263. console.log('变位置', pos)
  83264. this.scene.pointclouds.forEach(cloud=>{
  83265. Alignment.setMatrix(cloud)
  83266. })
  83267. },500)
  83268. }
  83269. }
  83270. }
  83271. }
  83272. })
  83273. }*/
  83274. }
  83275. lazyRenderViewports(updateCount) {
  83276. //本来要写this.needRender = true的, 但在分四个屏时防止太卡而排队render
  83277. var viewports = this.viewports;
  83278. if (viewports.length == 1 || this.needRender) {
  83279. return this.needRender = true;
  83280. }
  83281. var maxWaitTime = 200;
  83282. var now = Date.now();
  83283. var maxRenderCount = 1;
  83284. viewports.forEach(e => {
  83285. if (now - e.lastRenderTime > maxWaitTime) {
  83286. e.needRender = true;
  83287. }
  83288. });
  83289. var renderCount = viewports.filter(e => e.needRender).length;
  83290. //console.log('renderCount', renderCount)
  83291. var list = viewports.filter(e => !e.needRender).sort((a, b) => a.lastRenderTime - b.lastRenderTime); //没有准备render的,按上次渲染时间排序,作为候补
  83292. if (renderCount < maxRenderCount) {
  83293. //还有名额,补齐
  83294. list.slice(0, maxRenderCount - renderCount).forEach(e => {
  83295. e.needRender = true;
  83296. });
  83297. } else if (list[0] && now - list[0].lastRenderTime > maxWaitTime) {
  83298. //名额不足时,考虑候补队列第一个是否超时,超时的话也渲染
  83299. list[0].needRender = true;
  83300. }
  83301. }
  83302. ifPointBlockedByIntersect(point, panoId, soon) {
  83303. //点是否被遮挡
  83304. var ifShelter;
  83305. var now = Date.now();
  83306. var extraPanoId = panoId != void 0;
  83307. if (!this.shelterCount) return;
  83308. var history = shelterHistory.find(e => e.point.equals(point));
  83309. var cameraPos = this.mainViewport.view.position.clone();
  83310. if (panoId == void 0) {
  83311. if (this.images360.isAtPano(0.05)) {
  83312. panoId = this.images360.currentPano.id;
  83313. }
  83314. }
  83315. if (history) {
  83316. if (panoId != void 0) {
  83317. ifShelter = history.panos[panoId];
  83318. } else {
  83319. if (history.notAtPano.cameraPos && history.notAtPano.cameraPos.equals(cameraPos)) {
  83320. ifShelter = history.notAtPano.ifShelter;
  83321. }
  83322. }
  83323. var index = shelterHistory.indexOf(history); //先取出,稍后放回
  83324. shelterHistory.splice(index, 1);
  83325. } else {
  83326. //新增
  83327. history = {
  83328. point,
  83329. panos: {},
  83330. notAtPano: {}
  83331. };
  83332. var minCount = 100;
  83333. if (shelterHistory.length > minCount) {
  83334. //去除最早的
  83335. var old;
  83336. while (old = shelterHistory[0], now - old.lastTime > 1000) {
  83337. //因为不知热点个数,所以需要加上时间限制,超过时间才能删。
  83338. if (old == history || shelterHistory.length == minCount) break;
  83339. shelterHistory.splice(0, 1);
  83340. //console.log('delete')
  83341. }
  83342. }
  83343. }
  83344. if (ifShelter == void 0) {
  83345. delete history.waitCompute;
  83346. if (this.mainViewport.view.isFlying()) {
  83347. return useLastResult();
  83348. }
  83349. if (panoId != void 0) {
  83350. var pano = this.images360.getPano(panoId);
  83351. if ((soon || this.shelterCount.byTex < this.shelterCount.maxByTex) && pano.depthTex) {
  83352. ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({
  83353. point,
  83354. margin: Potree.config.shelterMargin,
  83355. useDepthTex: true,
  83356. pano,
  83357. viewport: this.mainViewport
  83358. });
  83359. history.panos[panoId] = ifShelter;
  83360. this.shelterCount.byTex++;
  83361. //console.log('computeByTex direct', panoId, point, ifShelter)
  83362. } else {
  83363. //console.log('延迟tex',panoId, point )
  83364. history.waitCompute = {
  83365. panoId,
  83366. forceGet: extraPanoId
  83367. };
  83368. return useLastResult();
  83369. }
  83370. } else {
  83371. if ( /* history.ifShelter == void 0 || */this.shelterCount.byCloud < this.shelterCount.maxByCloud) {
  83372. //弊端:第一个总是直接计算,后面的都是延后。但无法改进,因是一个个传进来的,无法预测。
  83373. ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({
  83374. point,
  83375. margin: Potree.config.shelterMargin,
  83376. pickWindowSize: 3
  83377. });
  83378. history.notAtPano = {
  83379. cameraPos,
  83380. ifShelter
  83381. };
  83382. this.shelterCount.byCloud++;
  83383. //console.log('computeByCloud direct', point.toArray())
  83384. } else {
  83385. //console.log('延迟cloud' )
  83386. history.waitCompute = {
  83387. cameraPos
  83388. };
  83389. return useLastResult();
  83390. }
  83391. }
  83392. }
  83393. history.ifShelter = ifShelter;
  83394. history.lastTime = now;
  83395. shelterHistory.push(history); //最新使用的保持在最后一个,使队列按照从旧到新排列
  83396. function useLastResult() {
  83397. //暂时先用上一次的值
  83398. shelterHistory.push(history);
  83399. history.lastTime = now;
  83400. return history.ifShelter;
  83401. }
  83402. return ifShelter;
  83403. }
  83404. computeShelter() {
  83405. //先算用深度图的,然后再点云;
  83406. //let depthTiming = Potree.timeCollect.depthSampler.median
  83407. var byTex = 0,
  83408. byCloud = 0;
  83409. var len = shelterHistory.length;
  83410. var waitCloud = [];
  83411. var maxTexCount = Common.getBestCount('shelterMaxDepthSample', 1, 50, 1, 13 /* ,true */);
  83412. for (var i = len - 1; i >= 0; i--) {
  83413. var history = shelterHistory[i];
  83414. if (history.waitCompute) {
  83415. if (history.waitCompute.panoId != void 0) {
  83416. if (!history.waitCompute.forceGet && (history.waitCompute.panoId != this.images360.currentPano.id || !this.images360.isAtPano(0.1))) {
  83417. delete history.waitCompute; //取消计算
  83418. } else {
  83419. if (this.images360.currentPano.depthTex) {
  83420. if (byTex >= maxTexCount) break;
  83421. byTex++;
  83422. var ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({
  83423. point: history.point,
  83424. margin: Potree.config.shelterMargin,
  83425. useDepthTex: true,
  83426. viewport: this.mainViewport
  83427. });
  83428. history.panos[this.images360.currentPano.id] = ifShelter;
  83429. history.ifShelter = ifShelter;
  83430. delete history.waitCompute;
  83431. //console.log('补1', history.point.toArray())
  83432. } else {
  83433. if (this.images360.currentPano.pointcloud.hasDepthTex) {
  83434. //先等待加载完深度图
  83435. } else {
  83436. waitCloud.push(history);
  83437. }
  83438. }
  83439. }
  83440. } else {
  83441. waitCloud.push(history);
  83442. }
  83443. }
  83444. }
  83445. var maxCloudCount;
  83446. if (byTex < maxTexCount && waitCloud.length) {
  83447. maxCloudCount = this.lastFrameChanged ? Common.getBestCount('shelterMaxCloud', 0, 2, 4, 8 /* ,true */) : 5;
  83448. var waitCloud2 = [];
  83449. if (maxCloudCount) {
  83450. for (var _i2 = 0; _i2 < waitCloud.length; _i2++) {
  83451. var _history = waitCloud[_i2];
  83452. if (_history.waitCompute.cameraPos) {
  83453. if (!viewer.mainViewport.view.position.equals(_history.waitCompute.cameraPos)) {
  83454. delete _history.waitCompute;
  83455. //console.log('delete history.waitCompute', history)
  83456. continue; //取消计算
  83457. } else {
  83458. waitCloud2.push(_history);
  83459. }
  83460. } else {
  83461. waitCloud2.push(_history);
  83462. }
  83463. }
  83464. var list = waitCloud2.map(e => e.point);
  83465. var result = Common.batchHandling.getSlice('shelterByCloud', list, {
  83466. maxUseCount: maxCloudCount,
  83467. useEquals: true,
  83468. stopWhenAllUsed: true
  83469. }); //iphonex稳定后大概在7-10。
  83470. //list.length>0 && console.log('list',list, maxCloudCount)
  83471. result.list.forEach(e => {
  83472. var history = waitCloud2.find(a => a.point.equals(e));
  83473. var ifShelter = !!viewer.inputHandler.ifBlockedByIntersect({
  83474. point: history.point,
  83475. margin: Potree.config.shelterMargin,
  83476. pickWindowSize: 3,
  83477. viewport: this.mainViewport
  83478. });
  83479. if (history.waitCompute.cameraPos) {
  83480. history.notAtPano = {
  83481. cameraPos: history.waitCompute.cameraPos,
  83482. ifShelter
  83483. };
  83484. } else {
  83485. history.panos[this.images360.currentPano.id] = ifShelter;
  83486. }
  83487. history.ifShelter = ifShelter;
  83488. byCloud++;
  83489. //console.log('补2', history.point.toArray())
  83490. delete history.waitCompute;
  83491. });
  83492. }
  83493. }
  83494. if (byTex || byCloud) {
  83495. //console.log('shelterComputed',byTex,byCloud, maxTexCount, maxCloudCount)
  83496. Common.intervalTool.isWaiting('shelterComputed', () => {
  83497. //console.log('shelterComputed update')
  83498. this.dispatchEvent('shelterComputed');
  83499. }, 340);
  83500. }
  83501. }
  83502. updateDatasetAt(force) {
  83503. //更新所在数据集
  83504. var fun = () => {
  83505. var currPos = viewer.mainViewport.view.position;
  83506. //if(force || !currPos.equals(this.lastPos)){
  83507. //this.lastPos.copy(currPos)
  83508. var at = this.scene.pointclouds.filter(e => (e.visible || e.unvisibleReasons && e.unvisibleReasons.length == 1 && e.unvisibleReasons[0].reason == 'displayMode') && e.ifContainsPoint(currPos));
  83509. if (Common.getDifferenceSet(at, this.atDatasets).length) {
  83510. //console.log('atDatasets', at)
  83511. this.atDatasets = at;
  83512. if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') {
  83513. this.updateFpVisiDatasets();
  83514. if (!viewer.modules.SiteModel.currentFloor) {
  83515. this.updatePanosVisibles(); //所在数据集的点位显示
  83516. }
  83517. }
  83518. this.dispatchEvent({
  83519. type: 'pointcloudAtChange',
  83520. pointclouds: at
  83521. });
  83522. }
  83523. force = false;
  83524. };
  83525. //}
  83526. if (force) fun();else Common.intervalTool.isWaiting('atWhichDataset', fun, 300);
  83527. }
  83528. updatePanosVisibles(currentFloor) {
  83529. //显示当前楼层的所有panos
  83530. if (!Potree.settings.ifShowMarker) return;
  83531. var inEntity = currentFloor;
  83532. //console.error('updatePanosVisibles', currentFloor)
  83533. viewer.images360.panos.forEach(pano => {
  83534. var visible = inEntity ? inEntity.panos.includes(pano) : this.atDatasets.some(e => e.panos.includes(pano));
  83535. Potree.Utils.updateVisible(pano, 'buildingChange', visible, 2);
  83536. });
  83537. this.dispatchEvent('content_changed');
  83538. } //注:非official的没有获取sitemodel的信息所以不执行楼层判断,marker显示不对是正常的
  83539. /* 2023.11.24 针对部分场景的楼层很矮,很容易就到楼层外了,且不能修改楼高。如SG-t-9NdCpxrUPLL#/,采取如下措施:
  83540. 1 如果不在任何一楼层,但在某个数据集中,就显示该数据集所有的marker
  83541. 2 如果当前楼层无,则显示上一次的currentFloor的marker
  83542. (目前先使用方案1)
  83543. */
  83544. updateMarkerVisibles() {
  83545. //限制显示的marker个数,因镜头内marker多的时候可能会卡
  83546. if (!Potree.settings.ifShowMarker) return;
  83547. var minRadius = 8 * this.images360.zoomLevel,
  83548. //当视线垂直于marker时的最小可见距离,此范围内可见的pano绝对可见
  83549. maxRadius = 50 * this.images360.zoomLevel,
  83550. //当视线垂直于marker时的最大可见距离,此范围外绝对不可见
  83551. hopeCount = browser.isMobile() ? 8 : 15; //期望达到的真实可见的marker数
  83552. var sheltered = pano => {
  83553. if ( /* Potree.settings.displayMode == 'showPanos' && !Potree.Features.EXT_DEPTH.isSupported() && */this.images360.isAtPano() && !this.mainViewport.view.isFlying()) {
  83554. return !this.images360.currentPano.neighbours.includes(pano) && this.images360.currentPano != pano; //起初因不支持EXT_DEPTH时无法用depthTex遮住marker, 后为了减少绘制,都判断
  83555. }
  83556. };
  83557. var panoMap = new Map(); //先记录想要设置为可见的
  83558. var set = () => {
  83559. //最后确定设置
  83560. var count = 0;
  83561. viewer.images360.panos.forEach(pano => {
  83562. var v = panoMap.get(pano).visible;
  83563. v && count++;
  83564. Potree.Utils.updateVisible(pano.marker, 'limitMarkerShow', v);
  83565. });
  83566. //console.log('updateMarkerVisibles marker显示个数', count)
  83567. this.dispatchEvent('content_changed');
  83568. };
  83569. var isWithinDis = (pano, maxDis) => {
  83570. //是否marker到相机的距离 没有超出可视距离。可视距离考虑上倾斜角,倾斜越大可视距离越短
  83571. var camPos = viewer.mainViewport.camera.position;
  83572. var o = panoMap.get(pano);
  83573. o.dis = o.dis || camPos.distanceTo(pano.marker.position);
  83574. o.sin = o.sin || Math.sqrt(Math.abs(camPos.z - pano.marker.position.z) / o.dis); //和地面夹角的sin。 按公式是不加Math.sqrt的,但是这样大马路上在贴近地面时算出的个数非常少,所以增大点……
  83575. return o.dis < maxDis * o.sin;
  83576. };
  83577. viewer.images360.panos.forEach(pano => {
  83578. //minRadius内的记录为可见
  83579. var o = {};
  83580. panoMap.set(pano, o);
  83581. if (pano.visible && !sheltered(pano) && isWithinDis(pano, minRadius)) {
  83582. o.visible = true;
  83583. }
  83584. });
  83585. //不超过hopeCount的话,可以直接确定设置
  83586. if (viewer.images360.panos.filter(pano => panoMap.get(pano).visible).length >= hopeCount) return set();
  83587. //距离超过maxRadius就绝对不可见
  83588. var insideOutCirle = viewer.images360.panos.filter(pano => pano.visible && !sheltered(pano) && isWithinDis(pano, maxRadius));
  83589. if (insideOutCirle.length <= hopeCount) {
  83590. insideOutCirle.forEach(pano => panoMap.get(pano).visible = true);
  83591. return set();
  83592. }
  83593. //数量超过hopeCount时,根据距离排序
  83594. insideOutCirle.sort((a, b) => {
  83595. return panoMap.get(a).dis - panoMap.get(b).dis;
  83596. });
  83597. var slice = insideOutCirle.slice(0, hopeCount);
  83598. slice.forEach(pano => panoMap.get(pano).visible = true);
  83599. set();
  83600. }
  83601. updateFpVisiDatasets() {
  83602. var Clip = this.modules.Clip;
  83603. var SiteModel = this.modules.SiteModel;
  83604. var Alignment = this.modules.Alignment;
  83605. var currentFloor = SiteModel.currentFloor;
  83606. /* if(Clip.editing){//下载页面已经改为和普通时一样,根据位置判断
  83607. this.updateCadVisibles(Clip.selectedDatasets)
  83608. }else */
  83609. if (this.selectedFloorplan) {
  83610. //平面图设置中 或 地理设置
  83611. var pointclouds = [this.selectedFloorplan];
  83612. this.updateCadVisibles(pointclouds);
  83613. } else if (SiteModel.editing || Alignment.editing) {
  83614. //只显示勾选的,也就是显示的点云的
  83615. var _pointclouds = this.scene.pointclouds.filter(p => Potree.Utils.getObjVisiByReason(p, 'datasetSelection'));
  83616. this.updateCadVisibles(_pointclouds);
  83617. //this.updatePanosVisibles(currentFloor/* , pointclouds */)
  83618. } else {
  83619. var _pointclouds2 = currentFloor ? this.findPointcloudsAtFloor(currentFloor) : [];
  83620. if (_pointclouds2.length == 0) {
  83621. if (this.focusDatasets) {
  83622. _pointclouds2 = this.focusDatasets;
  83623. }
  83624. }
  83625. if (_pointclouds2.length == 0) {
  83626. //如果当前不在任何楼层或楼层中无数据集,就用当前所在数据集
  83627. _pointclouds2 = this.atDatasets;
  83628. }
  83629. this.updateCadVisibles(_pointclouds2);
  83630. //this.updatePanosVisibles(currentFloor/* , pointclouds */)
  83631. }
  83632. }
  83633. /* findPointcloudsAtFloor(entity){//找当前楼层需要显示哪些数据集。
  83634. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  83635. //重叠体积>50% 或 包含>50%的漫游点
  83636. const ratio1 = 0.2, ratio2 = 0.5, ratio3 = 0.95
  83637. var lowScores = []
  83638. var pointclouds = viewer.scene.pointclouds.filter(e=>{
  83639. let score = 0
  83640. if(e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)){//条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  83641. return true
  83642. }
  83643. if(e.panos.length){//条件2
  83644. var insidePanos = e.panos.filter(a=>entity.ifContainsPoint(a.position));
  83645. let panoCountRatio = insidePanos.length / e.panos.length
  83646. if(panoCountRatio > ratio2)return true
  83647. score += panoCountRatio
  83648. }
  83649. //条件3
  83650. let volume = entity.intersectPointcloudVolume(e);
  83651. let volumeRatio = volume / entity.getVolume(true) //注:hole加入计算
  83652. if(volumeRatio > ratio3){ //ratio3要高一些,因为点云bounding可能很大,包含很多无点云的空间。即使整个数据集包含entity都不一定看起来在数据集中。(千万要防止两层楼都显示了)
  83653. return true
  83654. }else{
  83655. score += volumeRatio
  83656. }
  83657. lowScores.push({score, pointcloud:e})
  83658. })
  83659. if(pointclouds.length == 0){//从低分项挑一个出来。
  83660. lowScores.sort((a,b)=>{return a.score - b.score})
  83661. if(lowScores[0].score > 0.4){
  83662. pointclouds = [lowScores[0].pointcloud]
  83663. }
  83664. }
  83665. return pointclouds
  83666. } */
  83667. findPointcloudsAtFloor(entity) {
  83668. //找当前楼层需要显示哪些数据集。
  83669. //数据集的belongToEntity 在这个entity内(否则会出现点击数据集飞过去平面图却不显示)。or 如果数据集有漫游点的话,需要包含>20%的漫游点。 (防止重叠体积很大但其实一个漫游点都不包含)
  83670. //重叠体积>50% 或 包含>50%的漫游点
  83671. var ratio1 = 0.2,
  83672. ratio2 = 0.5,
  83673. ratio3 = 0.95;
  83674. var lowScores = [];
  83675. var pointclouds = viewer.scene.pointclouds.filter(e => {
  83676. var score = 0;
  83677. if (e.belongToEntity && (e.belongToEntity == entity || e.belongToEntity.buildParent == entity)) {
  83678. //条件1 若该数据集挂载到该楼层 或 该数据集挂载到的房间属于该楼层(这样能显示该层所有房间)
  83679. return true;
  83680. }
  83681. if (e.panos.length) {
  83682. //条件2
  83683. var insidePanos = e.panos.filter(a => entity.ifContainsPoint(a.position));
  83684. var panoCountRatio = insidePanos.length / e.panos.length;
  83685. if (panoCountRatio > ratio2) return true;
  83686. score += panoCountRatio * 2;
  83687. }
  83688. //条件3
  83689. var coverHeightRatio = entity.coverPointcloudHeight(e, true); //重叠高度占楼层高度的比率。
  83690. if (coverHeightRatio < 0.2) return;
  83691. var {
  83692. toEntity,
  83693. toPointcloud
  83694. } = entity.intersectPointcloudArea(e, true); //重叠面积占比
  83695. var coverAreaRatio = Math.max(toEntity, toPointcloud); //占数据集俯视面积的比率 和 占楼层的面积比率,挑一个大的。 (有的数据集被划分多个楼层,所以每层都应该显示该数据集的图。还有的数据集比较大,可能包含多个建筑,则看占楼层面积)
  83696. if (coverAreaRatio < 0.2) return;
  83697. score += coverAreaRatio * coverHeightRatio;
  83698. lowScores.push({
  83699. score,
  83700. pointcloud: e
  83701. });
  83702. });
  83703. /* if(pointclouds.length == 0){//从低分项挑一个出来。
  83704. lowScores.sort((a,b)=>{return a.score - b.score})
  83705. if(lowScores[0].score > 0.4){
  83706. pointclouds = [lowScores[0].pointcloud]
  83707. }
  83708. } */
  83709. lowScores.forEach(e => {
  83710. //一个楼层里可以包含许多个数据集 调试SG-t-ds27ym7xzjJ
  83711. if (e.score > 0.5) {
  83712. pointclouds.push(e.pointcloud);
  83713. }
  83714. });
  83715. return pointclouds;
  83716. }
  83717. updateCadVisibles(visiClouds, force) {
  83718. //console.log('visiClouds',visiClouds)
  83719. var oldVisi = this.fpVisiDatasets;
  83720. var visiClouds = this.fpVisiDatasets = visiClouds;
  83721. if (!force) {
  83722. var difference = Common.getDifferenceSet(oldVisi, visiClouds);
  83723. if (difference.length == 0) return;
  83724. }
  83725. //console.log('visiClouds',visiClouds.map(e=>e.name))
  83726. viewer.scene.pointclouds.forEach(pointcloud => {
  83727. var floorplan = viewer.mapViewer.mapLayer.getFloorplan(pointcloud.dataset_id);
  83728. var visi = visiClouds.includes(pointcloud);
  83729. if (floorplan) {
  83730. Potree.Utils.updateVisible(floorplan.objectGroup, 'buildingChange', visi);
  83731. } /* else if(!visi){
  83732. let changeVisi = (e)=>{
  83733. Potree.Utils.updateVisible(e.floorplan.objectGroup, 'buildingChange', this.fpVisiDatasets.includes(pointcloud))
  83734. viewer.mapViewer.mapLayer.removeEventListener('floorplanLoaded', changeVisi)
  83735. console.log('updateCadVisibles加载后更改显示',e)
  83736. }
  83737. viewer.mapViewer.mapLayer.addEventListener('floorplanLoaded', changeVisi)
  83738. } */
  83739. //已经添加了全局的 floorplanLoaded后会updateCadVisibles,这段就删了
  83740. });
  83741. viewer.mapViewer.mapLayer.needUpdate = true; //可能需要更新加载的level程度
  83742. viewer.mapViewer.needRender = true; //若上句不触发加载也要立即重新绘制
  83743. }
  83744. //促使点云加载出最高级别
  83745. testPointcloudsMaxLevel() {
  83746. var _this = this;
  83747. //所有点云都无需testMaxNodeLevel 就停止
  83748. var camera_changed,
  83749. count = 0;
  83750. var _test = function test() {
  83751. var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  83752. camera_changed = true;
  83753. var camera = e.camera || _this.scene.getActiveCamera();
  83754. Common.intervalTool.isWaiting('testPointcloudsMaxLevel', () => {
  83755. if (!camera_changed && count > 50 || Potree.settings.displayMode == 'showPanos' || _this.pauseTestMaxLevel) return; //只有当camera_changed后才继续循环, 除了最开始几次需要连续加载下
  83756. camera_changed = false;
  83757. count++;
  83758. //console.log('testPointcloudsMaxLevel中', camera.type /* count */)
  83759. var oldCount = _this.testMaxNodeCount;
  83760. var success = true;
  83761. viewer.scene.pointclouds.forEach(e => {
  83762. var wait = e.testMaxNodeLevel(camera);
  83763. if (wait) {
  83764. success = false;
  83765. }
  83766. });
  83767. /* if(oldCount<=Potree.config.testNodeCount1 && this.testMaxNodeCount>Potree.config.testNodeCount1 ){//差不多等当前所在数据集nodeMaxLevel加载出来
  83768. viewer.scene.pointclouds.forEach(e=>{e.changePointSize()}) //重新更新一下大小。因之前用的是nodeMaxLevelPredict (防止刚开始因nodeMaxLevel没涨完,导致过大的点云突然出现
  83769. } */
  83770. if (!success) return true; //没有全部加载完,继续循环
  83771. else {
  83772. _this.removeEventListener('camera_changed', _test);
  83773. console.log('testPointcloudsMaxLevel结束');
  83774. }
  83775. }, count < 10 ? 250 : 500);
  83776. };
  83777. this.addEventListener('camera_changed', _test);
  83778. _test();
  83779. /* 检验:
  83780. viewer.scene.pointclouds.sort((a,b)=>a.nodeMaxLevelPredict.min - b.nodeMaxLevelPredict.min).forEach(e=>console.log(e.nodeMaxLevel, e.nodeMaxLevelPredict.min))
  83781. */
  83782. }
  83783. setPointLevels() {
  83784. this.scene.pointclouds.forEach(e => {
  83785. e.setPointLevel();
  83786. });
  83787. }
  83788. onCrash(error) {
  83789. console.error(error);
  83790. $(this.renderArea).empty();
  83791. if ($(this.renderArea).find('#potree_failpage').length === 0) {
  83792. var elFailPage = $("\n\t\t\t<div id=\"#potree_failpage\" class=\"potree_failpage\"> \n\t\t\t\t\n\t\t\t\t<h1>Potree Encountered An Error </h1>\n\n\t\t\t\t<p>\n\t\t\t\tThis may happen if your browser or graphics card is not supported.\n\t\t\t\t<br>\n\t\t\t\tWe recommend to use \n\t\t\t\t<a href=\"https://www.google.com/chrome/browser\" target=\"_blank\" style=\"color:initial\">Chrome</a>\n\t\t\t\tor \n\t\t\t\t<a href=\"https://www.mozilla.org/\" target=\"_blank\">Firefox</a>.\n\t\t\t\t</p>\n\n\t\t\t\t<p>\n\t\t\t\tPlease also visit <a href=\"http://webglreport.com/\" target=\"_blank\">webglreport.com</a> and \n\t\t\t\tcheck whether your system supports WebGL.\n\t\t\t\t</p>\n\t\t\t\t<p>\n\t\t\t\tIf you are already using one of the recommended browsers and WebGL is enabled, \n\t\t\t\tconsider filing an issue report at <a href=\"https://github.com/potree/potree/issues\" target=\"_blank\">github</a>,<br>\n\t\t\t\tincluding your operating system, graphics card, browser and browser version, as well as the \n\t\t\t\terror message below.<br>\n\t\t\t\tPlease do not report errors on unsupported browsers.\n\t\t\t\t</p>\n\n\t\t\t\t<pre id=\"potree_error_console\" style=\"width: 100%; height: 100%\"></pre>\n\t\t\t\t\n\t\t\t</div>");
  83793. var elErrorMessage = elFailPage.find('#potree_error_console');
  83794. elErrorMessage.html(error.stack);
  83795. $(this.renderArea).append(elFailPage);
  83796. }
  83797. throw error;
  83798. }
  83799. // ------------------------------------------------------------------------------------
  83800. // Viewer API
  83801. // ------------------------------------------------------------------------------------
  83802. setScene(scene) {
  83803. if (scene === this.scene) {
  83804. return;
  83805. }
  83806. var oldScene = this.scene;
  83807. this.scene = scene;
  83808. this.dispatchEvent({
  83809. type: 'scene_changed',
  83810. oldScene: oldScene,
  83811. scene: scene
  83812. });
  83813. {
  83814. // Annotations
  83815. $('.annotation').detach();
  83816. // for(let annotation of this.scene.annotations){
  83817. // this.renderArea.appendChild(annotation.domElement[0]);
  83818. // }
  83819. this.scene.annotations.traverse(annotation => {
  83820. this.renderArea.appendChild(annotation.domElement[0]);
  83821. });
  83822. if (!this.onAnnotationAdded) {
  83823. this.onAnnotationAdded = e => {
  83824. // console.log("annotation added: " + e.annotation.title);
  83825. e.annotation.traverse(node => {
  83826. $("#potree_annotation_container").append(node.domElement);
  83827. //this.renderArea.appendChild(node.domElement[0]);
  83828. node.scene = this.scene;
  83829. });
  83830. };
  83831. }
  83832. if (oldScene) {
  83833. oldScene.annotations.removeEventListener('annotation_added', this.onAnnotationAdded);
  83834. }
  83835. this.scene.annotations.addEventListener('annotation_added', this.onAnnotationAdded);
  83836. }
  83837. }
  83838. setControls(controls /* , setSpeed */) {
  83839. if (controls !== this.controls) {
  83840. if (this.controls) {
  83841. this.controls.setEnable(false);
  83842. //this.inputHandler.removeInputListener(this.controls);
  83843. this.controls.moveSpeed = this.moveSpeed; //记录 (因为orbit的radius很大,转为firstPerson时要缩小)
  83844. }
  83845. this.controls = controls;
  83846. controls.moveSpeed && this.setMoveSpeed(controls.moveSpeed); //add
  83847. this.controls.setEnable(true);
  83848. //this.inputHandler.addInputListener(this.controls);
  83849. }
  83850. }
  83851. getControls() {
  83852. if (this.renderer.xr.isPresenting) {
  83853. return this.vrControls;
  83854. } else {
  83855. return this.controls;
  83856. }
  83857. }
  83858. getMinNodeSize() {
  83859. return this.minNodeSize;
  83860. }
  83861. setMinNodeSize(value) {
  83862. if (this.minNodeSize !== value) {
  83863. this.minNodeSize = value;
  83864. this.dispatchEvent({
  83865. 'type': 'minnodesize_changed',
  83866. 'viewer': this
  83867. });
  83868. }
  83869. }
  83870. getBackground() {
  83871. return this.background;
  83872. }
  83873. setBackground(bg, src) {
  83874. /* if (this.background === bg ) {
  83875. return;
  83876. } */
  83877. if (bg === "skybox") {
  83878. if (!src) src = Potree.resourcePath + '/textures/skybox/xingkong.jpg';
  83879. this.skybox = Utils.loadSkybox(src, this.skybox, () => {
  83880. this.background = bg;
  83881. });
  83882. } else {
  83883. this.background = bg;
  83884. }
  83885. this.backgroundOpacity = 1; //add
  83886. this.dispatchEvent({
  83887. 'type': 'background_changed',
  83888. 'viewer': this
  83889. });
  83890. }
  83891. setDescription(value) {
  83892. this.description = value;
  83893. $('#potree_description').html(value);
  83894. //$('#potree_description').text(value);
  83895. }
  83896. getDescription() {
  83897. return this.description;
  83898. }
  83899. setShowBoundingBox(value) {
  83900. if (this.showBoundingBox !== value) {
  83901. this.showBoundingBox = value;
  83902. this.dispatchEvent({
  83903. 'type': 'show_boundingbox_changed',
  83904. 'viewer': this
  83905. });
  83906. }
  83907. }
  83908. getShowBoundingBox() {
  83909. return this.showBoundingBox;
  83910. }
  83911. setMoveSpeed(value) {
  83912. if (this.getMoveSpeed() !== value) {
  83913. this.mainViewport.setMoveSpeed(value);
  83914. this.dispatchEvent({
  83915. 'type': 'move_speed_changed',
  83916. 'viewer': this,
  83917. 'speed': value
  83918. });
  83919. }
  83920. }
  83921. getMoveSpeed() {
  83922. return this.mainViewport.moveSpeed;
  83923. }
  83924. setWeightClassification(w) {
  83925. for (var i = 0; i < this.scene.pointclouds.length; i++) {
  83926. this.scene.pointclouds[i].material.weightClassification = w;
  83927. this.dispatchEvent({
  83928. 'type': 'attribute_weights_changed' + i,
  83929. 'viewer': this
  83930. });
  83931. }
  83932. }
  83933. setFreeze(value) {
  83934. value = Boolean(value);
  83935. if (this.freeze !== value) {
  83936. this.freeze = value;
  83937. this.dispatchEvent({
  83938. 'type': 'freeze_changed',
  83939. 'viewer': this
  83940. });
  83941. }
  83942. }
  83943. getFreeze() {
  83944. return this.freeze;
  83945. }
  83946. setElevationGradientRepeat(value) {
  83947. if (this.elevationGradientRepeat !== value) {
  83948. this.elevationGradientRepeat = value;
  83949. this.dispatchEvent({
  83950. type: "elevation_gradient_repeat_changed",
  83951. viewer: this
  83952. });
  83953. }
  83954. }
  83955. setPointBudget(value) {
  83956. //pointBudget: 每次刷新显示点数量的最大值。 缓存中的点数量也跟此有关,但大于这个数值。
  83957. if (Potree.pointBudget !== value && value) {
  83958. Potree.pointBudget = parseInt(value);
  83959. this.dispatchEvent({
  83960. 'type': 'point_budget_changed',
  83961. 'viewer': this
  83962. });
  83963. }
  83964. }
  83965. getPointBudget() {
  83966. return Potree.pointBudget;
  83967. }
  83968. setShowAnnotations(value) {
  83969. if (this.showAnnotations !== value) {
  83970. this.showAnnotations = value;
  83971. this.dispatchEvent({
  83972. 'type': 'show_annotations_changed',
  83973. 'viewer': this
  83974. });
  83975. }
  83976. }
  83977. getShowAnnotations() {
  83978. return this.showAnnotations;
  83979. }
  83980. setDEMCollisionsEnabled(value) {
  83981. if (this.useDEMCollisions !== value) {
  83982. this.useDEMCollisions = value;
  83983. this.dispatchEvent({
  83984. 'type': 'use_demcollisions_changed',
  83985. 'viewer': this
  83986. });
  83987. }
  83988. ;
  83989. }
  83990. getDEMCollisionsEnabled() {
  83991. return this.useDEMCollisions;
  83992. }
  83993. setEDLEnabled(value) {
  83994. value = Boolean(value) && Features.SHADER_EDL.isSupported();
  83995. if (this.useEDL !== value) {
  83996. this.useEDL = value;
  83997. this.dispatchEvent({
  83998. 'type': 'use_edl_changed',
  83999. 'viewer': this
  84000. });
  84001. this.dispatchEvent('pointcloud_changed');
  84002. }
  84003. }
  84004. getEDLEnabled() {
  84005. return this.useEDL;
  84006. }
  84007. setEDLRadius(value) {
  84008. if (this.edlRadius !== value) {
  84009. this.edlRadius = value;
  84010. this.dispatchEvent({
  84011. 'type': 'edl_radius_changed',
  84012. 'viewer': this
  84013. });
  84014. this.dispatchEvent('pointcloud_changed');
  84015. }
  84016. }
  84017. getEDLRadius() {
  84018. return this.edlRadius;
  84019. }
  84020. setEDLStrength(value) {
  84021. if (this.edlStrength !== value) {
  84022. this.edlStrength = value;
  84023. this.dispatchEvent({
  84024. 'type': 'edl_strength_changed',
  84025. 'viewer': this
  84026. });
  84027. this.dispatchEvent('pointcloud_changed');
  84028. }
  84029. }
  84030. getEDLStrength() {
  84031. return this.edlStrength;
  84032. }
  84033. setEDLOpacity(value) {
  84034. if (this.edlOpacity !== value) {
  84035. this.edlOpacity = value;
  84036. this.dispatchEvent({
  84037. 'type': 'edl_opacity_changed',
  84038. 'viewer': this
  84039. });
  84040. this.dispatchEvent('pointcloud_changed');
  84041. }
  84042. }
  84043. getEDLOpacity() {
  84044. return this.edlOpacity;
  84045. }
  84046. setFOV(value) {
  84047. if (this.fov !== value) {
  84048. var oldFov = this.fov;
  84049. this.fov = value;
  84050. this.scene.cameraP.fov = this.fov; //add
  84051. this.scene.cameraP.updateProjectionMatrix(); //add
  84052. this.dispatchEvent({
  84053. 'type': 'fov_changed',
  84054. 'viewer': this,
  84055. oldFov,
  84056. fov: this.fov
  84057. });
  84058. }
  84059. }
  84060. getFOV() {
  84061. return this.fov;
  84062. }
  84063. disableAnnotations() {
  84064. this.scene.annotations.traverse(annotation => {
  84065. annotation.domElement.css('pointer-events', 'none');
  84066. // return annotation.visible;
  84067. });
  84068. }
  84069. enableAnnotations() {
  84070. this.scene.annotations.traverse(annotation => {
  84071. annotation.domElement.css('pointer-events', 'auto');
  84072. // return annotation.visible;
  84073. });
  84074. }
  84075. setClassifications(classifications) {
  84076. this.classifications = classifications;
  84077. this.dispatchEvent({
  84078. 'type': 'classifications_changed',
  84079. 'viewer': this
  84080. });
  84081. }
  84082. setClassificationVisibility(key, value) {
  84083. if (!this.classifications[key]) {
  84084. this.classifications[key] = {
  84085. visible: value,
  84086. name: 'no name'
  84087. };
  84088. this.dispatchEvent({
  84089. 'type': 'classification_visibility_changed',
  84090. 'viewer': this
  84091. });
  84092. } else if (this.classifications[key].visible !== value) {
  84093. this.classifications[key].visible = value;
  84094. this.dispatchEvent({
  84095. 'type': 'classification_visibility_changed',
  84096. 'viewer': this
  84097. });
  84098. }
  84099. }
  84100. toggleAllClassificationsVisibility() {
  84101. var numVisible = 0;
  84102. var numItems = 0;
  84103. for (var key of Object.keys(this.classifications)) {
  84104. if (this.classifications[key].visible) {
  84105. numVisible++;
  84106. }
  84107. numItems++;
  84108. }
  84109. var visible = true;
  84110. if (numVisible === numItems) {
  84111. visible = false;
  84112. }
  84113. var somethingChanged = false;
  84114. for (var _key of Object.keys(this.classifications)) {
  84115. if (this.classifications[_key].visible !== visible) {
  84116. this.classifications[_key].visible = visible;
  84117. somethingChanged = true;
  84118. }
  84119. }
  84120. if (somethingChanged) {
  84121. this.dispatchEvent({
  84122. 'type': 'classification_visibility_changed',
  84123. 'viewer': this
  84124. });
  84125. }
  84126. }
  84127. setFilterReturnNumberRange(from, to) {
  84128. this.filterReturnNumberRange = [from, to];
  84129. this.dispatchEvent({
  84130. 'type': 'filter_return_number_range_changed',
  84131. 'viewer': this
  84132. });
  84133. }
  84134. setFilterNumberOfReturnsRange(from, to) {
  84135. this.filterNumberOfReturnsRange = [from, to];
  84136. this.dispatchEvent({
  84137. 'type': 'filter_number_of_returns_range_changed',
  84138. 'viewer': this
  84139. });
  84140. }
  84141. setFilterGPSTimeRange(from, to) {
  84142. this.filterGPSTimeRange = [from, to];
  84143. this.dispatchEvent({
  84144. 'type': 'filter_gps_time_range_changed',
  84145. 'viewer': this
  84146. });
  84147. }
  84148. setFilterPointSourceIDRange(from, to) {
  84149. this.filterPointSourceIDRange = [from, to];
  84150. this.dispatchEvent({
  84151. 'type': 'filter_point_source_id_range_changed',
  84152. 'viewer': this
  84153. });
  84154. }
  84155. setLengthUnit(value) {
  84156. switch (value) {
  84157. case 'm':
  84158. this.lengthUnit = LengthUnits.METER;
  84159. this.lengthUnitDisplay = LengthUnits.METER;
  84160. break;
  84161. case 'ft':
  84162. this.lengthUnit = LengthUnits.FEET;
  84163. this.lengthUnitDisplay = LengthUnits.FEET;
  84164. break;
  84165. case 'in':
  84166. this.lengthUnit = LengthUnits.INCH;
  84167. this.lengthUnitDisplay = LengthUnits.INCH;
  84168. break;
  84169. }
  84170. this.dispatchEvent({
  84171. 'type': 'length_unit_changed',
  84172. 'viewer': this,
  84173. value: value
  84174. });
  84175. }
  84176. setLengthUnitAndDisplayUnit(lengthUnitValue, lengthUnitDisplayValue) {
  84177. switch (lengthUnitValue) {
  84178. case 'm':
  84179. this.lengthUnit = LengthUnits.METER;
  84180. break;
  84181. case 'ft':
  84182. this.lengthUnit = LengthUnits.FEET;
  84183. break;
  84184. case 'in':
  84185. this.lengthUnit = LengthUnits.INCH;
  84186. break;
  84187. }
  84188. switch (lengthUnitDisplayValue) {
  84189. case 'm':
  84190. this.lengthUnitDisplay = LengthUnits.METER;
  84191. break;
  84192. case 'ft':
  84193. this.lengthUnitDisplay = LengthUnits.FEET;
  84194. break;
  84195. case 'in':
  84196. this.lengthUnitDisplay = LengthUnits.INCH;
  84197. break;
  84198. }
  84199. this.dispatchEvent({
  84200. 'type': 'length_unit_changed',
  84201. 'viewer': this,
  84202. value: lengthUnitValue
  84203. });
  84204. }
  84205. zoomTo(node, factor) {
  84206. var animationDuration = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
  84207. var view = this.mainViewport.view;
  84208. var camera = this.scene.cameraP.clone();
  84209. camera.rotation.copy(this.scene.cameraP.rotation);
  84210. camera.rotation.order = "ZXY";
  84211. camera.rotation.x = Math.PI / 2 + view.pitch;
  84212. camera.rotation.z = view.yaw;
  84213. camera.updateMatrix();
  84214. camera.updateMatrixWorld();
  84215. camera.zoomTo(node, factor);
  84216. var bs;
  84217. if (node.boundingSphere) {
  84218. bs = node.boundingSphere;
  84219. } else if (node.geometry && node.geometry.boundingSphere) {
  84220. bs = node.geometry.boundingSphere;
  84221. } else {
  84222. bs = node.boundingBox.getBoundingSphere(new Sphere());
  84223. }
  84224. bs = bs.clone().applyMatrix4(node.matrixWorld);
  84225. var startPosition = view.position.clone();
  84226. var endPosition = camera.position.clone();
  84227. var startTarget = view.getPivot();
  84228. var endTarget = bs.center;
  84229. var startRadius = view.radius;
  84230. var endRadius = endPosition.distanceTo(endTarget);
  84231. var easing = TWEEN.Easing.Quartic.Out;
  84232. {
  84233. // animate camera position
  84234. var pos = startPosition.clone();
  84235. var tween = new TWEEN.Tween(pos).to(endPosition, animationDuration);
  84236. tween.easing(easing);
  84237. tween.onUpdate(() => {
  84238. view.position.copy(pos);
  84239. });
  84240. tween.start();
  84241. }
  84242. {
  84243. // animate camera target
  84244. var target = startTarget.clone();
  84245. var _tween = new TWEEN.Tween(target).to(endTarget, animationDuration);
  84246. _tween.easing(easing);
  84247. _tween.onUpdate(() => {
  84248. view.lookAt(target);
  84249. });
  84250. _tween.onComplete(() => {
  84251. view.lookAt(target);
  84252. this.dispatchEvent({
  84253. type: 'focusing_finished',
  84254. target: this
  84255. });
  84256. });
  84257. this.dispatchEvent({
  84258. type: 'focusing_started',
  84259. target: this
  84260. });
  84261. _tween.start();
  84262. }
  84263. }
  84264. moveToGpsTimeVicinity(time) {
  84265. var result = Potree.Utils.findClosestGpsTime(time, viewer);
  84266. var box = result.node.pointcloud.deepestNodeAt(result.position).getBoundingBox();
  84267. var diameter = box.min.distanceTo(box.max);
  84268. var camera = this.scene.getActiveCamera();
  84269. var offset = camera.getWorldDirection(new Vector3()).multiplyScalar(diameter);
  84270. var newCamPos = result.position.clone().sub(offset);
  84271. this.scene.view.position.copy(newCamPos);
  84272. this.scene.view.lookAt(result.position);
  84273. }
  84274. showAbout() {
  84275. $(function () {
  84276. $('#about-panel').dialog();
  84277. });
  84278. }
  84279. getGpsTimeExtent() {
  84280. var range = [Infinity, -Infinity];
  84281. for (var pointcloud of this.scene.pointclouds) {
  84282. var attributes = pointcloud.pcoGeometry.pointAttributes.attributes;
  84283. var aGpsTime = attributes.find(a => a.name === "gps-time");
  84284. if (aGpsTime) {
  84285. range[0] = Math.min(range[0], aGpsTime.range[0]);
  84286. range[1] = Math.max(range[1], aGpsTime.range[1]);
  84287. }
  84288. }
  84289. return range;
  84290. }
  84291. fitToScreen() {
  84292. var factor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
  84293. var animationDuration = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  84294. var box = this.getBoundingBox(this.scene.pointclouds);
  84295. var node = new Object3D();
  84296. node.boundingBox = box;
  84297. this.zoomTo(node, factor, animationDuration);
  84298. this.controls.stop();
  84299. }
  84300. toggleNavigationCube() {
  84301. this.navigationCube.visible = !this.navigationCube.visible;
  84302. /* this.viewports.push({
  84303. name:'navigationCube',
  84304. left:0, bottom:0, width:0.2,
  84305. }) */
  84306. }
  84307. /* setView(pos, view) {
  84308. if(!pos) return;
  84309. switch(pos) {
  84310. case "F":
  84311. this.setFrontView(view);
  84312. break;
  84313. case "B":
  84314. this.setBackView(view);
  84315. break;
  84316. case "L":
  84317. this.setLeftView(view);
  84318. break;
  84319. case "R":
  84320. this.setRightView(view);
  84321. break;
  84322. case "U":
  84323. this.setTopView(view);
  84324. break;
  84325. case "D":
  84326. this.setBottomView(view);
  84327. break;
  84328. }
  84329. } */
  84330. setTopView(view) {
  84331. view = view || this.scene.view;
  84332. view.setCubeView("top");
  84333. this.fitToScreen();
  84334. }
  84335. setBottomView() {
  84336. this.scene.view.yaw = -Math.PI;
  84337. this.scene.view.pitch = Math.PI / 2;
  84338. this.fitToScreen();
  84339. }
  84340. setFrontView(view) {
  84341. view = view || this.scene.view;
  84342. view.yaw = 0;
  84343. view.pitch = 0;
  84344. this.fitToScreen();
  84345. }
  84346. setBackView(view) {
  84347. view = view || this.scene.view;
  84348. view.yaw = Math.PI;
  84349. view.pitch = 0;
  84350. this.fitToScreen();
  84351. }
  84352. setLeftView() {
  84353. this.scene.view.yaw = -Math.PI / 2;
  84354. this.scene.view.pitch = 0;
  84355. this.fitToScreen();
  84356. }
  84357. setRightView() {
  84358. this.scene.view.yaw = Math.PI / 2;
  84359. this.scene.view.pitch = 0;
  84360. this.fitToScreen();
  84361. }
  84362. flipYZ() {
  84363. this.isFlipYZ = !this.isFlipYZ;
  84364. // TODO flipyz
  84365. console.log('TODO');
  84366. }
  84367. setCameraMode(mode) {
  84368. this.scene.cameraMode = mode;
  84369. viewer.mainViewport.camera = mode == CameraMode.PERSPECTIVE ? this.scene.cameraP : this.scene.cameraO; //改
  84370. for (var pointcloud of this.scene.pointclouds) {
  84371. pointcloud.material.useOrthographicCamera = mode == CameraMode.ORTHOGRAPHIC;
  84372. }
  84373. }
  84374. getProjection() {
  84375. var pointcloud = this.scene.pointclouds[0];
  84376. if (pointcloud) {
  84377. return pointcloud.projection;
  84378. } else {
  84379. return null;
  84380. }
  84381. }
  84382. loadProject(url, done) {
  84383. return _asyncToGenerator(function* () {
  84384. var response = yield fetch(url);
  84385. if (response.ok) {
  84386. var text = yield response.text();
  84387. var json = JSON5.parse(text);
  84388. // const json = JSON.parse(text);
  84389. if (json.type === "Potree") {
  84390. Potree.loadProject(viewer, json, done);
  84391. }
  84392. } else {
  84393. console.warn("未能加载:" + url);
  84394. }
  84395. })();
  84396. }
  84397. saveProject() {
  84398. return Potree.saveProject(this);
  84399. }
  84400. loadSettingsFromURL() {
  84401. if (Utils.getParameterByName("pointSize")) {
  84402. this.setPointSize(parseFloat(Utils.getParameterByName("pointSize")));
  84403. }
  84404. if (Utils.getParameterByName("FOV")) {
  84405. this.setFOV(parseFloat(Utils.getParameterByName("FOV")));
  84406. }
  84407. if (Utils.getParameterByName("opacity")) {
  84408. this.setOpacity(parseFloat(Utils.getParameterByName("opacity")));
  84409. }
  84410. if (Utils.getParameterByName("edlEnabled")) {
  84411. var enabled = Utils.getParameterByName("edlEnabled") === "true";
  84412. this.setEDLEnabled(enabled);
  84413. }
  84414. if (Utils.getParameterByName('edlRadius')) {
  84415. this.setEDLRadius(parseFloat(Utils.getParameterByName('edlRadius')));
  84416. }
  84417. if (Utils.getParameterByName('edlStrength')) {
  84418. this.setEDLStrength(parseFloat(Utils.getParameterByName('edlStrength')));
  84419. }
  84420. if (Utils.getParameterByName('pointBudget')) {
  84421. this.setPointBudget(parseFloat(Utils.getParameterByName('pointBudget')));
  84422. }
  84423. if (Utils.getParameterByName('showBoundingBox')) {
  84424. var _enabled = Utils.getParameterByName('showBoundingBox') === 'true';
  84425. if (_enabled) {
  84426. this.setShowBoundingBox(true);
  84427. } else {
  84428. this.setShowBoundingBox(false);
  84429. }
  84430. }
  84431. if (Utils.getParameterByName('material')) {
  84432. var material = Utils.getParameterByName('material');
  84433. this.setMaterial(material);
  84434. }
  84435. if (Utils.getParameterByName('pointSizing')) {
  84436. var sizing = Utils.getParameterByName('pointSizing');
  84437. this.setPointSizing(sizing);
  84438. }
  84439. if (Utils.getParameterByName('quality')) {
  84440. var quality = Utils.getParameterByName('quality');
  84441. this.setQuality(quality);
  84442. }
  84443. if (Utils.getParameterByName('position')) {
  84444. var value = Utils.getParameterByName('position');
  84445. value = value.replace('[', '').replace(']', '');
  84446. var tokens = value.split(';');
  84447. var x = parseFloat(tokens[0]);
  84448. var y = parseFloat(tokens[1]);
  84449. var z = parseFloat(tokens[2]);
  84450. this.scene.view.position.set(x, y, z);
  84451. }
  84452. if (Utils.getParameterByName('target')) {
  84453. var _value = Utils.getParameterByName('target');
  84454. _value = _value.replace('[', '').replace(']', '');
  84455. var _tokens = _value.split(';');
  84456. var _x = parseFloat(_tokens[0]);
  84457. var _y = parseFloat(_tokens[1]);
  84458. var _z = parseFloat(_tokens[2]);
  84459. this.scene.view.lookAt(new Vector3(_x, _y, _z));
  84460. }
  84461. if (Utils.getParameterByName('background')) {
  84462. var _value2 = Utils.getParameterByName('background');
  84463. this.setBackground(_value2);
  84464. }
  84465. // if(Utils.getParameterByName("elevationRange")){
  84466. // let value = Utils.getParameterByName("elevationRange");
  84467. // value = value.replace("[", "").replace("]", "");
  84468. // let tokens = value.split(";");
  84469. // let x = parseFloat(tokens[0]);
  84470. // let y = parseFloat(tokens[1]);
  84471. //
  84472. // this.setElevationRange(x, y);
  84473. // //this.scene.view.target.set(x, y, z);
  84474. // }
  84475. }
  84476. // ------------------------------------------------------------------------------------
  84477. // Viewer Internals
  84478. // ------------------------------------------------------------------------------------
  84479. createControls() {
  84480. {
  84481. // create FIRST PERSON CONTROLS
  84482. this.fpControls = new FirstPersonControls(this, this.mainViewport);
  84483. this.fpControls.enabled = false;
  84484. this.fpControls.addEventListener('start', this.disableAnnotations.bind(this));
  84485. this.fpControls.addEventListener('end', this.enableAnnotations.bind(this));
  84486. /* this.addEventListener("loadPointCloudDone", ()=>{
  84487. let boundPlane = new THREE.Box3()
  84488. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  84489. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  84490. FirstPersonControls.boundPlane = boundPlane
  84491. FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  84492. }) */
  84493. }
  84494. // { // create GEO CONTROLS
  84495. // this.geoControls = new GeoControls(this.scene.camera, this.renderer.domElement);
  84496. // this.geoControls.enabled = false;
  84497. // this.geoControls.addEventListener("start", this.disableAnnotations.bind(this));
  84498. // this.geoControls.addEventListener("end", this.enableAnnotations.bind(this));
  84499. // this.geoControls.addEventListener("move_speed_changed", (event) => {
  84500. // this.setMoveSpeed(this.geoControls.moveSpeed);
  84501. // });
  84502. // }
  84503. {
  84504. // create ORBIT CONTROLS
  84505. this.orbitControls = new OrbitControls$1(this);
  84506. this.orbitControls.enabled = false;
  84507. this.orbitControls.addEventListener('start', this.disableAnnotations.bind(this));
  84508. this.orbitControls.addEventListener('end', this.enableAnnotations.bind(this));
  84509. }
  84510. /* { // create EARTH CONTROLS
  84511. this.earthControls = new EarthControls(this);
  84512. this.earthControls.enabled = false;
  84513. this.earthControls.addEventListener('start', this.disableAnnotations.bind(this));
  84514. this.earthControls.addEventListener('end', this.enableAnnotations.bind(this));
  84515. }
  84516. { // create DEVICE ORIENTATION CONTROLS
  84517. this.deviceControls = new DeviceOrientationControls(this);
  84518. this.deviceControls.enabled = false;
  84519. this.deviceControls.addEventListener('start', this.disableAnnotations.bind(this));
  84520. this.deviceControls.addEventListener('end', this.enableAnnotations.bind(this));
  84521. } */
  84522. /* { // create VR CONTROLS
  84523. this.vrControls = new VRControls(this);
  84524. this.vrControls.enabled = false;
  84525. this.vrControls.addEventListener('start', this.disableAnnotations.bind(this));
  84526. this.vrControls.addEventListener('end', this.enableAnnotations.bind(this));
  84527. } */
  84528. }
  84529. toggleSidebar() {
  84530. var renderArea = $('#potree_render_area');
  84531. var isVisible = renderArea.css('left') !== '0px';
  84532. if (isVisible) {
  84533. renderArea.css('left', '0px');
  84534. } else {
  84535. renderArea.css('left', '300px');
  84536. }
  84537. }
  84538. toggleMap() {
  84539. // let map = $('#potree_map');
  84540. // map.toggle(100);
  84541. if (this.mapView) {
  84542. this.mapView.toggle();
  84543. }
  84544. }
  84545. onGUILoaded(callback) {
  84546. if (this.guiLoaded) {
  84547. callback();
  84548. } else {
  84549. this.guiLoadTasks.push(callback);
  84550. }
  84551. }
  84552. promiseGuiLoaded() {
  84553. return new Promise(resolve => {
  84554. if (this.guiLoaded) {
  84555. resolve();
  84556. } else {
  84557. this.guiLoadTasks.push(resolve);
  84558. }
  84559. });
  84560. }
  84561. loadGUI(callback) {
  84562. if (callback) {
  84563. this.onGUILoaded(callback);
  84564. }
  84565. var viewer = this;
  84566. var sidebarContainer = $('#potree_sidebar_container');
  84567. sidebarContainer.load(new URL(Potree.scriptPath + '/' + (Potree.settings.sidebar || 'sidebar1.html')).href, () => {
  84568. sidebarContainer.css('width', '300px');
  84569. sidebarContainer.css('height', '100%');
  84570. var imgMenuToggle = document.createElement('img');
  84571. imgMenuToggle.src = new URL(Potree.resourcePath + '/icons/menu_button.svg').href;
  84572. imgMenuToggle.onclick = this.toggleSidebar;
  84573. imgMenuToggle.classList.add('potree_menu_toggle');
  84574. var imgMapToggle = document.createElement('img');
  84575. imgMapToggle.src = new URL(Potree.resourcePath + '/icons/map_icon.png').href;
  84576. imgMapToggle.style.display = 'none';
  84577. imgMapToggle.onclick = e => {
  84578. this.toggleMap();
  84579. };
  84580. imgMapToggle.id = 'potree_map_toggle';
  84581. var elButtons = $("#potree_quick_buttons").get(0);
  84582. elButtons.append(imgMenuToggle);
  84583. elButtons.append(imgMapToggle);
  84584. VRButton$1.createButton(this.renderer).then(vrButton => {
  84585. if (vrButton == null) {
  84586. console.log("VR not supported or active.");
  84587. return;
  84588. }
  84589. this.renderer.xr.enabled = true;
  84590. var element = vrButton.element;
  84591. element.style.position = "";
  84592. element.style.bottom = "";
  84593. element.style.left = "";
  84594. element.style.margin = "4px";
  84595. element.style.fontSize = "100%";
  84596. element.style.width = "2.5em";
  84597. element.style.height = "2.5em";
  84598. element.style.padding = "0";
  84599. element.style.textShadow = "black 2px 2px 2px";
  84600. element.style.display = "block";
  84601. elButtons.append(element);
  84602. vrButton.onStart(() => {
  84603. this.dispatchEvent({
  84604. type: "vr_start"
  84605. });
  84606. });
  84607. vrButton.onEnd(() => {
  84608. this.dispatchEvent({
  84609. type: "vr_end"
  84610. });
  84611. });
  84612. });
  84613. /* this.mapView = new MapView(this);
  84614. this.mapView.init(); */
  84615. i18n.init({
  84616. lng: 'en',
  84617. resGetPath: Potree.resourcePath + '/lang/__lng__/__ns__.json',
  84618. preload: ['en', 'fr', 'de', 'jp', 'se', 'es', 'zh'],
  84619. getAsync: true,
  84620. debug: false
  84621. }, function (t) {
  84622. // Start translation once everything is loaded
  84623. $('body').i18n();
  84624. });
  84625. $(() => {
  84626. //initSidebar(this);
  84627. var sidebar = new Sidebar(this);
  84628. sidebar.init();
  84629. this.sidebar = sidebar;
  84630. //if (callback) {
  84631. // $(callback);
  84632. //}
  84633. var elProfile = $('<div>').load(new URL(Potree.scriptPath + '/profile.html').href, () => {
  84634. $(document.body).append(elProfile.children());
  84635. this.profileWindow = new ProfileWindow(this);
  84636. this.profileWindowController = new ProfileWindowController(this);
  84637. $('#profile_window').draggable({
  84638. handle: $('#profile_titlebar'),
  84639. containment: $(document.body)
  84640. });
  84641. $('#profile_window').resizable({
  84642. containment: $(document.body),
  84643. handles: 'n, e, s, w'
  84644. });
  84645. $(() => {
  84646. this.guiLoaded = true;
  84647. for (var task of this.guiLoadTasks) {
  84648. task();
  84649. }
  84650. });
  84651. });
  84652. });
  84653. });
  84654. return this.promiseGuiLoaded();
  84655. }
  84656. setLanguage(lang) {
  84657. i18n.setLng(lang);
  84658. $('body').i18n();
  84659. }
  84660. setServer(server) {
  84661. this.server = server;
  84662. }
  84663. initDragAndDrop() {
  84664. var _this2 = this;
  84665. function allowDrag(e) {
  84666. e.dataTransfer.dropEffect = 'copy';
  84667. e.preventDefault();
  84668. }
  84669. var dropHandler = /*#__PURE__*/function () {
  84670. var _ref = _asyncToGenerator(function* (event) {
  84671. console.log(event);
  84672. event.preventDefault();
  84673. for (var item of event.dataTransfer.items) {
  84674. console.log(item);
  84675. if (item.kind !== "file") {
  84676. continue;
  84677. }
  84678. var file = item.getAsFile();
  84679. var isJson = file.name.toLowerCase().endsWith(".json");
  84680. var isGeoPackage = file.name.toLowerCase().endsWith(".gpkg");
  84681. if (isJson) {
  84682. try {
  84683. var text = yield file.text();
  84684. var json = JSON.parse(text);
  84685. if (json.type === "Potree") {
  84686. Potree.loadProject(viewer, json);
  84687. }
  84688. } catch (e) {
  84689. console.error("failed to parse the dropped file as JSON");
  84690. console.error(e);
  84691. }
  84692. } else if (isGeoPackage) {
  84693. var hasPointcloud = viewer.scene.pointclouds.length > 0;
  84694. if (!hasPointcloud) {
  84695. var msg = "At least one point cloud is needed that specifies the ";
  84696. msg += "coordinate reference system before loading vector data.";
  84697. console.error(msg);
  84698. } else {
  84699. proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
  84700. proj4.defs("pointcloud", _this2.getProjection());
  84701. var transform = proj4("WGS84", "pointcloud");
  84702. var buffer = yield file.arrayBuffer();
  84703. var params = {
  84704. transform: transform,
  84705. source: file.name
  84706. };
  84707. var geo = yield Potree.GeoPackageLoader.loadBuffer(buffer, params);
  84708. viewer.scene.addGeopackage(geo);
  84709. }
  84710. }
  84711. }
  84712. });
  84713. return function dropHandler(_x2) {
  84714. return _ref.apply(this, arguments);
  84715. };
  84716. }();
  84717. $("body")[0].addEventListener("dragenter", allowDrag);
  84718. $("body")[0].addEventListener("dragover", allowDrag);
  84719. $("body")[0].addEventListener("drop", dropHandler);
  84720. }
  84721. updateAnnotations() {
  84722. if (!this.visibleAnnotations) {
  84723. this.visibleAnnotations = new Set();
  84724. }
  84725. this.scene.annotations.updateBounds();
  84726. this.scene.cameraP.updateMatrixWorld();
  84727. this.scene.cameraO.updateMatrixWorld();
  84728. var distances = [];
  84729. var renderAreaSize = this.renderer.getSize(new Vector2());
  84730. var viewer = this;
  84731. var visibleNow = [];
  84732. this.scene.annotations.traverse(annotation => {
  84733. if (annotation === this.scene.annotations) {
  84734. return true;
  84735. }
  84736. if (!annotation.visible) {
  84737. return false;
  84738. }
  84739. annotation.scene = this.scene;
  84740. var element = annotation.domElement;
  84741. var position = annotation.position.clone();
  84742. position.add(annotation.offset);
  84743. if (!position) {
  84744. position = annotation.boundingBox.getCenter(new Vector3());
  84745. }
  84746. var distance = viewer.scene.cameraP.position.distanceTo(position);
  84747. var radius = annotation.boundingBox.getBoundingSphere(new Sphere()).radius;
  84748. var screenPos = new Vector3();
  84749. var screenSize = 0;
  84750. {
  84751. // SCREEN POS
  84752. screenPos.copy(position).project(this.scene.getActiveCamera());
  84753. screenPos.x = renderAreaSize.x * (screenPos.x + 1) / 2;
  84754. screenPos.y = renderAreaSize.y * (1 - (screenPos.y + 1) / 2);
  84755. // SCREEN SIZE
  84756. if (viewer.scene.cameraMode == CameraMode.PERSPECTIVE) {
  84757. var fov = Math.PI * viewer.scene.cameraP.fov / 180;
  84758. var slope = Math.tan(fov / 2.0);
  84759. var projFactor = 0.5 * renderAreaSize.y / (slope * distance);
  84760. screenSize = radius * projFactor;
  84761. } else {
  84762. screenSize = Utils.projectedRadiusOrtho(radius, viewer.scene.cameraO.projectionMatrix, renderAreaSize.x, renderAreaSize.y);
  84763. }
  84764. }
  84765. element.css("left", screenPos.x + "px");
  84766. element.css("top", screenPos.y + "px");
  84767. //element.css("display", "block");
  84768. var zIndex = 10000000 - distance * (10000000 / this.scene.cameraP.far);
  84769. if (annotation.descriptionVisible) {
  84770. zIndex += 10000000;
  84771. }
  84772. element.css("z-index", parseInt(zIndex));
  84773. if (annotation.children.length > 0) {
  84774. var expand = screenSize > annotation.collapseThreshold || annotation.boundingBox.containsPoint(this.scene.getActiveCamera().position);
  84775. annotation.expand = expand;
  84776. if (!expand) {
  84777. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  84778. var inFrustum = screenPos.z >= -1 && screenPos.z <= 1;
  84779. if (inFrustum) {
  84780. visibleNow.push(annotation);
  84781. }
  84782. }
  84783. return expand;
  84784. } else {
  84785. //annotation.display = (screenPos.z >= -1 && screenPos.z <= 1);
  84786. var _inFrustum = screenPos.z >= -1 && screenPos.z <= 1;
  84787. if (_inFrustum) {
  84788. visibleNow.push(annotation);
  84789. }
  84790. }
  84791. });
  84792. var notVisibleAnymore = new Set(this.visibleAnnotations);
  84793. for (var annotation of visibleNow) {
  84794. annotation.display = true;
  84795. notVisibleAnymore.delete(annotation);
  84796. }
  84797. this.visibleAnnotations = visibleNow;
  84798. for (var _annotation of notVisibleAnymore) {
  84799. _annotation.display = false;
  84800. }
  84801. }
  84802. updateMaterialDefaults(pointcloud) {
  84803. // PROBLEM STATEMENT:
  84804. // * [min, max] of intensity, source id, etc. are computed as point clouds are loaded
  84805. // * the point cloud material won't know the range it should use until some data is loaded
  84806. // * users can modify the range at runtime, but sensible default ranges should be
  84807. // applied even if no GUI is present
  84808. // * display ranges shouldn't suddenly change even if the actual range changes over time.
  84809. // e.g. the root node has intensity range [1, 478]. One of the descendants increases range to
  84810. // [0, 2047]. We should not automatically change to the new range because that would result
  84811. // in sudden and drastic changes of brightness. We should adjust the min/max of the sidebar slider.
  84812. var material = pointcloud.material;
  84813. var attIntensity = pointcloud.getAttribute("intensity");
  84814. if (attIntensity != null && material.intensityRange[0] === Infinity) {
  84815. material.intensityRange = [...attIntensity.range];
  84816. }
  84817. // const attIntensity = pointcloud.getAttribute("intensity");
  84818. // if(attIntensity && material.intensityRange[0] === Infinity){
  84819. // material.intensityRange = [...attIntensity.range];
  84820. // }
  84821. // let attributes = pointcloud.getAttributes();
  84822. // for(let attribute of attributes.attributes){
  84823. // if(attribute.range){
  84824. // let range = [...attribute.range];
  84825. // material.computedRange.set(attribute.name, range);
  84826. // //material.setRange(attribute.name, range);
  84827. // }
  84828. // }
  84829. }
  84830. update(delta, timestamp) {
  84831. viewer.addTimeMark('update', 'start');
  84832. TWEEN.update(timestamp);
  84833. transitions.update(delta); //写在开头,因为这时候最为固定,计时准确
  84834. this.dispatchEvent({
  84835. type: 'update_start',
  84836. delta: delta,
  84837. timestamp: timestamp
  84838. });
  84839. this.updateScreenSize(); //判断是否改变canvas大小
  84840. var scene = this.scene;
  84841. var camera = scene.getActiveCamera();
  84842. var visiblePointClouds = this.scene.pointclouds.filter(pc => pc.visible);
  84843. Potree.pointLoadLimit = Potree.pointBudget * 2;
  84844. /* const lTarget = camera.position.clone().add(camera.getWorldDirection(new THREE.Vector3()).multiplyScalar(1000));
  84845. this.scene.directionalLight.position.copy(camera.position);
  84846. this.scene.directionalLight.lookAt(lTarget); */
  84847. for (var pointcloud of visiblePointClouds) {
  84848. pointcloud.showBoundingBox = this.showBoundingBox;
  84849. pointcloud.generateDEM = this.generateDEM;
  84850. pointcloud.minimumNodePixelSize = this.minNodeSize;
  84851. var material = pointcloud.material;
  84852. material.uniforms.uFilterReturnNumberRange.value = this.filterReturnNumberRange;
  84853. material.uniforms.uFilterNumberOfReturnsRange.value = this.filterNumberOfReturnsRange;
  84854. material.uniforms.uFilterGPSTimeClipRange.value = this.filterGPSTimeRange;
  84855. material.uniforms.uFilterPointSourceIDClipRange.value = this.filterPointSourceIDRange;
  84856. material.classification = this.classifications;
  84857. material.recomputeClassification();
  84858. this.updateMaterialDefaults(pointcloud);
  84859. }
  84860. {
  84861. if (this.showBoundingBox) {
  84862. var bbRoot = this.scene.scene.getObjectByName("potree_bounding_box_root");
  84863. if (!bbRoot) {
  84864. var node = new Object3D();
  84865. node.name = "potree_bounding_box_root";
  84866. this.scene.scene.add(node);
  84867. bbRoot = node;
  84868. }
  84869. var visibleBoxes = [];
  84870. for (var _pointcloud of this.scene.pointclouds) {
  84871. for (var _node of _pointcloud.visibleNodes.filter(vn => vn.boundingBoxNode !== undefined)) {
  84872. var box = _node.boundingBoxNode;
  84873. visibleBoxes.push(box);
  84874. }
  84875. }
  84876. bbRoot.children = visibleBoxes;
  84877. }
  84878. }
  84879. if (this.boundNeedUpdate) this.updateModelBound(); //add
  84880. this.scene.cameraP.fov = this.fov;
  84881. var controls = this.getControls();
  84882. if (controls === this.deviceControls) {
  84883. this.controls.setScene(scene);
  84884. this.controls.update(delta);
  84885. this.scene.cameraP.position.copy(scene.view.position);
  84886. this.scene.cameraO.position.copy(scene.view.position);
  84887. } else if (controls !== null) {
  84888. controls.setScene(scene);
  84889. controls.update(delta);
  84890. //更新camera
  84891. this.viewports.forEach(viewport => {
  84892. if (!viewport.active) return;
  84893. viewport.view.applyToCamera(viewport.camera);
  84894. });
  84895. }
  84896. this.lastFrameChanged = this.cameraChanged(); //判断camera画面是否改变
  84897. {
  84898. // update clip boxes
  84899. var boxes = [];
  84900. // volumes with clipping enabled
  84901. boxes.push(...this.scene.volumes.filter(v => v.clip && v instanceof BoxVolume$1));
  84902. // profile segments
  84903. for (var profile of this.scene.profiles) {
  84904. boxes.push(...profile.boxes);
  84905. }
  84906. // Needed for .getInverse(), pre-empt a determinant of 0, see #815 / #816
  84907. var degenerate = box => box.matrixWorld.determinant() !== 0 && box.clip;
  84908. var clipBoxes = boxes.filter(degenerate).map(box => {
  84909. box.updateMatrixWorld();
  84910. var boxInverse = box.matrixWorld.clone().invert();
  84911. //let boxPosition = box.getWorldPosition(new THREE.Vector3());
  84912. return {
  84913. box: box,
  84914. inverse: boxInverse /* , position: boxPosition */
  84915. };
  84916. });
  84917. //改
  84918. var bigClipInBox = clipBoxes.find(e => e.box.clipTask == ClipTask.SHOW_INSIDE_Big && !e.box.highlight); //裁剪下载 when this.modules.Clip.editing
  84919. var clipBoxes_in = clipBoxes.filter(e => e.box.clipTask == ClipTask.SHOW_INSIDE && !e.box.highlight);
  84920. var clipBoxes_out = clipBoxes.filter(e => e.box.clipTask == ClipTask.SHOW_OUTSIDE && !e.box.highlight);
  84921. var highlightBoxes = clipBoxes.filter(e => e.box.highlight);
  84922. //let prismPolygons = this.modules.volumeComputer && this.modules.volumeComputer.entered ? viewer.scene.measurements.filter(e=>(e.measureType == 'MulDistance Ring') && !e.isNew) : []
  84923. var prismPolygons = this.modules.volumeComputer ? this.modules.volumeComputer.prisms.filter(e => !e.isNew && e.visible && !e.dontHighlight && (e.baseModel || !e.modelHaventLoad)) : [];
  84924. // set clip volumes in material
  84925. for (var _pointcloud2 of visiblePointClouds) {
  84926. _pointcloud2.material.setClipBoxes(bigClipInBox, clipBoxes_in, clipBoxes_out, highlightBoxes, prismPolygons);
  84927. }
  84928. }
  84929. {
  84930. for (var _pointcloud3 of visiblePointClouds) {
  84931. _pointcloud3.material.elevationGradientRepeat = this.elevationGradientRepeat;
  84932. }
  84933. }
  84934. {
  84935. // update navigation cube
  84936. this.navigationCube.update(camera.rotation);
  84937. }
  84938. this.updateAnnotations();
  84939. if (this.mapView) {
  84940. this.mapView.update(delta);
  84941. if (this.mapView.sceneProjection) {
  84942. $("#potree_map_toggle").css("display", "block");
  84943. }
  84944. }
  84945. this.transformationTool.update();
  84946. if (Potree.settings.editType != 'pano' && Potree.settings.editType != 'merge') {
  84947. this.modules.ParticleEditor.update(delta);
  84948. }
  84949. this.mapViewer && this.mapViewer.update(delta); //地图更新
  84950. this.dispatchEvent({
  84951. type: 'update',
  84952. delta: delta,
  84953. timestamp: timestamp
  84954. }); //在有sidebar时耗高cpu,占本update函数80%
  84955. viewer.addTimeMark('update', 'end');
  84956. //add ------
  84957. this.reticule.updateVisible();
  84958. }
  84959. updateViewPointcloud(camera, areaSize, isViewport) {
  84960. var result = Potree.updatePointClouds(this.scene.pointclouds, camera, areaSize);
  84961. //if(isViewport)return
  84962. var tStart = performance.now();
  84963. var campos = camera.position;
  84964. var closestImage = Infinity;
  84965. for (var images of this.scene.orientedImages) {
  84966. for (var image of images.images) {
  84967. var distance = image.mesh.position.distanceTo(campos);
  84968. closestImage = Math.min(closestImage, distance);
  84969. }
  84970. }
  84971. //const tEnd = performance.now();
  84972. //改:不根据点云修改视野near far
  84973. var near = camera.near,
  84974. far = camera.far;
  84975. if (!camera.limitFar && result.lowestSpacing !== Infinity) {
  84976. //let near = result.lowestSpacing * 10.0;
  84977. var _far = -this.getBoundingBox().applyMatrix4(camera.matrixWorldInverse).min.z;
  84978. _far = Math.max(_far * 1.5, 10000);
  84979. //near = Math.min(100.0, Math.max(0.01, near));
  84980. //near = Math.min(near, closestImage);
  84981. _far = Math.max(_far, near + 10000);
  84982. /* if(near === Infinity){
  84983. near = 0.1;
  84984. } */
  84985. //camera.near = near; //为了其他物体的显示,不修改near
  84986. camera.far = _far;
  84987. }
  84988. /* if(this.scene.cameraMode == CameraMode.ORTHOGRAPHIC) {//???
  84989. camera.near = -camera.far;
  84990. } */
  84991. if ( /* near != camera.near || */far != camera.far) {
  84992. camera.updateProjectionMatrix();
  84993. }
  84994. //注:pointcloud.visibleNodes会随着near far自动更新
  84995. }
  84996. getPRenderer() {
  84997. if (this.useHQ) {
  84998. if (!this.hqRenderer) {
  84999. this.hqRenderer = new HQSplatRenderer(this);
  85000. }
  85001. this.hqRenderer.useEDL = this.useEDL;
  85002. return this.hqRenderer;
  85003. } else {
  85004. /* if (this.useEDL && Features.SHADER_EDL.isSupported()) {
  85005. if (!this.edlRenderer) {
  85006. this.edlRenderer = new EDLRenderer(this);
  85007. }
  85008. return this.edlRenderer;
  85009. } else {
  85010. if (!this.potreeRenderer) {
  85011. this.potreeRenderer = new PotreeRenderer(this);
  85012. }
  85013. return this.potreeRenderer;
  85014. } */
  85015. if (!this.edlRenderer) {
  85016. this.edlRenderer = new EDLRenderer(this);
  85017. }
  85018. return this.edlRenderer;
  85019. }
  85020. }
  85021. renderVR() {
  85022. //渲染部分没改完
  85023. var renderer = this.renderer;
  85024. renderer.setClearColor(0x550000, 0);
  85025. renderer.clear();
  85026. var xr = renderer.xr;
  85027. var dbg = new PerspectiveCamera();
  85028. var xrCameras = xr.getCamera(dbg);
  85029. if (xrCameras.cameras.length !== 2) {
  85030. return;
  85031. }
  85032. var makeCam = this.vrControls.getCamera.bind(this.vrControls);
  85033. {
  85034. // clear framebuffer
  85035. if (viewer.background === "skybox") {
  85036. renderer.setClearColor(0xff0000, 1);
  85037. } else if (viewer.background === "gradient") {
  85038. renderer.setClearColor(0x112233, 1);
  85039. } else if (viewer.background === "black") {
  85040. renderer.setClearColor(0x000000, 1);
  85041. } else if (viewer.background === "white") {
  85042. renderer.setClearColor(0xFFFFFF, 1);
  85043. } else {
  85044. renderer.setClearColor(0x000000, 0);
  85045. }
  85046. renderer.clear();
  85047. }
  85048. // render background
  85049. if (this.background === "skybox") {
  85050. var {
  85051. skybox
  85052. } = this;
  85053. var _cam = makeCam();
  85054. skybox.camera.rotation.copy(_cam.rotation);
  85055. skybox.camera.fov = _cam.fov;
  85056. skybox.camera.aspect = _cam.aspect;
  85057. // let dbg = new THREE.Object3D();
  85058. var _dbg = skybox.parent;
  85059. // dbg.up.set(0, 0, 1);
  85060. _dbg.rotation.x = Math.PI / 2;
  85061. // skybox.camera.parent = dbg;
  85062. // dbg.children.push(skybox.camera);
  85063. _dbg.updateMatrix();
  85064. _dbg.updateMatrixWorld();
  85065. skybox.camera.updateMatrix();
  85066. skybox.camera.updateMatrixWorld();
  85067. skybox.camera.updateProjectionMatrix();
  85068. renderer.render(skybox.scene, skybox.camera);
  85069. // renderer.render(skybox.scene, cam);
  85070. } else if (this.background === "gradient") {
  85071. // renderer.render(this.scene.sceneBG, this.scene.cameraBG);
  85072. }
  85073. this.renderer.xr.getSession().updateRenderState({
  85074. depthNear: 0.1,
  85075. depthFar: 10000
  85076. });
  85077. var cam = null;
  85078. var view = null;
  85079. {
  85080. // render world scene
  85081. cam = makeCam();
  85082. cam.position.z -= 0.8 * cam.scale.x;
  85083. cam.parent = null;
  85084. // cam.near = 0.05;
  85085. cam.near = viewer.scene.getActiveCamera().near;
  85086. cam.far = viewer.scene.getActiveCamera().far;
  85087. cam.updateMatrix();
  85088. cam.updateMatrixWorld();
  85089. this.scene.scene.updateMatrix();
  85090. this.scene.scene.updateMatrixWorld();
  85091. this.scene.scene.matrixAutoUpdate = false;
  85092. var camWorld = cam.matrixWorld.clone();
  85093. view = camWorld.clone().invert();
  85094. this.scene.scene.matrix.copy(view);
  85095. this.scene.scene.matrixWorld.copy(view);
  85096. cam.matrix.identity();
  85097. cam.matrixWorld.identity();
  85098. cam.matrixWorldInverse.identity();
  85099. renderer.render(this.scene.scene, cam);
  85100. this.scene.scene.matrixWorld.identity();
  85101. }
  85102. for (var pointcloud of this.scene.pointclouds) {
  85103. var viewport = xrCameras.cameras[0].viewport;
  85104. pointcloud.material.useEDL = false;
  85105. pointcloud.screenHeight = viewport.height;
  85106. pointcloud.screenWidth = viewport.width;
  85107. // automatically switch to paraboloids because they cause far less flickering in VR,
  85108. // when point sizes are larger than around 2 pixels
  85109. // if(Features.SHADER_INTERPOLATION.isSupported()){
  85110. // pointcloud.material.shape = Potree.PointShape.PARABOLOID;
  85111. // }
  85112. }
  85113. // render point clouds
  85114. for (var xrCamera of xrCameras.cameras) {
  85115. var v = xrCamera.viewport;
  85116. renderer.setViewport(v.x, v.y, v.width, v.height);
  85117. // xrCamera.fov = 90;
  85118. {
  85119. // estimate VR fov
  85120. var proj = xrCamera.projectionMatrix;
  85121. var inv = proj.clone().invert();
  85122. var p1 = new Vector4(0, 1, -1, 1).applyMatrix4(inv);
  85123. var rad = p1.y;
  85124. var fov = 180 * (rad / Math.PI);
  85125. xrCamera.fov = fov;
  85126. }
  85127. for (var _pointcloud4 of this.scene.pointclouds) {
  85128. var {
  85129. material
  85130. } = _pointcloud4;
  85131. material.useEDL = false;
  85132. }
  85133. var vrWorld = view.clone().invert();
  85134. vrWorld.multiply(xrCamera.matrixWorld);
  85135. var vrView = vrWorld.clone().invert();
  85136. this.pRenderer.render(this.scene.scenePointCloud, xrCamera, null, {
  85137. viewOverride: vrView
  85138. });
  85139. }
  85140. {
  85141. // render VR scene
  85142. var _cam2 = makeCam();
  85143. _cam2.parent = null;
  85144. renderer.render(this.sceneVR, _cam2);
  85145. }
  85146. renderer.resetState();
  85147. }
  85148. clear() {
  85149. var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  85150. var background = params.background || this.background;
  85151. var backgroundOpacity = params.backgroundOpacity == void 0 ? this.backgroundOpacity : params.backgroundOpacity; //如果想完全透明,只需要backgroundOpacity为0
  85152. var renderer = this.renderer;
  85153. //let gl = renderer.getContext()
  85154. if (background instanceof Color) {
  85155. //add
  85156. renderer.setClearColor(background, backgroundOpacity);
  85157. } else if (background === "skybox") {
  85158. renderer.setClearColor(0x000000, backgroundOpacity);
  85159. } else if (background === 'gradient') {
  85160. renderer.setClearColor(0x000000, backgroundOpacity);
  85161. } else if (background === 'black') {
  85162. renderer.setClearColor(0x000000, 1);
  85163. } else if (background === 'white') {
  85164. renderer.setClearColor(0xFFFFFF, 1);
  85165. } else {
  85166. renderer.setClearColor(background, backgroundOpacity);
  85167. }
  85168. params.target || renderer.clear();
  85169. }
  85170. getBuffer(viewport) {
  85171. //根据不同viewport返回rtEDL的texture
  85172. var buffer = this.buffers.get(viewport);
  85173. if (!buffer) {
  85174. buffer = new WebGLRenderTarget(viewport.resolution.x, viewport.resolution.y, {
  85175. minFilter: NearestFilter,
  85176. magFilter: NearestFilter,
  85177. format: RGBAFormat,
  85178. type: FloatType
  85179. });
  85180. this.buffers.set(viewport, rtEDL);
  85181. }
  85182. return buffer;
  85183. }
  85184. renderDefault() {
  85185. var _arguments = arguments,
  85186. _this3 = this;
  85187. return _asyncToGenerator(function* () {
  85188. var params_ = _arguments.length > 0 && _arguments[0] !== undefined ? _arguments[0] : {};
  85189. if (!_this3.visible) return;
  85190. var pRenderer = _this3.getPRenderer();
  85191. var viewports = params_.viewports || _this3.viewports;
  85192. viewer.addTimeMark('renderDefault', 'start');
  85193. //console.log('render', viewports.map(e=>e.name).join(','))
  85194. var renderSize;
  85195. if (params_.target) {
  85196. renderSize = new Vector2(params_.target.width, params_.target.height); //是画布大小
  85197. //可能需要viewer.setSize
  85198. } else {
  85199. renderSize = _this3.renderer.getSize(new Vector2()); //是client大小
  85200. }
  85201. ///let needsResize = viewports.length > 1 || params_.resize //去掉原因:因为不需要渲染的viewport不在此中所以无法判断几个viewport
  85202. for (var i = 0; i < viewports.length; i++) {
  85203. var viewport = viewports[i];
  85204. var params = $.extend({}, params_);
  85205. params.viewport = viewport;
  85206. //if(!params.target){
  85207. params.camera = params.camera || viewport.camera;
  85208. params.extraEnableLayers = viewport.extraEnableLayers;
  85209. params.cameraLayers = viewport.cameraLayers;
  85210. //}
  85211. var left, bottom, width, height;
  85212. {
  85213. left = Math.ceil(renderSize.x * viewport.left);
  85214. bottom = Math.ceil(renderSize.y * viewport.bottom);
  85215. if (params_.target) {
  85216. //有target时最好viewport是专门建出来的
  85217. width = renderSize.x * viewport.width; //target的大小可能和viewport不同,比如截图,这时会更改viewport大小
  85218. height = renderSize.y * viewport.height;
  85219. } else {
  85220. width = viewport.resolution.x; // 用的是client的width和height
  85221. height = viewport.resolution.y;
  85222. }
  85223. if (width == 0 || height == 0) continue; //return
  85224. width = Math.ceil(width); //使用ceil,当原本有小数时,会重叠一个像素,无所谓
  85225. height = Math.ceil(height);
  85226. var scissorTest = viewport.width < 1 || viewport.height < 1;
  85227. if (params_.target) {
  85228. params_.target.viewport.set(left, bottom, width, height);
  85229. scissorTest && params_.target.scissor.set(left, bottom, width, height);
  85230. params_.target.scissorTest = scissorTest;
  85231. _this3.renderer.setRenderTarget(params_.target);
  85232. } else {
  85233. /* if(viewports.length == 1 && left == 0 && bottom == 0){
  85234. left = 1 , width-=1 //这种情况下渲染也会有问题,只有鼠标的地方刷新 估计是pick那影响的
  85235. } */
  85236. /* if(scissorTest && left == 0 && bottom == 0){
  85237. left = 1 , width-=1
  85238. } */
  85239. if (viewport.forViewOffset) {
  85240. //分块渲染,渲染时的camera还是原来的,但加载点云时的camera是分块中的
  85241. viewport.forViewOffset.camera.setViewOffset(renderSize.x, renderSize.y, left, renderSize.y - bottom - height, width, height);
  85242. _this3.renderer.setViewport(0, 0, renderSize.x, renderSize.y);
  85243. viewport.resolution.copy(viewport.forViewOffset.originViewport.resolution);
  85244. viewport.resolution2.copy(viewport.forViewOffset.originViewport.resolution2); //后续渲染都当做原先的viewport
  85245. } else {
  85246. _this3.renderer.setViewport(left, bottom, width, height); //规定视口,影响图形变换(画布的使用范围)
  85247. }
  85248. //scissorTest && console.log('setScissor', left, bottom, width, height)
  85249. scissorTest && _this3.renderer.setScissor(left, bottom, width, height); //规定渲染范围
  85250. _this3.renderer.setScissorTest(scissorTest); //开启WebGL剪裁测试功能,如果不开启,.setScissor方法设置的范围不起作用 | width==1且height==1时开启会只有鼠标的地方刷新,很奇怪
  85251. }
  85252. }
  85253. //if(needsResize){
  85254. _this3.ifEmitResize({
  85255. viewport
  85256. });
  85257. //}
  85258. viewer.dispatchEvent({
  85259. type: "render.begin",
  85260. viewer: viewer,
  85261. viewport,
  85262. params
  85263. });
  85264. viewport.beforeRender && viewport.beforeRender();
  85265. if (viewport.render) {
  85266. if (!viewport.render($.extend({}, params, {
  85267. renderer: _this3.renderer,
  85268. clear: _this3.clear.bind(_this3),
  85269. resize: null,
  85270. renderBG: _this3.renderBG.bind(_this3),
  85271. force: true //viewer content_change时map也直接渲染吧 //!viewport.noPointcloud //如果要渲染点云,必须也一直渲染地图,否则地图会被覆盖(点云目前未能获取是否改变,也可能有其他动态物体,所以还是一直渲染的好)
  85272. }))) continue; //return
  85273. } else {
  85274. _this3.clear(params);
  85275. pRenderer.clearTargets(params);
  85276. _this3.renderBG(viewport);
  85277. if (Potree.settings.notAdditiveBlending) {
  85278. params.renderBeforeCloud = true;
  85279. _this3.renderOverlay1(params); //先渲染不透明的model。 但drawedModelOnRT时这里提前多渲染了一遍
  85280. }
  85281. }
  85282. if (!viewport.noPointcloud) {
  85283. if (params_.needWaitLoadPoint) {
  85284. yield _this3.waitPointLoad(null, params_.maxTimeForPointLoad, viewport); //resolution得用split前整个的viewport的
  85285. } else {
  85286. _this3.updateViewPointcloud(params.camera, viewport.resolution, true);
  85287. }
  85288. pRenderer.render(params); //渲染点云 skybox
  85289. }
  85290. if (Potree.settings.notAdditiveBlending) {
  85291. // 融合页面才用到
  85292. params.renderBeforeCloud = false;
  85293. _this3.renderOverlay1(params);
  85294. _this3.renderOverlay2(params);
  85295. } else {
  85296. _this3.renderOverlay(params);
  85297. }
  85298. viewport.afterRender && viewport.afterRender();
  85299. _this3.dispatchEvent({
  85300. type: "render.end",
  85301. viewer: _this3,
  85302. viewport
  85303. });
  85304. viewport.needRender = false;
  85305. viewport.lastRenderTime = Date.now();
  85306. }
  85307. /* if(params_.screenshot){ //抗锯齿
  85308. this.composer.render();
  85309. } */
  85310. _this3.renderer.setRenderTarget(null);
  85311. viewer.scene.pointclouds[0] && _this3.addFakeMeasure('visibleNodes', viewer.scene.pointclouds[0].visibleNodes.length); //
  85312. _this3.addFakeMeasure('numVisiblePoints', Potree.numVisiblePoints / 100000); //十万 numVisiblePoints和帧率成反比(若每一帧都render的话),和render用时成正比 (y=kn+b)。但visibleNodes个数也影响,多的话也更卡。visibleNodes和numVisiblePoints不成正比,少的visibleNodes可能numVisiblePoints多
  85313. viewer.addTimeMark('renderDefault', 'end');
  85314. })();
  85315. }
  85316. renderBG(viewport) {
  85317. var background = viewport.background || viewer.background;
  85318. var backgroundOpacity = viewport.backgroundOpacity == void 0 ? viewer.backgroundOpacity : viewport.backgroundOpacity; //如果想完全透明,只需要backgroundOpacity为0
  85319. if (backgroundOpacity != 0) {
  85320. //绘制背景. 为了防止相机移动后天空不动有点死板,做一定的动态
  85321. if (background === "skybox") {
  85322. //限制相机到原点的距离。
  85323. var skyCamera = viewport.camera.type == "OrthographicCamera" ? viewer.skybox.cameraOrtho : viewer.skybox.camera;
  85324. var safeRatio = 0.02;
  85325. var safeWidth = Potree.config.skyboxBgWidth * safeRatio / 2; //相机只能在这个范围内移动
  85326. if (!viewport.skyboxFixPos) {
  85327. //允许不在全景图中心,允许位移造成一定程度畸变
  85328. var dir = new Vector3().subVectors(viewport.camera.position, viewer.bound.center);
  85329. var length = dir.length();
  85330. var moveMax = 100;
  85331. var aimRadius = easing.easeOutQuart(Math.min(length, moveMax), 0, safeWidth, moveMax); //(x, startY, wholeY, maxX) 当自变量为0-moveMax时,相机位移量为0-safeWidth
  85332. dir.multiplyScalar(aimRadius / length);
  85333. skyCamera.position.copy(dir);
  85334. } else {
  85335. skyCamera.position.set(0, 0, 0);
  85336. }
  85337. skyCamera.rotation.copy(viewport.camera.rotation);
  85338. skyCamera.aspect = viewport.camera.aspect;
  85339. if (viewport.camera.type == "OrthographicCamera") {
  85340. //调节zoom
  85341. skyCamera.left = viewport.camera.left;
  85342. skyCamera.right = viewport.camera.right;
  85343. skyCamera.top = viewport.camera.top;
  85344. skyCamera.bottom = viewport.camera.bottom;
  85345. var a = Potree.config.skyboxBgWidth / 2 - safeWidth;
  85346. var minY = Math.max(skyCamera.right / a, skyCamera.top / a, viewport.skyboxMinZoom || 0); //能够使skybox铺满画布的最小zoom. 提示:越远zoom越小
  85347. var maxY = Math.max(20, minY); //自定义一个 不会超过的最大实际zoom
  85348. //viewport.camera.zoom自变量的变化范围:
  85349. var minX = 1;
  85350. var maxX = 80;
  85351. var x = MathUtils.clamp(viewport.camera.zoom - minX, minX, maxX);
  85352. skyCamera.zoom = easing.easeOutCubic(x - minX, minY, maxY - minY, maxX - minX); //自变量范围从0开始,所以减去minX
  85353. //pos的范围先不管了 其实aimRadius是有误的,但效果还行
  85354. } else {
  85355. skyCamera.fov = viewport.camera.fov;
  85356. skyCamera.zoom = 1;
  85357. }
  85358. viewport.skyboxRenderFun && viewport.skyboxRenderFun();
  85359. skyCamera.updateProjectionMatrix();
  85360. skyCamera.updateMatrixWorld();
  85361. viewer.renderer.render(viewer.skybox.scene, skyCamera);
  85362. } else if (background === 'gradient') {
  85363. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg);
  85364. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  85365. } else if (background === 'overlayColor') {
  85366. //在不clear的前提下加一层背景色
  85367. viewer.scene.bg2.material.color.copy(viewport.backgroundColor);
  85368. viewer.scene.bg2.material.opacity = viewport.backgroundOpacity;
  85369. viewer.scene.cameraBG.layers.set(Potree.config.renderLayers.bg2);
  85370. viewer.renderer.render(viewer.scene.scene, viewer.scene.cameraBG);
  85371. }
  85372. }
  85373. //全景图的部分和点云有点相关就不移动到这了。但是如果是showPanos模式,就不要渲染背景了。
  85374. }
  85375. /*
  85376. 关于透明度:
  85377. 由于点云和mesh是分开渲染的,且材质很不一样,所以透明和blend有冲突
  85378. 1 如果点云的blend是AdditiveBlending,也就是普通的叠加模式。
  85379. 则半透明点云的depthTest和depthWrite都为false
  85380. 这时候mesh要后渲染,且depthWrite不能为false(除非depthTest也为false),否则将被点云遮住。
  85381. 2 如果点云的blend是普通型
  85382. 则半透明点云的depthTest和depthWrite都为true。(为何depthWrite不能像mesh一样为false, 否则点云自身透明会错乱,可能因为太多points了)
  85383. 这时候若mesh全部先渲染,则 透过depthWrite为false的半透明mesh看不透明点云,mesh会完全被点云遮住。但是透明的物体就是depthWrite要为false,否则也会完全遮住点云
  85384. 即使是后渲染半透明的mesh,若透过点云看mesh,mesh会完全被点云遮住(为什么之前遇到过 透过点云看mesh,点云会显示不出)
  85385. 最终选择是先渲染不透明的mesh,然后点云,然后透明的mesh。虽然点云对mesh透明会失效。
  85386. */
  85387. renderOverlay(params) {
  85388. viewer.addTimeMark('renderOverlay', 'start');
  85389. this.renderOverlay1(params);
  85390. this.renderOverlay2(params);
  85391. viewer.addTimeMark('renderOverlay', 'end');
  85392. }
  85393. renderOverlay1(params) {
  85394. var camera = params.camera ? params.camera : this.scene.getActiveCamera();
  85395. var renderer = params.renderer || this.renderer;
  85396. this.reticule.updateAtViewports(params.viewport);
  85397. renderer.setRenderTarget(params.target || null);
  85398. //为什么要在点云之后渲染,否则透明失效 、 会被点云覆盖
  85399. var cameraLayers;
  85400. if (params.cameraLayers) cameraLayers = params.cameraLayers;else {
  85401. if (params.viewport.name == "mapViewport") cameraLayers = ['bothMapAndScene', 'light'];else {
  85402. cameraLayers = ['sceneObjects', 'light', 'bothMapAndScene'];
  85403. if (!params.drawedModelOnRT) {
  85404. cameraLayers.push('model');
  85405. }
  85406. }
  85407. }
  85408. if (cameraLayers.length) {
  85409. Potree.Utils.setCameraLayers(camera, cameraLayers, params.extraEnableLayers); //透明贴图层 skybox 、reticule marker 不能遮住测量线
  85410. if ('renderBeforeCloud' in params) {
  85411. this.scene.scene.traverse(object => {
  85412. if (object.material) {
  85413. Potree.Utils.updateVisible(object, 'renderOpa', params.renderBeforeCloud && (object.material.opacity < 1 || !object.material.depthTest) || !params.renderBeforeCloud && object.material.opacity == 1 && object.material.depthTest ? false : true);
  85414. //点云之前渲染的话隐藏半透明的, 点云之后渲染的话隐藏不透明的。 depthTest==false的也最后渲染
  85415. }
  85416. }); //ground的材质中opacity为1,所以被当做不透明了
  85417. }
  85418. viewer.dispatchEvent({
  85419. type: "render.begin2",
  85420. name: 'scene',
  85421. viewport: params.viewport
  85422. });
  85423. renderer.render(this.scene.scene, camera);
  85424. if ('renderBeforeCloud' in params) {
  85425. this.scene.scene.traverse(object => {
  85426. if (object.material) {
  85427. Potree.Utils.updateVisible(object, 'renderOpa', true); //恢复
  85428. }
  85429. });
  85430. }
  85431. }
  85432. this.dispatchEvent({
  85433. type: "render.pass.scene",
  85434. viewer: viewer
  85435. });
  85436. }
  85437. renderOverlay2(params) {
  85438. var renderer = params.renderer || this.renderer;
  85439. var camera = params.camera ? params.camera : this.scene.getActiveCamera();
  85440. //清除深度 !!!!
  85441. renderer.clearDepth();
  85442. if (!params.magnifier) {
  85443. //测量线
  85444. this.dispatchEvent({
  85445. type: "render.pass.perspective_overlay",
  85446. camera,
  85447. screenshot: params.screenshot,
  85448. viewport: params.viewport,
  85449. renderer
  85450. });
  85451. if (!params.screenshot && params.viewport.name != "mapViewport") {
  85452. Potree.Utils.setCameraLayers(camera, ['magnifier']); //magnifier 遮住测量线
  85453. renderer.render(this.scene.scene, camera);
  85454. }
  85455. }
  85456. if (params.viewport.name != "mapViewport") {
  85457. Potree.Utils.setCameraLayers(camera, ['volume', 'transformationTool']);
  85458. //viewer.dispatchEvent({type: "render.begin2" , name:'clip&trans',viewport:params.viewport })
  85459. renderer.render(this.clippingTool.sceneVolume, camera); //official 可以删
  85460. renderer.render(this.transformationTool.scene, camera);
  85461. }
  85462. }
  85463. setLimitFar(state) {
  85464. //切换是否limitFar
  85465. viewer.mainViewport.camera.limitFar = !!state;
  85466. if (state) {
  85467. viewer.mainViewport.camera.near = 0.02;
  85468. viewer.mainViewport.camera.far = Potree.settings.displayMode == 'showPanos' ? viewer.farWhenShowPano : Potree.settings.cameraFar;
  85469. viewer.mainViewport.camera.updateProjectionMatrix();
  85470. }
  85471. }
  85472. setClipState(state) {
  85473. //有时候需要暂时关闭下clip
  85474. state = !!state;
  85475. if (this.clipUnabled == !state) return;
  85476. this.scene.volumes.filter(v => /* v.clip && */v instanceof Potree.BoxVolume).map(volume => {
  85477. volume.clip = state;
  85478. Potree.Utils.updateVisible(volume, 'setClipState', state);
  85479. });
  85480. this.clipUnabled = !state;
  85481. }
  85482. /* 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  85483. https://blog.csdn.net/weixin_30378311/article/details/94846947 */
  85484. render() {
  85485. var _arguments2 = arguments,
  85486. _this4 = this;
  85487. return _asyncToGenerator(function* () {
  85488. var params = _arguments2.length > 0 && _arguments2[0] !== undefined ? _arguments2[0] : {};
  85489. //add params
  85490. viewer.addTimeMark('render', 'start');
  85491. var vrActive = _this4.renderer.xr.isPresenting;
  85492. var SiteModel = viewer.modules.SiteModel;
  85493. if (_this4.screenshoting && !params.screenshot) return; //正在截图
  85494. var s = SiteModel.editing && SiteModel.selected && (SiteModel.selected.buildType == 'room' || SiteModel.selected.buildType == 'floor'); //空间模型的房间选中材质是需要depth的,这时候需要绘制两次点云
  85495. Potree.settings.pointEnableRT = !_this4.screenshoting && (_this4.scene.measurements.filter(e => e.visible).length > 0 || s);
  85496. if (vrActive) {
  85497. _this4.renderVR();
  85498. } else {
  85499. var specialRender = !!params.viewports;
  85500. var viewports = params.viewports || _this4.viewports;
  85501. if (!_this4.needRender) {
  85502. viewports = viewports.filter(v => v.needRender); //可以渲染的条件是viewer或viewport的needRender为true
  85503. }
  85504. viewports = viewports.filter(v => v.active);
  85505. if (viewports.length > 0) {
  85506. params.viewports = viewports;
  85507. if (_this4.outlinePass.selectedObjects.length && _this4.outlinePass.edgeStrength > 0 && !params.screenshot
  85508. // || this.images360.fastTranMaskPass.enabled
  85509. ) {
  85510. var scenes = _this4.inputHandler.interactiveScenes.concat(_this4.scene.scene).concat(viewer.scene.scenePointCloud);
  85511. _this4.composer.render(scenes, null, _this4.viewports, _this4.renderDefault.bind(_this4));
  85512. } else {
  85513. yield _this4.renderDefault(params);
  85514. }
  85515. }
  85516. if (!specialRender) _this4.needRender = false;
  85517. }
  85518. viewer.addTimeMark('render', 'end');
  85519. })();
  85520. }
  85521. startScreenshot() {
  85522. var _this5 = this;
  85523. var info = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  85524. var width = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 800;
  85525. var height = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 400;
  85526. var compressRatio = arguments.length > 3 ? arguments[3] : undefined;
  85527. //add
  85528. //let deferred = info.deferred || $.Deferred();
  85529. var getImageDeferred = info.getImageDeferred || $.Deferred();
  85530. var finishDeferred = info.finishDeferred || $.Deferred();
  85531. var viewerMaster = info.map ? this.mapViewer : this; //截图主体
  85532. var useMap = info.map || info.type == 'measure' || info.type.includes('prism2d');
  85533. if (Potree.settings.displayMode == 'showPanos' && viewer.mainViewport.view.isFlying('pos')) {
  85534. //如果在飞,飞完再截图
  85535. info.getImageDeferred = getImageDeferred, info.finishDeferred = finishDeferred;
  85536. var f = () => {
  85537. this.startScreenshot(info, width, height, compressRatio);
  85538. };
  85539. viewer.mainViewport.view.addEventListener('flyingDone', f, {
  85540. once: true
  85541. });
  85542. return {
  85543. getImagePromise: getImageDeferred.promise(),
  85544. finishPromise: finishDeferred.promise()
  85545. };
  85546. }
  85547. var startTime = Date.now();
  85548. //抗锯齿待加 1 post处理 2截图大张再抗锯齿缩小
  85549. this.pauseTestMaxLevel = true;
  85550. this.screenshoting = true;
  85551. console.log('startScreenshot: ' + startTime);
  85552. var updateCamera = () => {
  85553. viewports.forEach(e => {
  85554. e.view.applyToCamera(e.camera); //因为fly时只更新了view所以要强制更新下camera
  85555. this.dispatchEvent({
  85556. //update map and sprite, mapChanged
  85557. type: "camera_changed",
  85558. camera: e.camera,
  85559. viewport: e,
  85560. changeInfo: {
  85561. positionChanged: true,
  85562. changed: true
  85563. }
  85564. });
  85565. });
  85566. };
  85567. var screenshot = /*#__PURE__*/function () {
  85568. var _ref2 = _asyncToGenerator(function* () {
  85569. var pose;
  85570. useMap && (viewer.mapViewer.needRender = true);
  85571. info.beforeScreenshot && info.beforeScreenshot();
  85572. var render = /*#__PURE__*/function () {
  85573. var _ref3 = _asyncToGenerator(function* () {
  85574. _this5.needRender = true;
  85575. viewports.forEach(e => e.active = true);
  85576. if (info.useRenderTarget) {
  85577. //离屏渲染 有抗锯齿问题、在手机上速度慢 主视图一样会变内容,还是不用这个了
  85578. var {
  85579. dataUrl
  85580. } = viewerMaster.makeScreenshot(new Vector2(width, height), null, compressRatio);
  85581. } else {
  85582. //直接渲染 会改变canvas大小
  85583. var canvas = viewerMaster.renderer.domElement;
  85584. //canvas.width = width, canvas.height = height //不需要改canvas大小, 只需要 this.renderer.setSize(width, height ); 前面updateScreenSize已经执行
  85585. yield viewerMaster.render({
  85586. screenshot: true,
  85587. width,
  85588. height,
  85589. resize: true,
  85590. needWaitLoadPoint: !!info.splitRenderInfo,
  85591. maxTimeForPointLoad: info.maxTimeForPointLoad
  85592. }); //需要resize
  85593. /* if(info.type.includes('prism2d')){//o.map要为true
  85594. viewer.dispatchEvent({type:'resize', viewport:viewer.mapViewer.viewports[0]}) //借用viewer通知lineMaterial resize
  85595. viewerMaster.renderOverlay()
  85596. } */
  85597. var dataUrl = canvas.toDataURL('image/png', compressRatio);
  85598. }
  85599. return dataUrl;
  85600. });
  85601. return function render() {
  85602. return _ref3.apply(this, arguments);
  85603. };
  85604. }();
  85605. var dataUrl;
  85606. if (info.splitRenderInfo) {
  85607. //为了防崩溃,分区域批次渲染
  85608. var {
  85609. wc,
  85610. hc
  85611. } = info.splitRenderInfo;
  85612. var camera = viewer.mainViewport.camera;
  85613. var dataUrls = [];
  85614. var width_ = Math.ceil(1 / wc * width),
  85615. height_ = Math.ceil(1 / hc * height); //可能加起来比原图大,没事到时候边界会重合
  85616. viewer.updateScreenSize({
  85617. forceUpdateSize: true,
  85618. width: width_,
  85619. height: height_,
  85620. forTarget: info.useRenderTarget
  85621. }); //更新viewports相机透视 使focusOnObject在此窗口大小下
  85622. for (var i = 0; i < wc; i++) {
  85623. var col = [];
  85624. for (var j = 0; j < hc; j++) {
  85625. var left = Math.ceil((-wc / 2 + 0.5 + i) * width_),
  85626. top = Math.ceil((-hc / 2 + 0.5 + j) * height_);
  85627. camera.setViewOffset(width_, height_, left, top, width_, height_); //顺序从上到下从左到右
  85628. var _dataUrl = yield render();
  85629. //Common.downloadFile(dataUrl, 'screenshot'+ i+':'+j+'.png')
  85630. col.push({
  85631. dataUrl: _dataUrl,
  85632. width: width_,
  85633. height: height_
  85634. });
  85635. }
  85636. dataUrls.push(col);
  85637. }
  85638. camera.clearViewOffset();
  85639. dataUrl = yield Utils.combineImgs(dataUrls, compressRatio, width, height);
  85640. } else {
  85641. dataUrl = yield render();
  85642. }
  85643. if (info.splitRenderInfo) {
  85644. viewer.viewports = [viewer.mainViewport];
  85645. }
  85646. if (!Potree.settings.isOfficial) {
  85647. Common.downloadFile(dataUrl, 'screenshot.png');
  85648. }
  85649. var finish = () => {
  85650. oldStates.viewports.forEach(old => {
  85651. //恢复相机
  85652. var viewport = viewports.find(v => v.name == old.name);
  85653. viewport.left = old.left;
  85654. viewport.bottom = old.bottom;
  85655. viewport.width = old.width;
  85656. viewport.height = old.height;
  85657. viewport.view.copy(old.view);
  85658. //viewport.view.applyToCamera(viewport.camera);
  85659. if (viewport.camera.isOrthographicCamera) {
  85660. viewport.camera.zoom = viewport.view.zoom;
  85661. }
  85662. });
  85663. viewerMaster.updateScreenSize({
  85664. forceUpdateSize: true
  85665. }); //更新像素
  85666. /* oldStates.viewports.forEach(old=>{//恢复相机
  85667. var viewport = [mapViewport, mainViewport].find(v=>v.name == old.name);
  85668. this.dispatchEvent({ //update map
  85669. type: "camera_changed",
  85670. camera: viewport.camera,
  85671. viewport : viewport
  85672. })
  85673. }) */
  85674. updateCamera();
  85675. finishDeferred.resolve({
  85676. dataUrl,
  85677. pose
  85678. });
  85679. info.map || setTimeout(() => {
  85680. if (!_this5.screenshoting) {
  85681. //Potree.settings.pointNoLimit = false
  85682. Potree.settings.pointDensity = 'high';
  85683. //console.warn('恢复pointDensity')
  85684. /* if(viewer.scene.pointclouds[0].material.oldSize_ ){
  85685. viewer.scene.pointclouds[0].material.size = viewer.scene.pointclouds[0].material.oldSize_
  85686. viewer.scene.pointclouds[0].material.oldSize_ = null
  85687. } */
  85688. }
  85689. }, 500); //延迟:避免连续多次截图时释放点云
  85690. _this5.screenshoting = false;
  85691. console.log('screenshot done: ' + startTime, 'costTime', Date.now() - startTime + 'ms');
  85692. };
  85693. {
  85694. //恢复:
  85695. _this5.backgroundOpacity = oldStates.bgOpacity;
  85696. _this5.background = oldStates.background;
  85697. _this5.pauseTestMaxLevel = false;
  85698. oldStates.displayMode && (Potree.settings.displayMode = oldStates.displayMode);
  85699. if (info.type == 'measure' || info.type.includes('prism2d')) {
  85700. _this5.modules.SiteModel.pauseUpdateEntity = false;
  85701. _this5.focusDatasets = null;
  85702. _this5.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', true));
  85703. info.type == 'measure' && info.measurement.setSelected(false, 'screenshot');
  85704. }
  85705. if (info.type.includes('prism2d')) {
  85706. //viewer.mapViewer.transparentBG = false;
  85707. (info.prisms || [info.prism]).forEach(prism => {
  85708. prism.changeStyleForScreenshot(false);
  85709. if (info.type == 'prism2d-single') {
  85710. prism.baseModel && (Potree.Utils.updateVisible(prism.baseModel, 'screenshot', false, 3, 'cancel'), Potree.Utils.setObjectLayers(prism.baseModel, 'model'));
  85711. prism.setEditState(false);
  85712. }
  85713. });
  85714. }
  85715. _this5.images360.panos.forEach(pano => {
  85716. Potree.Utils.updateVisible(pano, 'screenshot', true);
  85717. });
  85718. Potree.Utils.updateVisible(_this5.reticule, 'screenshot', true);
  85719. if (useMap) {
  85720. Potree.Utils.updateVisible(_this5.mapViewer.cursor, 'screenshot', true);
  85721. if (oldStates.attachedToViewer != _this5.mapViewer.attachedToViewer) {
  85722. _this5.mapViewer.attachToMainViewer(!!oldStates.attachedToViewer);
  85723. }
  85724. if (oldStates.attachedToViewer && _this5.mapViewer.splitDir != oldStates.oldSplitDir) {
  85725. _this5.mapViewer.changeSplitScreenDir(oldStates.oldSplitDir);
  85726. }
  85727. mapViewport.noPointcloud = oldStates.noPointcloud;
  85728. Potree.Utils.updateVisible(viewer.mapViewer.mapLayer.sceneGroup, 'screenshot-prism', true);
  85729. }
  85730. var recover = () => {
  85731. if (Potree.settings.displayMode == 'showPanos') {
  85732. viewer.images360.flyToPano({
  85733. pano: oldStates.pano,
  85734. duration: 0,
  85735. callback: () => {
  85736. finish();
  85737. }
  85738. });
  85739. } else {
  85740. finish();
  85741. }
  85742. };
  85743. if (info.ifGetPose) {
  85744. Potree.sdk.scene.getPose().done(pose_ => {
  85745. pose = pose_;
  85746. getImageDeferred.resolve({
  85747. dataUrl,
  85748. pose
  85749. });
  85750. recover();
  85751. });
  85752. } else {
  85753. recover();
  85754. }
  85755. }
  85756. });
  85757. return function screenshot() {
  85758. return _ref2.apply(this, arguments);
  85759. };
  85760. }(); // screenshot end
  85761. var mapViewport;
  85762. var mainViewport = this.mainViewport;
  85763. var viewports = [],
  85764. oldStates = {
  85765. viewports: [],
  85766. pano: Potree.settings.displayMode == 'showPanos' ? viewer.images360.currentPano : null,
  85767. bgOpacity: this.backgroundOpacity,
  85768. background: this.background
  85769. };
  85770. if (!info.type.includes('prism2d')) {
  85771. viewports.push(mainViewport);
  85772. mainViewport.camera.isOrthographicCamera && (mainViewport.view.zoom = mainViewport.camera.zoom);
  85773. oldStates.viewports.push(mainViewport.clone());
  85774. }
  85775. if (useMap) {
  85776. mapViewport = this.mapViewer.viewports[0];
  85777. mapViewport.view.zoom = mapViewport.camera.zoom;
  85778. viewports.push(mapViewport);
  85779. oldStates.viewports.push(mapViewport.clone());
  85780. oldStates.attachedToViewer = this.mapViewer.attachedToViewer;
  85781. oldStates.noPointcloud = mapViewport.noPointcloud;
  85782. oldStates.displayMode = Potree.settings.displayMode;
  85783. Potree.Utils.updateVisible(this.mapViewer.cursor, 'screenshot', false); //令mapCursor不可见
  85784. }
  85785. viewports.forEach(e => e.active = false); //暂停渲染
  85786. if (info.hideMarkers) {
  85787. this.images360.panos.forEach(pano => {
  85788. //令漫游点不可见
  85789. Potree.Utils.updateVisible(pano, 'screenshot', false);
  85790. });
  85791. }
  85792. Potree.Utils.updateVisible(this.reticule, 'screenshot', false); //令reticule不可见
  85793. if (info.bgOpacity != void 0) {
  85794. this.backgroundOpacity = info.bgOpacity;
  85795. }
  85796. if (info.background != void 0) {
  85797. this.background = info.background;
  85798. }
  85799. Potree.settings.pointDensity = info.pointDensity || 'screenshot';
  85800. var focusDatasets = measurements => {
  85801. this.focusDatasets = [];
  85802. measurements.forEach(measure => {
  85803. measure.points_datasets.forEach(e => {
  85804. var p = viewer.scene.pointclouds.find(a => a.dataset_id == e);
  85805. if (p && !this.focusDatasets.includes(p)) {
  85806. this.focusDatasets.push(p);
  85807. }
  85808. });
  85809. });
  85810. this.updateFpVisiDatasets();
  85811. };
  85812. if (info.type == 'measure') {
  85813. //要截图双屏
  85814. this.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', e == info.measurement));
  85815. info.measurement.setSelected(true, 'screenshot');
  85816. //因为分屏后位置才最终确定,才能确定是否显示出floorplan所以先分屏
  85817. if (Potree.settings.floorplanEnable) {
  85818. oldStates.oldSplitDir = this.mapViewer.splitDir;
  85819. this.mapViewer.attachToMainViewer(true, 'measure', 0.5, {
  85820. dir: 'leftRight'
  85821. });
  85822. }
  85823. viewer.updateScreenSize({
  85824. forceUpdateSize: true,
  85825. width,
  85826. height,
  85827. forTarget: info.useRenderTarget
  85828. }); //更新viewports相机透视 使focusOnObject在此窗口大小下
  85829. var begin = () => {
  85830. useMap = this.mapViewer.attachedToViewer;
  85831. updateCamera();
  85832. if (useMap) {
  85833. var waitMap = () => {
  85834. console.log('waitMap: ' + startTime, Date.now(), this.mapViewer.mapLayer.loadingInProgress);
  85835. this.mapViewer.waitLoadDone(screenshot.bind(this)); //等待地图所有加载完
  85836. };
  85837. this.waitPointLoad(waitMap, info.maxTimeForPointLoad);
  85838. } else {
  85839. this.waitPointLoad(screenshot, info.maxTimeForPointLoad);
  85840. }
  85841. };
  85842. var {
  85843. promise
  85844. } = this.focusOnObject(info.measurement, 'measure', 0, {
  85845. basePanoSize: 1024,
  85846. gotoBestView: true
  85847. //minMapWidth: THREE.Math.clamp(Math.min(viewer.bound.boundSize.x, viewer.bound.boundSize.y) / (20/* this.mapViewer.mapLayer.maps.find(e=>e.name == 'map').disabled ? 6 : 3*/), 2, 25) //有地图的话为了显示出名字需要更大范围
  85848. }); //注意:不同角度截图 得到三维的会不一样,因为focusOnObject是根据方向的
  85849. promise.done(() => {
  85850. //console.log('promise.done')
  85851. //根据当前位置更新floorplan显示
  85852. //console.log('view Pos ', this.mainViewport.view.position.toArray())
  85853. this.updateDatasetAt(true);
  85854. this.modules.SiteModel.updateEntityAt(true, {
  85855. measure: info.measurement
  85856. }); //更新测量线所在楼层,展示俯视图
  85857. if (!this.modules.SiteModel.inEntity) {
  85858. focusDatasets([info.measurement]);
  85859. }
  85860. this.modules.SiteModel.pauseUpdateEntity = true;
  85861. //console.log('currentFloor', this.modules.SiteModel.currentFloor, 'currentDataset', this.atDatasets )
  85862. var floorplanShowed = this.mapViewer.mapLayer.maps.some(e => e.name.includes('floorplan') && e.objectGroup.visible); //如果没有floorplan展示就不分屏(如果focus时飞出数据集从而不展示怎么办。尤其是俯瞰比较长的线时容易这样,或许要根据其所在数据集强制显示)
  85863. if (!floorplanShowed && this.mapViewer.attachedToViewer) {
  85864. this.mapViewer.attachToMainViewer(false); //取消分屏
  85865. viewer.updateScreenSize({
  85866. forceUpdateSize: true,
  85867. width,
  85868. height,
  85869. forTarget: info.useRenderTarget
  85870. }); //更新viewports相机透视
  85871. var {
  85872. promise: _promise
  85873. } = this.focusOnObject(info.measurement, 'measure', 0, {
  85874. basePanoSize: 1024,
  85875. gotoBestView: true
  85876. }); //因画面比例更改,重新focus
  85877. _promise.done(() => {
  85878. begin();
  85879. });
  85880. } else {
  85881. begin();
  85882. }
  85883. });
  85884. } else if (info.type.includes('prism2d')) {
  85885. var points = [],
  85886. prisms = info.type == 'prism2d-all' ? info.prisms : [info.prism];
  85887. this.mapViewer.attachToMainViewer(true, 'screenshot', 1, {/* dir:'leftRight' */});
  85888. viewer.updateScreenSize({
  85889. forceUpdateSize: true,
  85890. width,
  85891. height,
  85892. forTarget: info.useRenderTarget
  85893. }); //更新viewports相机透视 使focusOnObject在此窗口大小下
  85894. prisms.forEach(prism => {
  85895. points.push(...prism.points);
  85896. prism.setSelected(false);
  85897. prism.changeStyleForScreenshot(true, {
  85898. hideLabel: info.type != 'prism2d-all',
  85899. showName: info.type == 'prism2d-all'
  85900. });
  85901. if (info.type == 'prism2d-single') {
  85902. prism.baseModel && (Potree.Utils.updateVisible(prism.baseModel, 'screenshot', true, 3, 'add'), Potree.Utils.setObjectLayers(prism.baseModel, 'bothMapAndScene'));
  85903. prism.setEditState(true);
  85904. }
  85905. });
  85906. this.scene.measurements.forEach(e => Potree.Utils.updateVisible(e, 'screenshot', prisms.includes(e)));
  85907. this.backgroundOpacity = 0;
  85908. var {
  85909. promise: _promise2
  85910. } = this.focusOnObject({
  85911. points
  85912. }, 'prisms2d', 0, {
  85913. minMapWidth: 0.5,
  85914. onlyMap: true,
  85915. focusBoundCenter: true,
  85916. boundExpandRatio: 1.4
  85917. });
  85918. _promise2.done(() => {
  85919. updateCamera();
  85920. if (info.type == 'prism2d-all') {
  85921. //全部 带平面图
  85922. focusDatasets(prisms); //更新平面图 可能有漏洞,当不在任何一个数据集内的话?
  85923. this.mapViewer.waitLoadDone(screenshot.bind(this)); //等待地图所有加载完
  85924. } else {
  85925. //single
  85926. mapViewport.noPointcloud = false; //显示点云,而非平面图
  85927. Potree.settings.displayMode = 'showPointCloud';
  85928. Potree.Utils.updateVisible(viewer.mapViewer.mapLayer.sceneGroup, 'screenshot-prism', false);
  85929. this.waitPointLoad(screenshot, 5000);
  85930. }
  85931. });
  85932. } else {
  85933. //default
  85934. var done = () => {
  85935. updateCamera();
  85936. if (info.splitRenderInfo) {
  85937. screenshot();
  85938. } else {
  85939. this.waitPointLoad(screenshot, info.maxTimeForPointLoad);
  85940. }
  85941. };
  85942. if (info.focusObjectInfo) {
  85943. viewer.updateScreenSize({
  85944. forceUpdateSize: true,
  85945. width,
  85946. height,
  85947. forTarget: info.useRenderTarget
  85948. }); //更新viewports相机透视 使focusOnObject在此窗口大小下
  85949. var {
  85950. promise: _promise3
  85951. } = this.focusOnObject(...info.focusObjectInfo);
  85952. _promise3.done(() => {
  85953. done();
  85954. });
  85955. } else {
  85956. done();
  85957. }
  85958. }
  85959. /*
  85960. 测量线的截图因为要调用分屏的,会改变画面
  85961. 但是普通截图的话,不会改变画面
  85962. */
  85963. return {
  85964. getImagePromise: getImageDeferred.promise(),
  85965. finishPromise: finishDeferred.promise()
  85966. };
  85967. }
  85968. waitPointLoad(done, maxTimeForPointLoad) {
  85969. var _arguments3 = arguments;
  85970. return _asyncToGenerator(function* () {
  85971. var viewport = _arguments3.length > 2 && _arguments3[2] !== undefined ? _arguments3[2] : viewer.mainViewport;
  85972. var resolution = _arguments3.length > 3 ? _arguments3[3] : undefined;
  85973. return new Promise((resolve, reject) => {
  85974. var finish;
  85975. var dealDone = () => {
  85976. viewer.removeEventListener('update', update);
  85977. viewer.removeEventListener('overPointBudget', decreaseLevel);
  85978. finish || done && done();
  85979. finish = true;
  85980. resolve();
  85981. };
  85982. var decreaseLevel = e => {
  85983. //降点云level 但基本降完也不会再加载低等级的点云了,所以是否直接不降?即使质量不平均
  85984. if (e.restQueueSize < 10) return; //差不多完成了
  85985. var pointclouds = viewer.scene.pointclouds.filter(e => e.visibleNodes.length);
  85986. console.log('准备decreaseLevel, numVisiblePoints', e.numVisiblePoints, '最小numVisiblePoints占比', 1 / pointclouds.length);
  85987. pointclouds.forEach(pointcloud => {
  85988. var percent = pointcloud.numVisiblePoints / e.numVisiblePoints;
  85989. //console.log('numVisiblePoints占总比', pointcloud.dataset_id, percent )
  85990. if (percent < 1 / pointclouds.length) return;
  85991. var old = pointcloud.maxLevel;
  85992. var levels = pointcloud.visibleNodes.map(e => e.getLevel());
  85993. var actMaxLevel = Math.max.apply(null, levels); //实际加载到的最高的node level
  85994. pointcloud.maxLevel = actMaxLevel - 1;
  85995. console.warn(pointcloud.dataset_id, 'decreaseLevel,新maxLevel', actMaxLevel - 1, '原maxlevel', old);
  85996. });
  85997. };
  85998. /* if(Potree.settings.displayMode == 'showPointCloud'){
  85999. viewer.updateScreenSize({forceUpdateSize:true, width, height, forTarget:info.useRenderTarget})//需要先setSize才能加载范围内的点云
  86000. } */
  86001. //updateCamera()
  86002. //viewer.addEventListener('overPointBudget',decreaseLevel)
  86003. var update = () => {
  86004. //前提:已经禁止渲染,仅加载点云
  86005. var camera = viewport.forViewOffset ? viewport.forViewOffset.camera : viewport.camera;
  86006. Potree.updatePointClouds(viewer.scene.pointclouds, camera, resolution || viewport.resolution);
  86007. };
  86008. viewer.addEventListener('update', update);
  86009. update();
  86010. var maxTime = maxTimeForPointLoad || 2000;
  86011. document.hidden && (maxTime *= 6); //离开页面后会变成1秒1帧
  86012. setTimeout(() => {
  86013. if (Potree.pointsLoading && Potree.settings.displayMode == 'showPointCloud') {
  86014. //如果还在加载
  86015. viewer.addEventListener('pointsLoaded', () => {
  86016. //点云加载完时(不一定准确)
  86017. if (!finish) console.log('加载完毕', ' numVisiblePoints', Potree.numVisiblePoints);
  86018. dealDone();
  86019. }, {
  86020. once: true
  86021. });
  86022. var overTime = () => {
  86023. //超时不候(其实之后等待地图还会再加载几秒)
  86024. if (document.hidden) {
  86025. return setTimeout(overTime, maxTime);
  86026. }
  86027. if (!finish) console.warn('超时, numVisiblePoints', Potree.numVisiblePoints);
  86028. dealDone();
  86029. };
  86030. setTimeout(overTime, maxTime);
  86031. } else {
  86032. console.log('已经加载完,无需再加载点云 numVisiblePoints', Potree.numVisiblePoints);
  86033. dealDone();
  86034. }
  86035. }, 200); //先加载一段时间
  86036. });
  86037. })();
  86038. }
  86039. focusOnObject(object, type, duration) {
  86040. var o = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
  86041. //飞向热点、测量线等 。
  86042. //console.log('focusOnObject: ', object, type)
  86043. var deferred = o.deferred || $.Deferred();
  86044. var target = new Vector3(),
  86045. //相机focus的位置
  86046. position = new Vector3(),
  86047. //相机最终位置
  86048. dis; //相机距离目标
  86049. duration = duration == void 0 ? 1200 : duration;
  86050. var camera = o.endCamera || viewer.scene.getActiveCamera();
  86051. var cameraPos = camera.position.clone();
  86052. var boundSize;
  86053. if (o.dontChangeCamDir && (o.endYaw == void 0 || o.endPitch == void 0)) {
  86054. //在俯视时仅靠dir来算不准
  86055. o.endYaw = viewer.mainViewport.view.yaw;
  86056. o.endPitch = viewer.mainViewport.view.pitch;
  86057. }
  86058. var moveMap = done => {
  86059. if (this.mapViewer && !o.dontMoveMap) {
  86060. //console.log('mapFocusOn: '+target.toArray())
  86061. var minMapWidth = o.minMapWidth || 2; //截图的时候要显示的地图范围较大,为了显示出地区名字
  86062. var minBound = new Vector2(minMapWidth, minMapWidth); //针对垂直线,在地图上只有一个点
  86063. //原始的bound
  86064. var boundOri;
  86065. if (object.points) {
  86066. boundOri = new Box3();
  86067. object.points.forEach(e => {
  86068. boundOri.expandByPoint(e);
  86069. });
  86070. } else {
  86071. boundOri = object.boundingBox;
  86072. }
  86073. if (o.focusBoundCenter) {
  86074. boundOri.getCenter(target);
  86075. }
  86076. var boundSizeOri = boundOri.getSize(new Vector3());
  86077. var boundSizeMap = boundSizeOri.clone().multiplyScalar(o.boundExpandRatio || math.linearClamp(Math.max(boundSizeOri.x, boundSizeOri.y), [0.5, 30], [2.5, 1.2])); //为了能同时看清测量线和地图,当测量线较短时,扩大margin,防止地图过度放大
  86078. boundSizeMap.x = Math.max(minBound.x, boundSizeMap.x);
  86079. boundSizeMap.y = Math.max(minBound.y, boundSizeMap.y);
  86080. this.mapViewer.moveTo(target.clone(), boundSizeMap, duration, o.margin, null, done);
  86081. }
  86082. };
  86083. if (o.onlyMap) {
  86084. moveMap(() => {
  86085. deferred.resolve();
  86086. });
  86087. return {
  86088. promise: deferred.promise()
  86089. };
  86090. }
  86091. var getPosWithFullBound = (points, boundingBox, target, cameraPos) => {
  86092. //使boundingBox差不多占满屏幕时的相机到target的距离
  86093. // points 和 boundingBox 至少有一个
  86094. var scale;
  86095. if (o.dontChangeCamDir) {
  86096. var inv = camera.matrixWorldInverse;
  86097. } else {
  86098. var cameraTemp = camera.clone();
  86099. var view = viewer.mainViewport.view.clone();
  86100. view.position.copy(cameraPos);
  86101. view.lookAt(target);
  86102. if (o.endPitch != void 0) {
  86103. view.pitch = o.endPitch;
  86104. view.yaw = o.endYaw;
  86105. }
  86106. view.applyToCamera(cameraTemp);
  86107. //对镜头的bound
  86108. var inv = cameraTemp.matrixWorldInverse;
  86109. }
  86110. var bound = new Box3();
  86111. if (points) {
  86112. //使用points得到的bound更小 //如果points和boundingbox的差别较大,尤其使target和points中心不一致,那么points不一定会刚好在boundingbox内
  86113. points.forEach(e => {
  86114. var p = e.clone().applyMatrix4(inv);
  86115. bound.expandByPoint(p);
  86116. });
  86117. scale = 1.2;
  86118. } else {
  86119. bound = boundingBox.applyMatrix4(inv);
  86120. scale = 1; //0.9;
  86121. }
  86122. boundSize = bound.getSize(new Vector3());
  86123. if (o.boundScale) {
  86124. scale = o.boundScale;
  86125. }
  86126. {
  86127. boundSize.x *= scale; //稍微放大一些,不然会靠到屏幕边缘
  86128. boundSize.y *= scale;
  86129. var min = 0.0001;
  86130. boundSize.x = Math.max(min, boundSize.x);
  86131. boundSize.y = Math.max(min, boundSize.y);
  86132. }
  86133. if (camera.type == 'OrthographicCamera') {
  86134. dis = boundSize.length() / 2;
  86135. } else {
  86136. var aspect = boundSize.x / boundSize.y;
  86137. if (camera.aspect > aspect) {
  86138. //视野更宽则用bound的纵向来决定
  86139. dis = boundSize.y / 2 / Math.tan(MathUtils.degToRad(camera.fov / 2)) + boundSize.z / 2;
  86140. } else {
  86141. var hfov = cameraLight.getHFOVForCamera(camera, true);
  86142. dis = boundSize.x / 2 / Math.tan(hfov / 2) + boundSize.z / 2;
  86143. }
  86144. dis += camera.near;
  86145. }
  86146. dis = Math.max(0.1, dis);
  86147. //三个顶点以上的由于measure的中心不等于bound的中心,所以点会超出bound外。 且由于视椎近大远小,即使是两个点的,bound居中后线看上去仍旧不居中.
  86148. //获得相机最佳位置
  86149. var dir;
  86150. if (o.dontChangeCamDir) {
  86151. dir = viewer.mainViewport.view.direction.negate();
  86152. } else {
  86153. dir = new Vector3().subVectors(cameraPos, target).normalize();
  86154. }
  86155. if (o.dontLookUp && dir.z < 0) {
  86156. dir.negate();
  86157. }
  86158. position.copy(target).add(dir.multiplyScalar(dis));
  86159. if (false) {
  86160. //打开以检查box
  86161. if (!this.boundBox) {
  86162. //调试
  86163. this.boundBox = new Mesh(new BoxGeometry(1, 1, 1, 1));
  86164. this.boundBox.material.wireframe = true;
  86165. this.boundBox.up.set(0, 0, 1);
  86166. Potree.Utils.setObjectLayers(this.boundBox, 'sceneObjects');
  86167. this.scene.scene.add(this.boundBox);
  86168. }
  86169. this.boundBox.position.copy(target);
  86170. this.boundBox.scale.copy(boundSize);
  86171. this.boundBox.lookAt(position);
  86172. }
  86173. return position;
  86174. };
  86175. if (this.images360.flying) {
  86176. var f = () => {
  86177. this.focusOnObject(object, type, duration, $.extend(o, {
  86178. deferred
  86179. }));
  86180. this.images360.removeEventListener('cameraMoveDone', f);
  86181. };
  86182. this.images360.addEventListener('cameraMoveDone', f);
  86183. return {
  86184. promise: deferred.promise()
  86185. };
  86186. }
  86187. if (type == 'measure') {
  86188. if (object.points.length == 0) {
  86189. return {
  86190. promise: deferred.resolve()
  86191. };
  86192. }
  86193. target.copy(object.getCenter());
  86194. //试试改变位置(方向),直视测量线。能避免倾斜角度造成的非常不居中、以及看不到面的情况
  86195. if (o.gotoBestView) {
  86196. //直接沿着法线方向看
  86197. if (object.points.length > 2) {
  86198. var facePlane = object.getFacePlane(target);
  86199. var normal = facePlane.normal.clone();
  86200. if (normal.dot(this.mainViewport.view.direction) > 0) {
  86201. normal.negate(); //顺着视线
  86202. }
  86203. //normal.z = Math.max(0.2, normal.z)//尽量不要仰视
  86204. cameraPos.copy(target).add(normal);
  86205. } else {
  86206. var lineDir = new Vector3().subVectors(object.points[0], object.points[1]).normalize();
  86207. var _facePlane = new Plane().setFromNormalAndCoplanarPoint(lineDir, target);
  86208. //if(cameraPos.z < target.z + 1)cameraPos.z = target.z + 1//尽量不要仰视
  86209. var dir = new Vector3().subVectors(cameraPos, target).normalize();
  86210. dir.z = Math.max(dir.z, 0.4);
  86211. cameraPos.copy(target).add(dir); //尽量不要仰视
  86212. var _dis = cameraPos.distanceTo(target);
  86213. dir = lineDir.clone().multiplyScalar(_dis);
  86214. var line = new Line3().set(cameraPos.clone().add(dir), cameraPos.clone().add(dir.negate())); //过相机位置作到面的垂线
  86215. _facePlane.intersectLine(line, cameraPos); //得垂足,作为新的相机位置。就能在测量线中间看测量线
  86216. }
  86217. } else {
  86218. if (object.points.length > 2) {
  86219. var _facePlane2 = object.getFacePlane(target);
  86220. var _normal = _facePlane2.normal.clone();
  86221. var angle = this.mainViewport.view.direction.angleTo(_normal);
  86222. var minDiff = MathUtils.degToRad(60);
  86223. //console.log('angle',angle)
  86224. if (angle > minDiff && angle < Math.PI - minDiff) {
  86225. //当几乎正对时就不执行
  86226. if (angle < Math.PI / 2) {
  86227. //在背面
  86228. _normal.negate();
  86229. }
  86230. var _dir = new Vector3().subVectors(camera.position, target).normalize();
  86231. var newDir = new Vector3().addVectors(_dir, _normal); //两个角度的中间
  86232. cameraPos.copy(target.clone().add(newDir));
  86233. }
  86234. } else if (object.points.length == 2) {
  86235. //线段
  86236. var _lineDir = new Vector3().subVectors(object.points[0], object.points[1]).normalize();
  86237. var _angle = this.mainViewport.view.direction.angleTo(_lineDir);
  86238. var maxDiff = Math.PI * 0.25; // 45度
  86239. if (_angle < maxDiff || _angle > Math.PI - maxDiff) {
  86240. //当几乎正对时就不执行
  86241. if (_angle > Math.PI / 2) {
  86242. //令dir和lineDir成钝角
  86243. _lineDir.negate();
  86244. }
  86245. var _dir2 = new Vector3().subVectors(camera.position, target).normalize();
  86246. var mid = new Vector3().addVectors(_lineDir, _dir2).normalize(); //中间法向量(如果刚好dir和lineDir反向,那得到的为零向量,就不移动了,但一般不会酱紫吧)
  86247. var _newDir = new Vector3().addVectors(_dir2, mid);
  86248. cameraPos.copy(target.clone().add(_newDir));
  86249. }
  86250. } else {
  86251. console.error('measure 没有facePlane points点数还不为2?');
  86252. }
  86253. }
  86254. //截图时直接飞到最佳视角,也就是平视它所在面。其余时候为了避免镜头旋转过大就算了。
  86255. position = getPosWithFullBound(object.points, null, target, cameraPos);
  86256. moveMap();
  86257. if (Potree.settings.displayMode == 'showPointCloud') {
  86258. //点云
  86259. var minDis = 0.3;
  86260. if (0) {
  86261. //如果没有被选中,会被遮挡。 2023.11.15 最好展示全局(尤其截图时),虽然被遮挡,但focus的过程是选中状态全显示的,可以看出所在范围。
  86262. var checkIntersect = () => {
  86263. var intersect = this.inputHandler.ifBlockedByIntersect({
  86264. point: position,
  86265. cameraPos: target
  86266. }); // 不一定准确
  86267. if (intersect) {
  86268. var blockCount = 0,
  86269. unblockCount = 0,
  86270. visi;
  86271. for (var i = 0; i < object.points.length; i++) {
  86272. //如果顶点超过一半不可见,就要更改位置
  86273. var p = object.points[i];
  86274. var blocked = this.inputHandler.ifBlockedByIntersect({
  86275. point: p,
  86276. margin: 0.3,
  86277. cameraPos: position,
  86278. pickWindowSize: 4
  86279. });
  86280. if (blocked) {
  86281. blockCount++;
  86282. if (blockCount / object.points.length >= 0.5) {
  86283. visi = false;
  86284. break;
  86285. }
  86286. } else {
  86287. unblockCount++;
  86288. if (unblockCount / object.points.length > 0.5) {
  86289. visi = true;
  86290. break;
  86291. }
  86292. }
  86293. }
  86294. if (visi == void 0) {
  86295. visi = unblockCount / object.points.length > 0.5;
  86296. }
  86297. var shrink = () => {
  86298. var dir = new Vector3().subVectors(position, target).normalize().multiplyScalar(intersect.distance);
  86299. position.copy(target).add(dir);
  86300. console.log('checkIntersect newPos', position.clone());
  86301. };
  86302. if (!visi) {
  86303. //更改位置距离target如果小于最小距离,需要反向。 否则直接缩短距离。
  86304. if (intersect.distance < minDis) {
  86305. console.log('检测到intersect 反向', intersect.distance);
  86306. var position1 = position.clone();
  86307. var _dir3 = new Vector3().subVectors(position, target);
  86308. position.copy(target).sub(_dir3);
  86309. var intersect2 = this.inputHandler.ifBlockedByIntersect({
  86310. point: position,
  86311. cameraPos: target
  86312. }); // 不一定准确
  86313. if (intersect2) {
  86314. if (intersect2.distance < intersect.distance) {
  86315. position.copy(position1); //恢复
  86316. }
  86317. shrink();
  86318. }
  86319. } else {
  86320. shrink();
  86321. }
  86322. }
  86323. }
  86324. };
  86325. checkIntersect();
  86326. //多折线没有areaPlane 有时候会看向空白区域 - -
  86327. }
  86328. } else if (Potree.settings.displayMode == 'showPanos') {
  86329. //全景 (比较难校准)
  86330. var target2, _dir4;
  86331. if (object.measureType.includes('MulDistance')) {
  86332. //因为该线不闭合,可能看向target的方向会没有线,所以换一个target
  86333. target2 = object.points[Math.round(object.points.length / 2)]; //直接看向中间点
  86334. _dir4 = new Vector3().subVectors(target2, position).normalize();
  86335. }
  86336. var pano = viewer.images360.fitPanoTowardPoint({
  86337. /*point : target, //不使用目标点来判断是因为缺少measure角度的信息。比如虽然可以靠近线的中心,但是线朝向屏幕,那几乎就是一个点了。
  86338. //bestDistance : dis * 0.5, //乘以小数是为了尽量靠近
  86339. boundSphere: boundOri.getBoundingSphere(new THREE.Sphere), */
  86340. target,
  86341. dir: _dir4,
  86342. point: position,
  86343. bestDistance: 0,
  86344. checkIntersect: o.checkIntersect,
  86345. gotoBestView: o.gotoBestView
  86346. });
  86347. var result = {
  86348. promise: deferred.promise()
  86349. };
  86350. if (pano && pano.msg) {
  86351. pano = pano.pano;
  86352. result.msg = pano.msg;
  86353. }
  86354. if (pano) {
  86355. viewer.images360.flyToPano({
  86356. pano,
  86357. target: target2 || target,
  86358. duration,
  86359. deferred,
  86360. dontMoveMap: true,
  86361. basePanoSize: o.basePanoSize
  86362. }); //dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  86363. if (viewer.images360.currentPano == pano) {
  86364. var dis1 = viewer.images360.currentPano.position.distanceTo(target);
  86365. var dis2 = position.distanceTo(target);
  86366. //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2)
  86367. return {
  86368. msg: dis1 / dis2 > 1.5 && dis1 - dis2 > 10 ? 'tooFar' : 'posNoChange',
  86369. promise: deferred.promise()
  86370. };
  86371. }
  86372. }
  86373. return result;
  86374. /* if(viewer.images360.currentPano == pano){
  86375. let dis1 = viewer.images360.currentPano.position.distanceTo(target)
  86376. let dis2 = position.distanceTo(target)
  86377. //console.log('dis1 / dis2',dis1 / dis2, 'dis1-dis2', dis1-dis2)
  86378. return {msg: (dis1 / dis2 > 1.5 && dis1-dis2>10)? 'tooFar' : 'posNoChange', promise : deferred.promise() }
  86379. }else{
  86380. return {promise : deferred.promise()}
  86381. } */
  86382. //出现过到达位置后测量线标签闪烁的情况
  86383. // 测量线截图 全景 最好能放大. 但要确保该位置放大后图片加载完有点困难
  86384. }
  86385. } else if (type == 'tag' || type == 'point') {
  86386. //dimension = 1
  86387. target.copy(object.position);
  86388. var bestDistance = o.distance || 3;
  86389. if (!o.dontMoveMap && this.mapViewer) {
  86390. //console.log('mapFocusOn: '+target.toArray())
  86391. this.mapViewer.moveTo(target.clone(), null, duration);
  86392. }
  86393. if (Potree.settings.displayMode == 'showPointCloud') {
  86394. if (o.dontChangePos) {
  86395. position.copy(cameraPos);
  86396. } else {
  86397. dis = bestDistance;
  86398. var _dir5 = o.direction ? o.direction.clone().negate() : this.mainViewport.view.direction.negate(); // */new THREE.Vector3().subVectors(camera.position, target).normalize()
  86399. if (o.dontLookUp && _dir5.z < 0) _dir5.z *= -1;
  86400. position.copy(target).add(_dir5.multiplyScalar(dis));
  86401. }
  86402. if (o.sameFloor) {
  86403. //需要在同一楼层
  86404. var atFloor = this.modules.SiteModel.pointInWhichEntity(target, 'floor');
  86405. if (atFloor) {
  86406. var camFloor = this.modules.SiteModel.pointInWhichEntity(position, 'floor');
  86407. if (camFloor != atFloor) {
  86408. var raycaster = new Raycaster();
  86409. var origin = target;
  86410. var _dir6 = new Vector3().subVectors(position, target).normalize();
  86411. raycaster.set(origin, _dir6);
  86412. var intersect = Potree.Utils.getIntersect(null, [atFloor.box], null, raycaster);
  86413. if (intersect) {
  86414. var _dis2 = MathUtils.clamp(intersect.distance - 0.2, camera.near, intersect.distance);
  86415. position.addVectors(origin, _dir6.multiplyScalar(_dis2));
  86416. console.log('移动到楼层');
  86417. } else {
  86418. console.error('?no intersect?');
  86419. }
  86420. }
  86421. }
  86422. }
  86423. if (o.checkIntersect) {
  86424. //识别被点云遮住的话
  86425. var _intersect; //反向查找从target到相机的第一个intersect
  86426. _intersect = this.inputHandler.ifBlockedByIntersect({
  86427. point: position,
  86428. margin: 0,
  86429. cameraPos: target
  86430. } /* {point:target, margin: 0.2, cameraPos:position} */);
  86431. if (_intersect) {
  86432. position.copy(_intersect.location);
  86433. console.log('移近');
  86434. }
  86435. }
  86436. } else if (Potree.settings.displayMode == 'showPanos') {
  86437. var _pano = viewer.images360.fitPanoTowardPoint({
  86438. point: target,
  86439. dir: this.mainViewport.view.direction,
  86440. //尽量不改相机方向,避免镜头晃动
  86441. checkIntersect: o.checkIntersect,
  86442. sameFloor: o.sameFloor,
  86443. bestDistance,
  86444. maxDis: o.maxDis //越近越好,但不要太近,bestDistance左右差不多
  86445. });
  86446. var _result = {
  86447. promise: deferred.promise()
  86448. };
  86449. if (_pano && _pano.msg) {
  86450. _pano = _pano.pano;
  86451. _result.msg = _pano.msg;
  86452. }
  86453. _pano && viewer.images360.flyToPano({
  86454. pano: _pano,
  86455. target,
  86456. duration,
  86457. deferred,
  86458. dontMoveMap: true,
  86459. basePanoSize: o.basePanoSize
  86460. });
  86461. return _result;
  86462. }
  86463. } else if (object.boundingBox && type == 'boundingBox') {
  86464. //使屏幕刚好看全boundingBox
  86465. target = object.boundingBox.getCenter(new Vector3());
  86466. if (o.dir) {
  86467. //指定方向
  86468. cameraPos.copy(target).sub(o.dir);
  86469. }
  86470. position = getPosWithFullBound(object.points, object.boundingBox.clone(), target, cameraPos);
  86471. if (Potree.settings.displayMode == 'showPanos') {
  86472. //全景 (比较难校准)
  86473. var _pano2 = viewer.images360.fitPanoTowardPoint({
  86474. point: position,
  86475. bestDistance: 0
  86476. });
  86477. var _result2 = {
  86478. promise: deferred.promise()
  86479. };
  86480. if (_pano2 && _pano2.msg) {
  86481. _pano2 = _pano2.pano;
  86482. _result2.msg = _pano2.msg;
  86483. }
  86484. _pano2 && viewer.images360.flyToPano({
  86485. pano: _pano2,
  86486. target,
  86487. duration,
  86488. deferred,
  86489. dontMoveMap: true,
  86490. basePanoSize: o.basePanoSize
  86491. }); //dontMoveMap不要移动map,否则flytopano会自动在map中focus到漫游点的位置,而非测量线了
  86492. if (!_pano2) {
  86493. console.error('no pano');
  86494. }
  86495. return _result2;
  86496. //出现过到达位置后测量线标签闪烁的情况
  86497. } else {
  86498. /* if(o.dontChangeCamDir){
  86499. target = null
  86500. } */
  86501. moveMap();
  86502. }
  86503. }
  86504. if (o.startCamera && o.endCamera) {
  86505. viewer.mainViewport.view.tranCamera(this.mainViewport, {
  86506. endPosition: position,
  86507. target,
  86508. boundSize,
  86509. callback: () => {
  86510. //console.log('focusOnObjectSuccess: '+object.name, type)
  86511. deferred.resolve();
  86512. },
  86513. startCamera: o.startCamera,
  86514. endCamera: o.endCamera,
  86515. midCamera: this.scene.cameraBasic,
  86516. endYaw: o.endYaw,
  86517. endPitch: o.endPitch
  86518. }, duration);
  86519. } else if (camera.type == "OrthographicCamera") {
  86520. viewer.mainViewport.view.moveOrthoCamera(this.mainViewport, {
  86521. endPosition: position,
  86522. target,
  86523. boundSize,
  86524. endYaw: o.endYaw,
  86525. endPitch: o.endPitch,
  86526. callback: () => {
  86527. //console.log('focusOnObjectSuccess: '+object.name, type)
  86528. deferred.resolve();
  86529. }
  86530. }, duration);
  86531. } else {
  86532. viewer.mainViewport.view.setView({
  86533. position,
  86534. target,
  86535. duration,
  86536. endYaw: o.endYaw,
  86537. endPitch: o.endPitch,
  86538. callback: () => {
  86539. //console.log('focusOnObjectSuccess: '+object.name, type)
  86540. deferred.resolve();
  86541. }
  86542. });
  86543. }
  86544. this.dispatchEvent({
  86545. type: 'focusOnObject',
  86546. CamTarget: target,
  86547. position
  86548. }); //给controls发送信息
  86549. return {
  86550. promise: deferred.promise()
  86551. };
  86552. }
  86553. flyToDataset() {
  86554. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  86555. var pointcloud;
  86556. if (o instanceof Object3D) pointcloud = o;else if (o.pointcloud) pointcloud = o.pointcloud;else pointcloud = this.scene.pointclouds.find(p => p.dataset_id == o.id);
  86557. var duration = o.duration == void 0 ? 1000 : o.duration;
  86558. if (o.focusOnPoint || !pointcloud.panosBound) {
  86559. //focus点云上一点,避免center区域刚好没有点
  86560. if (pointcloud.root.geometryNode) {
  86561. var posArr = pointcloud.root.geometryNode.geometry.attributes.position.array;
  86562. var count = pointcloud.root.geometryNode.geometry.attributes.position.count;
  86563. var index = Math.ceil(count / 2); //随便取一个点
  86564. var point = new Vector3(posArr[index * 3 + 0], posArr[index * 3 + 1], posArr[index * 3 + 2]);
  86565. //point.applyMatrix4(pointcloud.root.pointcloud.matrixWorld)
  86566. point.applyMatrix4(pointcloud.root.sceneNode.matrixWorld);
  86567. viewer.focusOnObject({
  86568. position: point
  86569. }, 'point', duration, {
  86570. dontChangeCamDir: true,
  86571. distance: 15
  86572. });
  86573. o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration);
  86574. console.log('flyToDataset focusOnPoint done');
  86575. return;
  86576. }
  86577. }
  86578. var center = pointcloud.bound.getCenter(new Vector3());
  86579. var position;
  86580. var getPano = () => {
  86581. //获取离中心最近的pano
  86582. var request = [];
  86583. var rank = [Images360.scoreFunctions.distanceSquared({
  86584. position: center
  86585. })];
  86586. var r = Common.sortByScore(pointcloud.panos, request, rank);
  86587. if (r.length) {
  86588. return r[0].item;
  86589. }
  86590. };
  86591. if (Potree.settings.displayMode == 'showPanos') {
  86592. var pano = getPano();
  86593. if (pano) {
  86594. if (pano == this.images360.currentPano) return 'posNoChange';
  86595. this.images360.flyToPano({
  86596. pano
  86597. });
  86598. } else return false;
  86599. } else {
  86600. var target;
  86601. position = center;
  86602. if (pointcloud.panosBound) {
  86603. var panosCenter = pointcloud.panosBound.center; //pano集中的地方,也就是真正有点云的地方
  86604. position = panosCenter.clone();
  86605. /* let ratio = 0.2
  86606. position.z = center.z * ratio + panosCenter.z * (1-ratio) //因为panos一般比较低,为了不让相机朝下时看不到点云,加一丢丢中心高度
  86607. */
  86608. var _pano3 = getPano();
  86609. if (_pano3) {
  86610. target = _pano3.position; //针对像隧道一样的场景, 中心点还是panosCenter都在没有点云的地方,所以还是看向其中一个漫游点好。
  86611. position.z = target.z; //水平, 避免朝上或朝下
  86612. }
  86613. }
  86614. if (this.modules.Clip.editing) {
  86615. position.z = center.z; //剪裁时在中心高度,因为以点云为重点
  86616. this.modules.Clip.bus.dispatchEvent({
  86617. type: 'flyToPos',
  86618. position,
  86619. duration
  86620. });
  86621. } else {
  86622. if (math.closeTo(position, this.images360.position)) return 'posNoChange';
  86623. viewer.mainViewport.view.setView({
  86624. position,
  86625. target,
  86626. duration
  86627. });
  86628. }
  86629. o.dontMoveMap || viewer.mapViewer.fitToPointcloud(pointcloud, duration);
  86630. }
  86631. return true;
  86632. }
  86633. findClosestDatasetOnMap(position) {
  86634. //寻找当前平面图上离某点最近的数据集
  86635. var pointclouds = viewer.scene.pointclouds.filter(e => e.visible);
  86636. var addScore = viewer.bound.boundSize.length();
  86637. var r = Potree.Common.sortByScore(pointclouds, [], [e => {
  86638. //pos2d和bound2d距离排序
  86639. var pos3d = position.clone().setZ(e.panosBound ? e.panosBound.center.z : (e.bound.min.z + e.bound.max.z) / 2);
  86640. return -(e.panosBound ? e.panosBound.bounding : e.bound).distanceToPoint(pos3d);
  86641. }, e => {
  86642. //最有可能的是地图上显示的平面图
  86643. return e in viewer.fpVisiDatasets ? addScore : 0;
  86644. }]);
  86645. return r[0] && r[0].item;
  86646. }
  86647. addTimeMark(name, type) {
  86648. var record = Potree.timeCollect[name];
  86649. var needRecord = record && record.start && record.measures.length < record.minCount;
  86650. if (needRecord || Potree.measureTimings) {
  86651. performance.mark(name + "-" + type);
  86652. if (type == 'end') {
  86653. var measure = performance.measure(name, name + "-start", name + "-end");
  86654. if (needRecord) {
  86655. record.measures.push(measure.duration);
  86656. record.sum += measure.duration;
  86657. record.ave = record.sum / record.measures.length;
  86658. record.measures.sort((a, b) => a - b);
  86659. record.median = record.measures[parseInt(record.measures.length / 2)];
  86660. }
  86661. }
  86662. }
  86663. }
  86664. addFakeMeasure(name, duration) {
  86665. //把一些count当做duration来统计
  86666. if (!Potree.measureTimings) return;
  86667. if (!this.fakeMeasure[name]) {
  86668. this.fakeMeasure[name] = [];
  86669. }
  86670. var object = {
  86671. name,
  86672. duration
  86673. };
  86674. this.fakeMeasure[name].push(object);
  86675. }
  86676. resolveTimings(timestamp, log) {
  86677. //打印用时。 注:performance手机的精度只到整数位 。 sidebar中监听update时有高cpu的函数所以不要用demo测
  86678. if (!this.toggle) {
  86679. this.toggle = timestamp;
  86680. }
  86681. var duration = timestamp - this.toggle;
  86682. if (duration > 1000.0) {
  86683. if (log) {
  86684. var measures = performance.getEntriesByType("measure");
  86685. for (var i in this.fakeMeasure) {
  86686. measures.push(...this.fakeMeasure[i]);
  86687. }
  86688. var names = new Set();
  86689. for (var measure of measures) {
  86690. names.add(measure.name);
  86691. }
  86692. var groups = new Map();
  86693. for (var name of names) {
  86694. groups.set(name, {
  86695. measures: [],
  86696. sum: 0,
  86697. n: 0,
  86698. min: Infinity,
  86699. max: -Infinity
  86700. });
  86701. }
  86702. for (var _measure of measures) {
  86703. var group = groups.get(_measure.name);
  86704. group.measures.push(_measure);
  86705. group.sum += _measure.duration;
  86706. group.n++;
  86707. group.min = Math.min(group.min, _measure.duration);
  86708. group.max = Math.max(group.max, _measure.duration);
  86709. }
  86710. /* let glQueries = Potree.resolveQueries(this.renderer.getContext()); // resolveQueries 无
  86711. for(let [key, value] of glQueries){
  86712. let group = {
  86713. measures: value.map(v => {return {duration: v}}),
  86714. sum: value.reduce( (a, i) => a + i, 0),
  86715. n: value.length,
  86716. min: Math.min(...value),
  86717. max: Math.max(...value)
  86718. };
  86719. let groupname = `[tq] ${key}`;
  86720. groups.set(groupname, group);
  86721. names.add(groupname);
  86722. } */
  86723. for (var [_name, _group] of groups) {
  86724. _group.mean = _group.sum / _group.n;
  86725. /* group.measures.sort( (a, b) => a.duration - b.duration );
  86726. if(group.n === 1){
  86727. group.median = group.measures[0].duration;
  86728. }else if(group.n > 1){
  86729. group.median = group.measures[parseInt(group.n / 2)].duration;
  86730. }
  86731. */
  86732. var _measures = _group.measures.slice();
  86733. _measures.sort((a, b) => a.duration - b.duration);
  86734. if (_group.n === 1) {
  86735. _group.median = _measures[0].duration;
  86736. } else if (_group.n > 1) {
  86737. _group.median = _measures[parseInt(_group.n / 2)].duration;
  86738. }
  86739. }
  86740. var cn = Array.from(names).reduce((a, i) => Math.max(a, i.length), 0) + 5;
  86741. var cmin = 6;
  86742. var cmed = 6;
  86743. var cmax = 6;
  86744. var csam = 4;
  86745. var message = " ".concat("NAME".padEnd(cn), " |") + " ".concat("MIN".padStart(cmin), " |") + " ".concat("MEDIAN".padStart(cmed), " |") + " ".concat("MAX".padStart(cmax), " |") + " ".concat("AVE".padStart(cmax), " |") + " ".concat("SAMPLES".padStart(csam), " \n");
  86746. message += " ".concat("-".repeat(message.length), "\n");
  86747. names = Array.from(names).sort();
  86748. for (var _name2 of names) {
  86749. var _group2 = groups.get(_name2);
  86750. var min = _group2.min.toFixed(3);
  86751. var median = _group2.median.toFixed(3);
  86752. var max = _group2.max.toFixed(3);
  86753. var ave = _group2.mean.toFixed(3); //add
  86754. var n = _group2.n;
  86755. message += " ".concat(_name2.padEnd(cn), " |") + " ".concat(min.padStart(cmin), " |") + " ".concat(median.padStart(cmed), " |") + " ".concat(max.padStart(cmax), " |") + " ".concat(ave.padStart(cmax), " |") + " ".concat(n.toString().padStart(csam), "\n");
  86756. }
  86757. message += "\n";
  86758. console.log(message);
  86759. }
  86760. this.fakeMeasure = {}; //clear
  86761. performance.clearMarks();
  86762. performance.clearMeasures();
  86763. this.toggle = timestamp;
  86764. }
  86765. //注意,console.log本身用时挺高,降4倍时可能占用0.5毫秒,所以不能每帧都打印
  86766. }
  86767. loop(timestamp) {
  86768. //let startTime = performance.now()
  86769. //console.log('间隔:' /*, parseInt((startTime - this.lastEndTime)*100 )/100 */)
  86770. if (this.paused) return;
  86771. if (performance.getEntriesByName("loopWaitNext-start").length) viewer.addTimeMark('loopWaitNext', 'end');
  86772. if (this.stats) {
  86773. this.stats.begin();
  86774. }
  86775. performance.mark('loop-start'); // 无论有没有reportTimings都要获取,因为getBestCound需要
  86776. this.dispatchEvent('loopStart');
  86777. this.interacted = false;
  86778. this.shelterCount = {
  86779. byTex: 0,
  86780. byCloud: 0,
  86781. maxByTex: 100,
  86782. maxByCloud: 0
  86783. }; //清空 因ifPointBlockedByIntersect可能在任何时候触发,所以需要一开始就定义这个,且每次计算最大可计算次数太麻烦了就定义一个吧。
  86784. var deltaTime = this.clock.getDelta();
  86785. this.update(deltaTime, timestamp);
  86786. this.magnifier.render();
  86787. this.render();
  86788. this.objs.children.forEach(e => {
  86789. if (e.fileType == '3dTiles') {
  86790. e.traverse(child => {
  86791. if (child.runtime) {
  86792. child.runtime.update(deltaTime, this.renderer, this.mainViewport.camera);
  86793. return {
  86794. stopContinue: true
  86795. };
  86796. }
  86797. });
  86798. }
  86799. });
  86800. // let vrActive = viewer.renderer.xr.isPresenting;
  86801. // if(vrActive){
  86802. // this.update(this.clock.getDelta(), timestamp);
  86803. // this.render();
  86804. // }else{
  86805. // this.update(this.clock.getDelta(), timestamp);
  86806. // this.render();
  86807. // }
  86808. Potree.framenumber++;
  86809. //-------------
  86810. this.images360.tileDownloader.update();
  86811. this.images360.panoRenderer.update();
  86812. this.images360.getNeighbours(this.interacted);
  86813. this.computeShelter();
  86814. //-------------
  86815. if (this.stats) {
  86816. this.stats.end();
  86817. }
  86818. viewer.addTimeMark('loop', 'end');
  86819. viewer.addTimeMark('loopWaitNext', 'start');
  86820. this.resolveTimings(timestamp, Potree.measureTimings);
  86821. //Potree.measureTimings = 1
  86822. }
  86823. postError(content) {
  86824. var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  86825. var message = this.postMessage(content, params);
  86826. message.element.addClass("potree_message_error");
  86827. return message;
  86828. }
  86829. postMessage(content) {
  86830. var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  86831. var message = new Message(content);
  86832. var animationDuration = 100;
  86833. message.element.css("display", "none");
  86834. message.elClose.click(() => {
  86835. message.element.slideToggle(animationDuration);
  86836. var index = this.messages.indexOf(message);
  86837. if (index >= 0) {
  86838. this.messages.splice(index, 1);
  86839. }
  86840. });
  86841. this.elMessages.prepend(message.element);
  86842. message.element.slideToggle(animationDuration);
  86843. this.messages.push(message);
  86844. if (params.duration !== undefined) {
  86845. var fadeDuration = 500;
  86846. var slideOutDuration = 200;
  86847. setTimeout(() => {
  86848. message.element.animate({
  86849. opacity: 0
  86850. }, fadeDuration);
  86851. message.element.slideToggle(slideOutDuration);
  86852. }, params.duration);
  86853. }
  86854. return message;
  86855. }
  86856. getBoundingBox(pointclouds) {
  86857. //可以直接返回viewer.bound
  86858. if (!this.bound) {
  86859. this.updateModelBound();
  86860. }
  86861. return this.bound.boundingBox.clone(); //this.scene.getBoundingBox(pointclouds);
  86862. }
  86863. updateModelBound(reason) {
  86864. this.boundNeedUpdate = false;
  86865. this.bound = Utils.computePointcloudsBound(this.scene.pointclouds.filter(pointcloud =>
  86866. //只求可见
  86867. pointcloud.visible || pointcloud.unvisibleReasons && pointcloud.unvisibleReasons.length == 1 && pointcloud.unvisibleReasons[0].reason == 'displayMode'));
  86868. if (Potree.settings.boundAddObjs) {
  86869. //加上obj的bound 需要确保都updateMatrixWorld过
  86870. this.objs.children.forEach(e => {
  86871. this.bound.boundingBox.union(e.boundingBox.clone().applyMatrix4(e.matrixWorld));
  86872. });
  86873. this.bound.boundingBox.getSize(this.bound.boundSize);
  86874. this.bound.boundingBox.getCenter(this.bound.center);
  86875. }
  86876. viewer.farWhenShowPano = this.bound.boundSize.length() * 10; //全景漫游时要能看到整个skybox 原本*2的但对于距离特远的数据集需要乘大一些否则会黑面
  86877. /* let boundPlane = new THREE.Box3()
  86878. boundPlane.expandByPoint(this.bound.boundingBox.min.clone())//最低高度为bound的最低
  86879. boundPlane.expandByPoint(this.bound.boundingBox.max.clone().setZ(this.bound.center.z))//最高高度为bound的中心高度
  86880. FirstPersonControls.boundPlane = boundPlane */
  86881. //FirstPersonControls.standardSpeed = THREE.Math.clamp( Math.sqrt(this.bound.boundSize.length() )/ 100 , 0.02,0.5); //在这个boundPlane中的速度
  86882. viewer.scene.pointclouds.forEach(e => {
  86883. //海拔范围
  86884. e.material.heightMin = this.bound.boundingBox.min.z;
  86885. e.material.heightMax = this.bound.boundingBox.max.z;
  86886. });
  86887. this.dispatchEvent({
  86888. type: 'updateModelBound'
  86889. });
  86890. }
  86891. waitForLoad(object, isLoadedCallback) {
  86892. //等待加载时显示loading。主要是贴图
  86893. this.waitQueue.push({
  86894. object,
  86895. isLoadedCallback
  86896. });
  86897. //console.warn('waitForLoad',object.id,this.waitQueue.length)
  86898. 1 === this.waitQueue.length && this.dispatchEvent({
  86899. type: "loading",
  86900. show: true
  86901. });
  86902. }
  86903. ifAllLoaded() {
  86904. if (this.waitQueue.length > 0) {
  86905. this.waitQueue = this.waitQueue.filter(function (e) {
  86906. return !e.isLoadedCallback();
  86907. });
  86908. }
  86909. //console.warn('ifAllLoaded', this.waitQueue.length)
  86910. 0 === this.waitQueue.length && this.dispatchEvent({
  86911. type: "loading",
  86912. show: false
  86913. });
  86914. }
  86915. cancelLoad(object) {
  86916. //add 突然出现还没加载完就被deactivateTiledPano但还在loading的情况,所以加了这个
  86917. this.waitQueue = this.waitQueue.filter(function (e) {
  86918. return e.object != object;
  86919. });
  86920. //console.log('cancelLoad', object.id)
  86921. this.ifAllLoaded();
  86922. }
  86923. setView() {
  86924. var o = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  86925. var callback = () => {
  86926. if (o.displayMode) {
  86927. Potree.settings.displayMode = o.displayMode;
  86928. }
  86929. if (!o.pano && o.currentPano) this.images360.currentPano = o.currentPano;
  86930. o.callback && o.callback();
  86931. };
  86932. if (o.pano != void 0) {
  86933. //pano 权重高于 position
  86934. this.images360.flyToPano(o);
  86935. } else {
  86936. this.mainViewport.view.setView($.extend({}, o, {
  86937. callback
  86938. }));
  86939. }
  86940. }
  86941. //设置点云为标准模式
  86942. setPointStandardMat(state, pointDensity, fitPointsize) {
  86943. console.log('setPointStandardMat', state);
  86944. if (state) {
  86945. if (this.pointStatesBefore) {
  86946. return console.warn('已设置过pointStatesBefore!');
  86947. }
  86948. this.pointStatesBefore = {
  86949. opacity: new Map(),
  86950. size: new Map(),
  86951. density: Potree.settings.pointDensity,
  86952. useEDL: this.getEDLEnabled(),
  86953. shape: viewer.scene.pointclouds[0].material.shape
  86954. };
  86955. viewer.scene.pointclouds.forEach(e => {
  86956. this.pointStatesBefore.opacity.set(e, e.temp.pointOpacity); //因为更改pointDensity时会自动变opacity,所以这项最先获取
  86957. this.pointStatesBefore.colorType = e.material.activeAttributeName;
  86958. fitPointsize && this.pointStatesBefore.size.set(e, e.temp.pointSize); //这项不一定有用,因为会被后期覆盖
  86959. });
  86960. if (pointDensity) Potree.settings.pointDensity = pointDensity; //万一之后切换到全景模式怎么办
  86961. if (fitPointsize) Potree.settings.sizeFitToLevel = true;
  86962. viewer.scene.pointclouds.forEach(e => {
  86963. e.material.activeAttributeName = 'rgba';
  86964. e.material.shape = Potree.PointShape['SQUARE'];
  86965. fitPointsize && e.changePointSize(Potree.config.material.realPointSize, true);
  86966. e.changePointOpacity(1);
  86967. });
  86968. viewer.setEDLEnabled(false);
  86969. } else {
  86970. if (!this.pointStatesBefore) {
  86971. return console.error('未设置过pointStatesBefore!');
  86972. }
  86973. Potree.settings.sizeFitToLevel = false;
  86974. if (pointDensity) Potree.settings.pointDensity = this.pointStatesBefore.pointDensity;
  86975. viewer.scene.pointclouds.forEach(e => {
  86976. e.material.activeAttributeName = this.pointStatesBefore.colorType;
  86977. e.changePointOpacity(this.pointStatesBefore.opacity.get(e));
  86978. e.material.shape = this.pointStatesBefore.shape;
  86979. var size = this.pointStatesBefore.size.get(e);
  86980. if (size) e.changePointSize(size);
  86981. });
  86982. viewer.setEDLEnabled(this.pointStatesBefore.useEDL);
  86983. this.pointStatesBefore = null;
  86984. }
  86985. }
  86986. //调试时显示transformControl来调节object
  86987. transformObject(object) {
  86988. var seleted = viewer.inputHandler.selection[0];
  86989. if (!object) {
  86990. //取消
  86991. seleted && viewer.inputHandler.toggleSelection(seleted);
  86992. return;
  86993. }
  86994. if (seleted && seleted != object) {
  86995. //要更换,先取消
  86996. this.transformObject(null);
  86997. }
  86998. if (!object.boundingBox) {
  86999. object.boundingBox = new Box3(); //任意大小 只是为了显示黄色外框
  87000. //??? computeBoundingBox
  87001. }
  87002. if (!viewer.inputHandler.selection.includes(object)) {
  87003. viewer.inputHandler.toggleSelection(object);
  87004. }
  87005. }
  87006. pointInWhichPointcloud(pos) {
  87007. //选择最接近中心的那个 使用boundSphere
  87008. var result = Common.sortByScore(this.scene.pointclouds, [], [pointcloud => {
  87009. var size = pointcloud.pcoGeometry.tightBoundingBox.getSize(new Vector3());
  87010. var center = pointcloud.bound.getCenter(new Vector3());
  87011. var length = size.length() / 2;
  87012. var dis = pos.distanceTo(center);
  87013. return length / dis; //到数据集中心的距离占数据集大小越小越好
  87014. }]);
  87015. //若要求更准确的话,可以使用ifContainsPoint判断一下是否在bound中
  87016. var r = result[0];
  87017. return r && r.score > 1 ? result[0].item : null;
  87018. }
  87019. /* createRoomEv(){
  87020. const environment = new RoomEnvironment();
  87021. const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
  87022. }
  87023. */
  87024. modelLoaded(object) {
  87025. var fileInfo_ = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  87026. var done = arguments.length > 2 ? arguments[2] : undefined;
  87027. //普通模型加载完以后
  87028. object.isModel = true;
  87029. var boundingBox = new Box3();
  87030. if (fileInfo_.parentInfo) {
  87031. object.name = fileInfo_.name;
  87032. fileInfo_.parentInfo.loadedCount++;
  87033. fileInfo_.parentInfo.modelGroup.add(object);
  87034. if (fileInfo_.parentInfo.loadedCount == fileInfo_.parentInfo.url.length) {
  87035. return this.modelLoaded(fileInfo_.parentInfo.modelGroup, fileInfo_.parentInfo, done);
  87036. } else {
  87037. return;
  87038. }
  87039. }
  87040. object.name = fileInfo_.name != void 0 ? fileInfo_.name : fileInfo_.fileType;
  87041. object.fileType = fileInfo_.fileType;
  87042. object.boundingBox = boundingBox; //未乘上matrixWorld的本地boundingBox
  87043. //object.scale.set(1,1,1);//先获取原始的大小时的boundingBox
  87044. object.opacity = 1; //初始化 记录
  87045. object.updateMatrixWorld();
  87046. if (fileInfo_.id != void 0) object.dataset_id = fileInfo_.id;
  87047. fileInfo_.loadCostTime = Date.now() - fileInfo_.loadStartTime;
  87048. /* let weight = Math.round((total / 1024 / 1024) * 100) / 100;*/
  87049. console.log('加载完毕:', Common.getNameFromURL(fileInfo_.url), '耗时(ms)', fileInfo_.loadCostTime /* 模型数据量:' + weight + 'M' */);
  87050. if (fileInfo_.fileType == '3dTiles') {
  87051. var isGroup = !object.runtime;
  87052. var children = object.runtime ? [object] : object.children;
  87053. children.forEach(object => {
  87054. var boundingBox_ = new Box3();
  87055. var tileset = object.runtime.getTileset();
  87056. //TileHeader: tileset.root
  87057. //参见另一个工程 TileRenderer.js preprocessNode //这个坐标位置几万…… let data = boundingVolume.halfAxes //但这个似乎是premultiply( transform );过后的,可能需还原下
  87058. var json = tileset.tileset;
  87059. var box = json.root.boundingVolume.box;
  87060. if (box) {
  87061. var center = new Vector3(box[0], box[1], box[2]);
  87062. var boundSize = new Vector3();
  87063. // get the extents of the bounds in each axis
  87064. var vecX = new Vector3(box[3], box[4], box[5]);
  87065. var vecY = new Vector3(box[6], box[7], box[8]);
  87066. var vecZ = new Vector3(box[9], box[10], box[11]);
  87067. var scaleX = vecX.length();
  87068. var scaleY = vecY.length();
  87069. var scaleZ = vecZ.length();
  87070. boundingBox_.min.set(-scaleX, -scaleY, -scaleZ);
  87071. boundingBox_.max.set(scaleX, scaleY, scaleZ);
  87072. if (isGroup) {
  87073. //如果是多个拼成的,每个都保留原先在parent中的offset。 如果是外层,作为独立个体,不用理会位置信息,直接放中央。
  87074. object.position.copy(center);
  87075. object.position.z *= -1;
  87076. boundingBox_.translate(object.position); //由于是内层,其位移会改变整体的boundingbox
  87077. }
  87078. } else if (json.root.boundingVolume.sphere) {
  87079. var sphereData = json.root.boundingVolume.sphere;
  87080. var _center = new Vector3(...sphereData);
  87081. var radius = sphereData[3] / 2;
  87082. /* let sphere = new THREE.Sphere(center, radius)
  87083. let box = sphere.getBoundingBox()
  87084. boundingBox.copy(box) */
  87085. boundingBox_.min.set(-radius, -radius, -radius);
  87086. boundingBox_.max.set(radius, radius, radius);
  87087. } else {
  87088. return console.error('json boundingVolume 缺少信息');
  87089. }
  87090. //中心点居然没用。可能是漏用了什么信息,也许这和LVBADUI_qp是散的有关。
  87091. console.log('3d tiles json', json);
  87092. json.root.refine = 'ADD';
  87093. json.refine = 'ADD';
  87094. boundingBox.union(boundingBox_);
  87095. });
  87096. } else {
  87097. Potree.Utils.setObjectLayers(object, Potree.settings.showObjectsOnMap ? 'bothMapAndScene' : 'model');
  87098. object.traverse(child => {
  87099. var is = child.isMesh || child instanceof Points || child.isLine;
  87100. if (is) {
  87101. child.renderOrder = Potree.config.renderOrders.model;
  87102. //if(Potree.settings.boundAddObjs){
  87103. child.geometry.computeBoundingBox();
  87104. //console.log(child.matrixWorld.clone())
  87105. boundingBox.union(child.geometry.boundingBox.clone().applyMatrix4(child.matrixWorld)); //但感觉如果最外层object大小不为1,要还原下scale再乘
  87106. //}//获取在scale为1时,表现出的大小
  87107. //Potree.Utils.makeTexDontResize(child.material.map)
  87108. //console.log(child.name, 'roughness',child.material.roughness,'metalness',child.material.metalness)
  87109. if (fileInfo_.unlit && !(child.material instanceof BasicMaterial) /* || object.fileType == 'glb' */) {
  87110. //注释掉是因为已经写入到loader文件里了
  87111. //let material = new THREE.MeshBasicMaterial({map:child.material.map})
  87112. var material = new BasicMaterial({
  87113. map: child.material.map,
  87114. opacity: child.material.opacity,
  87115. color: child.material.color
  87116. }); //很奇怪glb的图会使原本的MeshBasicMaterial 会偏暗,所以自己重新写
  87117. //child.material.dispose()
  87118. child.material = material;
  87119. }
  87120. if (fileInfo_.useStandandMat && !(child.material instanceof MeshStandardMaterial)) {
  87121. child.material = new MeshStandardMaterial();
  87122. }
  87123. if (child.material instanceof MeshStandardMaterial) {
  87124. /* child.material.roughness = 0.7
  87125. child.material.metalness = 0.5 */
  87126. }
  87127. //纯色的还是不能用BasicMaterial
  87128. }
  87129. });
  87130. }
  87131. this.objs.add(object);
  87132. if (fileInfo_.transform) {
  87133. var setTransfrom = name => {
  87134. var value = fileInfo_.transform[name];
  87135. if (!value) return;
  87136. if (value instanceof Array) {
  87137. object[name].fromArray(value);
  87138. } else {
  87139. object[name].copy(value);
  87140. }
  87141. };
  87142. setTransfrom('position');
  87143. setTransfrom('rotation');
  87144. setTransfrom('scale');
  87145. }
  87146. if (fileInfo_.moveWithPointcloud) {
  87147. object.updateMatrix();
  87148. object.matrixAutoUpdate = false;
  87149. object.matrix.premultiply(viewer.scene.pointclouds[0].transformMatrix); //默认跟随第一个数据集
  87150. object.matrixWorldNeedsUpdate = true;
  87151. }
  87152. object.updateMatrixWorld();
  87153. MergeEditor.getBoundCenter(object); //初始化
  87154. done && done(object, fileInfo_);
  87155. this.dispatchEvent({
  87156. type: 'modelLoaded',
  87157. model: object
  87158. });
  87159. //如果需要点击出现transform工具需要它有select事件 如 viewer.objs.children[1].addEventListener('select',()=>{})
  87160. }
  87161. loadModel(fileInfo, done, onProgress_, onError) {
  87162. var _this6 = this;
  87163. return _asyncToGenerator(function* () {
  87164. console.log('开始加载', Common.getNameFromURL(fileInfo.url));
  87165. var boundingBox = new Box3();
  87166. /* if(!Potree.settings.boundAddObjs){
  87167. boundingBox.min.set(-0.5,-0.5,-0.5); boundingBox.max.set(0.5,0.5,0.5)
  87168. } */
  87169. if (fileInfo.objurl) {
  87170. fileInfo.url = fileInfo.objurl, fileInfo.fileType = 'obj'; //兼容最早的
  87171. }
  87172. if (fileInfo.url instanceof Array) {
  87173. if (fileInfo.url.length == 1) {
  87174. fileInfo.url = fileInfo.url[0];
  87175. } else {
  87176. fileInfo.loadedCount = 0;
  87177. fileInfo.modelGroup = new Object3D(); //parentGroup.name = fileInfo.title
  87178. fileInfo.url.forEach((url, i) => {
  87179. var fileInfoS = Common.CloneObject(fileInfo);
  87180. fileInfoS.url = url;
  87181. fileInfoS.name = 'child-' + i;
  87182. fileInfoS.parentInfo = fileInfo;
  87183. _this6.loadModel(fileInfoS, done, onProgress_, onError);
  87184. });
  87185. return;
  87186. }
  87187. }
  87188. fileInfo.url = Common.dealURL(fileInfo.url); //去除'+'
  87189. fileInfo.loadStartTime = Date.now();
  87190. //let fileType = fileInfo.tilesUrl ? '3dTiles' : fileInfo.objurl ? 'obj' : 'glb'
  87191. var loadDone = (object, fileInfo_) => {
  87192. _this6.modelLoaded(object, fileInfo_ || fileInfo, done);
  87193. };
  87194. var onProgress = function onProgress(xhr) {
  87195. if (xhr.lengthComputable) {
  87196. var percentComplete = xhr.loaded / xhr.total * 100;
  87197. //console.log( Math.round(percentComplete, 2) + '% downloaded' );
  87198. onProgress_ && onProgress_(percentComplete);
  87199. }
  87200. };
  87201. if (fileInfo.fileType == 'obj') {
  87202. //暂时不支持数组
  87203. if (fileInfo.mtlurl) {
  87204. loaders.mtlLoader.load(fileInfo.mtlurl, materials => {
  87205. materials.preload();
  87206. loaders.objLoader.setMaterials(materials).load(fileInfo.objurl, (object, total) => {
  87207. loadDone(object /* , total, fileInfo.objurl */);
  87208. }, onProgress, onError);
  87209. }, onProgress, onError);
  87210. } else {
  87211. loaders.objLoader.load(fileInfo.objurl, (object, total) => {
  87212. loadDone(object);
  87213. }, onProgress, onError);
  87214. }
  87215. } else if (fileInfo.fileType == 'glb') {
  87216. loaders.glbLoader.unlitMat = true; //!!fileInfo.unlit
  87217. loaders.glbLoader.load(fileInfo.url, (gltf, total) => {
  87218. //console.log('loadGLTF', gltf)
  87219. loadDone(gltf.scene /* , total, fileInfo.url */);
  87220. }, onProgress, onError);
  87221. } else if (fileInfo.fileType == 'ply') {
  87222. loaders.plyLoader.load(fileInfo.url, geometry => {
  87223. var object;
  87224. console.log('ply加载完毕', geometry);
  87225. if (!geometry.index) {
  87226. //点云
  87227. object = new Points(geometry, new PointsMaterial({
  87228. vertexColors: true,
  87229. size: 0.02
  87230. }));
  87231. //141M的点云,intersect费时300ms以上
  87232. } else {
  87233. //mesh
  87234. object = new Mesh(geometry);
  87235. }
  87236. loadDone(object);
  87237. });
  87238. } else if (fileInfo.fileType == '3dTiles') {
  87239. var result = yield Loader3DTiles.load({
  87240. url: fileInfo.url,
  87241. gltfLoader: loaders.glbLoader,
  87242. //renderer: SceneRenderer.renderer
  87243. options: {
  87244. //dracoDecoderPath: '../utils/loaders/DRACOLoader/draco',
  87245. //basisTranscoderPath: '../utils/loaders/KTX2Loader/basis',
  87246. maximumScreenSpaceError: fileInfo.maximumScreenSpaceError || 80,
  87247. //越小越清晰。 如果本身tiles很密很小这个值就不能很大。
  87248. //maxDepth: 100,
  87249. //maximumMemoryUsage: 100, //缓存大小,见tiles3DMaxMemory。单位M(但实际结果是 2.5*maximumMemoryUsage + 750 。超过2G会崩, 所以应该小于540) 若太小,密集的tile反复加载很卡. (任务管理器刷新网页后若内存不掉就要结束进程否则虚高)
  87250. debug: browser.urlHasValue('tilesBox'),
  87251. //show box
  87252. parent: _this6.scene.scene,
  87253. is4dkk: fileInfo.is4dkk,
  87254. //是否是4dkk中的模型. 通常maximumScreenSpaceError需要10
  87255. updateTime: fileInfo.updateTime //加后缀防止缓存
  87256. }
  87257. });
  87258. console.log(result);
  87259. result.model.runtime = result.runtime;
  87260. var loaded = false;
  87261. var tileset = result.runtime.getTileset();
  87262. tileset.addEventListener('endTileLoading', function (data) {
  87263. //Tileset3D
  87264. if (data.loadingCount == 0 && !loaded) {
  87265. loaded = true;
  87266. console.log('loaded!!!!!!!!!!!!!');
  87267. }
  87268. });
  87269. tileset.addEventListener('tileLoaded', e => {
  87270. //每一个tile加载完要更改透明度
  87271. var opacity = result.model.parent == _this6.objs ? result.model.opacity : result.model.parent.opacity; //最多两层
  87272. MergeEditor.changeOpacity(e.tileContent, opacity);
  87273. //set Layers ?
  87274. });
  87275. {
  87276. var vi = true;
  87277. Object.defineProperty(result.model, "visible", {
  87278. get: function get() {
  87279. return vi;
  87280. },
  87281. set: function set(v) {
  87282. vi = v;
  87283. tileset.visible = v; //同步,使不加载
  87284. tileset.nextForceUpdate = true;
  87285. }
  87286. });
  87287. }
  87288. loadDone(result.model /* , null, fileInfo.url */);
  87289. } else if (fileInfo.fileType == 'dxf') {
  87290. loaders.dxfLoader.load(fileInfo.url, object => {
  87291. loadDone(object);
  87292. }, fileInfo);
  87293. } else if (fileInfo.fileType == 'shp') {
  87294. loaders.shapeLoader.transform = viewer.transform.lonlatToLocal;
  87295. var shp = yield loaders.shapeLoader.load(fileInfo.url);
  87296. var shpModel = shp.node;
  87297. loadDone(shpModel);
  87298. } else if (fileInfo.fileType == '3dgs') {
  87299. var gsViewer = new Potree.GaussianSplats3D.Viewer({
  87300. rootElement: _this6.renderArea,
  87301. threeScene: _this6.scene.scene,
  87302. renderer: _this6.renderer,
  87303. camera: _this6.mainViewport.camera,
  87304. useBuiltInControls: false
  87305. //dropInMode: true,
  87306. // sharedMemoryForWorkers:false //否则 报错 Uncaught (in promise) DOMException: Failed to execute 'postMessage' on 'DedicatedWorkerGlobalScope': SharedArrayBuffer transfer requires self.crossOriginIsolated.
  87307. });
  87308. //let path = Potree.resourcePath+'/models/gaussian/bonsai.ksplat';
  87309. gsViewer.addSplatScene(fileInfo.url, {
  87310. 'streamView': true
  87311. }).then(() => {
  87312. gsViewer.start();
  87313. /* gsViewer.splatMesh.rotation.x = -2.365929590263301
  87314. gsViewer.splatMesh.position.z = 5 */
  87315. gsViewer.splatMesh.updateMatrix();
  87316. gsViewer.splatMesh.updateMatrixWorld();
  87317. gsViewer.splatMesh.visible = false;
  87318. //viewer.mainViewport.view.setView({position: new THREE.Vector3(-4.980, -5.3879, 5.4503095), quaternion:new THREE.Quaternion(0.5750,-0.2809,-0.3372,0.6903)})
  87319. gsViewer.splatMesh.onSplatTreeReadyCallback = () => {
  87320. var {
  87321. sceneMax,
  87322. sceneMin
  87323. } = gsViewer.splatMesh.splatTree.subTrees[0];
  87324. gsViewer.splatMesh.boundingBox.min.copy(sceneMin);
  87325. gsViewer.splatMesh.boundingBox.max.copy(sceneMax);
  87326. loadDone(gsViewer.splatMesh);
  87327. };
  87328. });
  87329. //window.gsViewer = gsViewer
  87330. viewer.addEventListener('render.begin2', e => {
  87331. if (e.name == 'scene') {
  87332. //gsViewer.selfDrivenUpdate()
  87333. gsViewer.update();
  87334. if (gsViewer.initialized && gsViewer.splatRenderReady) {
  87335. gsViewer.splatMesh.visible = true;
  87336. }
  87337. }
  87338. });
  87339. }
  87340. })();
  87341. }
  87342. removeModel(model) {
  87343. this.objs.remove(model);
  87344. var dispose = e => {
  87345. e.geometry && e.geometry.dispose();
  87346. e.material && e.material.dispose();
  87347. };
  87348. model.traverse(e => {
  87349. dispose(e);
  87350. });
  87351. if (Potree.settings.boundAddObjs) {
  87352. this.updateModelBound();
  87353. }
  87354. }
  87355. setDisplay(state) {
  87356. var cause = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'setDisplay';
  87357. //如果创建了iframe,主页的需要隐藏的话需要释放一些内存出来。iframe关闭前也释放下比较保险
  87358. state = !!state;
  87359. this.objs.children.forEach(e => {
  87360. if (e.fileType == '3dTiles') {
  87361. var tileset = e.runtime.getTileset();
  87362. Potree.Utils.updateVisible(e, cause, state);
  87363. if (!state) tileset._cache.trim(); //使下一次update时dispose所有不可见的tiles
  87364. e.runtime.update(16, this.renderer, this.mainViewport.camera, true);
  87365. if (state) this.dispatchEvent('content_changed');
  87366. }
  87367. });
  87368. if (state) {
  87369. Potree.pointBudget = 6 * 1000 * 1000; //先随便写一个, 随后mergeEditor.updateMemoryUsage
  87370. } else {
  87371. Potree.pointBudget = 0;
  87372. Potree.updatePointClouds(this.scene.pointclouds, this.mainViewport.camera, this.mainViewport.resolution);
  87373. this.images360.panoRenderer.disposeIdelTargets(); //如果也能清空当前使用的就好了,但是恢复就需要时间
  87374. this.images360.depthSampler.clearTexData();
  87375. }
  87376. this.dispatchEvent({
  87377. type: 'setDisplay',
  87378. state
  87379. });
  87380. this.paused = !state;
  87381. }
  87382. addFire() {
  87383. if (Potree.settings.number == 't-CwfhfqJ') {
  87384. var position = Potree.Utils.datasetPosTransform({
  87385. pointcloud: viewer.scene.pointclouds[0],
  87386. position: new Vector3(4.4318, -0.580291847759, -0.78),
  87387. fromDataset: true
  87388. });
  87389. viewer.modules.ParticleEditor.addParticle({
  87390. type: 'fire',
  87391. positions: [position],
  87392. radius: 0.42,
  87393. height: 10
  87394. });
  87395. viewer.modules.ParticleEditor.addParticle({
  87396. type: 'smoke',
  87397. positions: [new Vector3().addVectors(position, new Vector3(0, 0, 0.3))],
  87398. positionStyle: 'sphere',
  87399. positionRadius: 0.3,
  87400. sizeTween: [[0, 0.3, 0.9, 1], [0.05, 0.1, 1, 0.8]],
  87401. opacityBase: 0.2,
  87402. opacityTween: [[0, 0.3, 0.7, 0.95, 1], [0, 0.2, 1, 0.1, 0]],
  87403. velocityBase: new Vector3(0, 0, 1),
  87404. velocitySpread: new Vector3(0.2, 0.2, -0.3),
  87405. accelerationBase: 0.2,
  87406. accelerationSpread: 0.7,
  87407. radius: 0,
  87408. //particlesPerSecond : 30,
  87409. particleDeathAge: 3.0
  87410. });
  87411. viewer.modules.ParticleEditor.addParticle({
  87412. type: 'explode',
  87413. name: 'fire splash',
  87414. position: new Vector3().addVectors(position, new Vector3(0, 0, 0.3)),
  87415. size: 0.1,
  87416. sizeRange: 0.3,
  87417. sizeTween: [[0, 0.05, 0.3, 0.45], [0, 0.02, 0.1, 0.05]],
  87418. opacityTween: [[0, 0.05, 0.3, 0.45], [1, 1, 0.5, 0]],
  87419. speed: 1,
  87420. //sphere
  87421. speedRange: 4,
  87422. radius: 0.1,
  87423. acceleration: 0.3,
  87424. accelerationRange: 1,
  87425. particleSpaceTime: 0,
  87426. strength: 4
  87427. });
  87428. }
  87429. }
  87430. addVideo() {
  87431. if (Potree.settings.number != 'SS-t-P6zBR73Gke') return;
  87432. var geo = new PlaneGeometry(1, 1, 1, 1);
  87433. var videoInfo = this.videoInfo = [{
  87434. id: '40-2',
  87435. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/10/0aabafee-36b8-455d-9c11-0780bf694786.mp4',
  87436. rotation: [-1.494468618954883, -1.4987317433158989, -3.061254983446741],
  87437. position: [19.801820617361624, 2.884673619844108, -0.03362305858221648],
  87438. scale: [3.5741423153151763, 2.8738725275578703, 1]
  87439. }, {
  87440. id: 40,
  87441. /* rotation:[-1.534692822378723, 0.01083403560862361, 3.141535283661569],
  87442. position:[17.2934294239949861, 2.413510747928117, -0.008057029580231356], */
  87443. url: 'https://laser-oss.4dkankan.com/testdata/SS-t-P6zBR73Gke/temp/poi/2022/05/09/7896d6ef-a2d6-4fd7-949c-768782a5b484.mp4',
  87444. rotation: [-1.5487684197910518, 0.021848470169552752, -3.1387534893955236],
  87445. position: [17.277316608096, 2.0840432922115846, -0.0931149415437065],
  87446. scale: [2.0821757723834047, 0.6129478480765236, 1],
  87447. visibles: [40]
  87448. }];
  87449. var add = info => {
  87450. var video = $("<video controls=\"controls\" loop autoplay x5-playsinline=\"\" webkit-playsinline=\"true\" playsinline=\"true\" controlslist=\"nodownload\"></video>")[0];
  87451. video.setAttribute("crossOrigin", 'Anonymous');
  87452. video.src = info.url || Potree.resourcePath + "/video/".concat(Potree.settings.number, "/").concat(info.id, ".mp4");
  87453. var map = new VideoTexture(video);
  87454. var plane = this.videoPlane = new Mesh(geo, new MeshBasicMaterial({
  87455. color: "#ffffff",
  87456. transparent: !0,
  87457. depthTest: false,
  87458. opacity: 0,
  87459. //side:2,
  87460. map
  87461. }));
  87462. plane.position.fromArray(info.position);
  87463. plane.rotation.fromArray(info.rotation);
  87464. info.scale && plane.scale.fromArray(info.scale);
  87465. this.scene.scene.add(plane);
  87466. info.plane = plane;
  87467. plane.boundingBox = new Box3(new Vector3(0, -0.5, 0), new Vector3(1, -0.4, 0.2));
  87468. video.addEventListener('loadeddata', function (e) {
  87469. video.play();
  87470. if (!info.visibles /* ||!viewer.images360.currentPano || info.visibles.includes(viewer.images360.currentPano.id) */) {
  87471. plane.material.opacity = 1;
  87472. }
  87473. info.scale || plane.scale.set(video.videoWidth / 1000, video.videoHeight / 1000, 1); // 1080 * 1920
  87474. console.log('video loadeddata', info.id);
  87475. });
  87476. if (info.visibles) {
  87477. this.images360.addEventListener('flyToPano', e => {
  87478. //飞之前
  87479. if (info.visibles.includes(e.toPano.pano.id)) {
  87480. //出现
  87481. setTimeout(() => {
  87482. plane.visible = true;
  87483. video.currentTime = 0;
  87484. video.play();
  87485. if (video.paused) {
  87486. var startPlay = () => {
  87487. plane.visible && video.play();
  87488. this.removeEventListener('global_mousedown', startPlay);
  87489. };
  87490. this.addEventListener('global_mousedown', startPlay);
  87491. }
  87492. Potree.settings.zoom.enabled = false;
  87493. transitions.start(lerp.property(plane.material, "opacity", 1), e.toPano.duration * 0.4, () => {}, 0, easing['easeInOutQuad']);
  87494. }, e.toPano.duration * 0.6); //时间上不能和消失的重叠 延迟
  87495. } else {
  87496. //消失
  87497. transitions.start(lerp.property(plane.material, "opacity", 0), e.toPano.duration * 0.4, () => {
  87498. if (!info) {
  87499. plane.visible = false;
  87500. video.pause();
  87501. Potree.settings.zoom.enabled = true;
  87502. }
  87503. }, 0, easing['easeInOutQuad']);
  87504. }
  87505. });
  87506. }
  87507. var startPlay = () => {
  87508. video.play();
  87509. //video.pause()
  87510. //video.currentTime = 0.1;
  87511. this.removeEventListener('global_mousedown', startPlay);
  87512. };
  87513. this.addEventListener('global_mousedown', startPlay);
  87514. Potree.settings.isTest && plane.addEventListener('select', e => {
  87515. console.log(e);
  87516. });
  87517. };
  87518. videoInfo.forEach(info => {
  87519. add(info);
  87520. });
  87521. /* this.images360.addEventListener('flyToPano' ,(e)=>{//飞之前
  87522. if(Potree.settings.displayMode != 'showPanos') return
  87523. let info = videoInfo[e.toPano.pano.id]
  87524. if(info ){ //出现
  87525. setTimeout(()=>{
  87526. plane.visible = true;
  87527. plane.position.fromArray(info.position)
  87528. plane.rotation.fromArray(info.rotation)
  87529. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${e.toPano.pano.id}.mp4`
  87530. video.play();
  87531. video.currentTime = 0
  87532. Potree.settings.zoom.enabled = false
  87533. transitions.start(lerp.property(plane.material, "opacity", 1 ) , e.toPano.duration*0.4 , ()=>{
  87534. }, 0, easing['easeInOutQuad'])
  87535. }, e.toPano.duration*0.6) //时间上不能和消失的重叠 延迟
  87536. }
  87537. //消失
  87538. transitions.start(lerp.property(plane.material, "opacity", 0, ) , e.toPano.duration*0.4, ()=>{
  87539. if(!info){
  87540. plane.visible = false
  87541. video.pause()
  87542. Potree.settings.zoom.enabled = true
  87543. }
  87544. }, 0, easing['easeInOutQuad'])
  87545. })
  87546. this.images360.addEventListener('endChangeMode',(e)=>{ //暂时不处理初始加载时就在有视频的点位上的情况
  87547. if(e.mode == 'showPanos'){
  87548. let info = videoInfo[this.images360.currentPano.id]
  87549. if(info ){ //出现
  87550. plane.visible = true;
  87551. plane.position.fromArray(info.position)
  87552. plane.rotation.fromArray(info.rotation)
  87553. plane.material.opacity = 0
  87554. video.src = Potree.resourcePath+`/video/${Potree.settings.number}/${this.images360.currentPano.id}.mp4`
  87555. video.play();
  87556. video.currentTime = 0
  87557. Potree.settings.zoom.enabled = false
  87558. transitions.start(lerp.property(plane.material, "opacity", 1, (e)=>{console.log('fadeIn',e)}) , 300 , ()=>{
  87559. }, 0, easing['easeInOutQuad'])
  87560. }
  87561. }else{
  87562. plane.visible = false;
  87563. Potree.settings.zoom.enabled = true
  87564. }
  87565. })
  87566. */
  87567. }
  87568. /* addTube(){//加水管 自动生成
  87569. if(Potree.settings.number == 't-8KbK1JjubE'){
  87570. let boundingBox = new THREE.Box3()
  87571. boundingBox.min.set(-1,-1,-1); boundingBox.max.set(1,1,1)
  87572. let radius = 0.08;
  87573. let radialSegments = 5
  87574. let radSegments = Math.PI*2 / radialSegments
  87575. var circlePts = [];//横截面
  87576. for(let i=0;i<radialSegments;i++){
  87577. let angle = radSegments * i;
  87578. circlePts.push(new THREE.Vector2(radius * Math.cos(angle), radius * Math.sin(angle) ))
  87579. }
  87580. var count = 0
  87581. var addMesh = (color, path, height)=>{//height:在path之上的高度,负数代表在path之下
  87582. var name = 'cylinder'+count
  87583. var mat = new THREE.MeshStandardMaterial({color, depthTest:false, roughness:0.4,metalness:0.5}) 
  87584. let linePath = path.map(e=>new THREE.Vector3().copy(e).setZ(e.z+height))
  87585. let geo = MeshDraw.getExtrudeGeo( circlePts, null,{ extrudePath:linePath, tension:0.2} )
  87586. var mesh = new THREE.Mesh(geo,mat);
  87587. mesh.name = name
  87588. window[name] = mesh
  87589. mesh.boundingBox = boundingBox
  87590. mesh.matrixAutoUpdate = false
  87591. mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix)
  87592. mesh.matrixWorldNeedsUpdate = true
  87593. this.scene.scene.add(mesh);
  87594. count ++
  87595. }
  87596. let linePath, height
  87597. //地上管子 黄色
  87598. linePath = [{"x":-109.83,"y":-68.33,"z":-7.52},{"x":-95.17,"y":-59.3,"z":-7.38}, {"x":-38.75,"y":-24.01,"z":-6.01},{"x":0.5,"y":0.19,"z":-3.89},{"x":39.29,"y":24.41,"z":-1.31}
  87599. ,{"x":43.58,"y":27.7,"z":-0.97},{"x":40.22,"y":35.37,"z":-0.67}// 拐弯向右
  87600. , {"x":39.18,"y":36.71,"z":0.35},{"x":38.69,"y":36.04,"z":18.04} // 拐弯向上
  87601. ]
  87602. height = radius + 0.05;
  87603. addMesh('#b86', linePath, height)
  87604. //地下管子 藍色
  87605. linePath = [{"x":-108.24,"y":-70.61,"z":-7.52}, {"x":-57.8,"y":-39.31,"z":-6.72},{"x":-18.8,"y":-15.35,"z":-5.01},{"x":55.87,"y":31.67,"z":-0.04},{"x":110.53,"y":66.48,"z":5.14}
  87606. ]
  87607. height = -0.5;
  87608. addMesh('#48a', linePath, height)
  87609. }
  87610. } */
  87611. addTube(datas) {
  87612. var _this7 = this;
  87613. var _loop = function _loop() {
  87614. if (number == Potree.settings.number) {
  87615. var data = datas[number];
  87616. var boundingBox = new Box3();
  87617. boundingBox.min.set(-1, -1, -1);
  87618. boundingBox.max.set(1, 1, 1);
  87619. index = 0;
  87620. addMesh = function addMesh() {
  87621. var {
  87622. color,
  87623. path,
  87624. height,
  87625. fromDataset,
  87626. radius = 0.08,
  87627. datasetId = Potree.settings.originDatasetId,
  87628. spaceDis,
  87629. tension = 0.1,
  87630. visiEntity
  87631. } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  87632. //height:在path之上的高度,负数代表在path之下
  87633. var name = 'tube_' + index;
  87634. var radialSegments = 30; //THREE.Math.clamp( Math.round(radius * 800), 10, 40)
  87635. var radSegments = Math.PI * 2 / radialSegments;
  87636. var circlePts = []; //横截面
  87637. for (var i = 0; i < radialSegments; i++) {
  87638. var angle = radSegments * i;
  87639. circlePts.push(new Vector2(radius * Math.cos(angle), radius * Math.sin(angle)));
  87640. }
  87641. var mat = new MeshStandardMaterial({
  87642. color,
  87643. /* wireframe:true, depthTest:false,*/roughness: 0.9,
  87644. metalness: 0.3
  87645. });
  87646. var linePath = path.map(e => {
  87647. e instanceof Array && (e = new Vector3().fromArray(e));
  87648. var pos;
  87649. if (fromDataset) {
  87650. //获取:JSON.stringify(viewer.scene.measurements[0].dataset_points.map(e=>Potree.math.toPrecision(e.toArray(),3)))
  87651. pos = Potree.Utils.datasetPosTransform({
  87652. fromDataset: true,
  87653. position: e,
  87654. datasetId
  87655. });
  87656. } else {
  87657. pos = new Vector3().copy(e);
  87658. }
  87659. return pos.setZ(pos.z + height);
  87660. });
  87661. console.log(linePath);
  87662. var geo = MeshDraw.getExtrudeGeo(circlePts, null, {
  87663. extrudePath: linePath,
  87664. tension,
  87665. spaceDis
  87666. });
  87667. var mesh = new Mesh(geo, mat);
  87668. mesh.name = name;
  87669. window[name] = mesh;
  87670. mesh.boundingBox = boundingBox;
  87671. mesh.matrixAutoUpdate = false;
  87672. fromDataset || mesh.matrix.copy(viewer.scene.pointclouds[0].transformMatrix);
  87673. mesh.matrixWorldNeedsUpdate = true;
  87674. _this7.scene.scene.add(mesh);
  87675. if (visiEntity) {
  87676. _this7.modules.SiteModel.bus.addEventListener('buildingChange', e => {
  87677. Potree.Utils.updateVisible(mesh, 'isInEntity', e.entity && e.entity.name == visiEntity);
  87678. });
  87679. }
  87680. };
  87681. while (index < data.length) {
  87682. addMesh(data[index]);
  87683. index++;
  87684. }
  87685. }
  87686. },
  87687. index,
  87688. addMesh;
  87689. //加水管 自动生成
  87690. for (var number in datas) {
  87691. _loop();
  87692. }
  87693. /*
  87694. 可能用到的
  87695. viewer.scene.measurements.forEach(e=>e.edgeLabels.forEach(e=>Potree.Utils.updateVisible(e,'f',false)))
  87696. JSON.stringify(viewer.scene.measurements.find(e=>e.visible).dataset_points.map(e=>Potree.math.toPrecision(e.toArray(),3)))
  87697. */
  87698. }
  87699. addSprite(e) {
  87700. //api
  87701. var sprite;
  87702. if (e.text != void 0) {
  87703. sprite = new TextSprite(e);
  87704. } else {
  87705. var map = texLoader.load(src);
  87706. e.map = map;
  87707. sprite = new Sprite(e);
  87708. }
  87709. return sprite;
  87710. }
  87711. }
  87712. ;
  87713. //------ CLIP 默认clipTask都是clipInside ----------------------
  87714. /*
  87715. 并集相当于加法,交集相当于乘法。 所有结果都能展开成多个乘积相加。
  87716. 假设有4个clipBoxes,ABCD, 如果是 A*B + C*D ,那么这是最终结果。 如果是 (A+B)*(C+D) = A*C+A*D+B*C+B*D
  87717. */
  87718. /*
  87719. let Clips = {
  87720. boxes : [],
  87721. unionGroups : [], //二维数组。最外层要求并集,里层要求交集(如果只有一个元素就是本身)。总结起来就是要求一堆交集的并集
  87722. shaderParams:{},
  87723. needsUpdate : true,
  87724. addClip(box, clipMethod){
  87725. //不允许重复
  87726. if(this.boxes.includes(box)){
  87727. return console.warn('addClip重复添加了box',box)
  87728. }
  87729. boxes.push(box)
  87730. if(clipMethod == 'any'){//并
  87731. this.unionGroups.push([box])
  87732. }else if(clipMethod == 'all'){//交
  87733. this.unionGroups.forEach(mixGroup=>mixGroup.push(box))
  87734. }
  87735. this.needsUpdate = true
  87736. },
  87737. removeClip(box){
  87738. if(!this.boxes.includes(box)){
  87739. return console.warn('removeClip没有找到该box',box)
  87740. }
  87741. var newGroups = [];
  87742. this.unionGroups.forEach(mixGroup=>{
  87743. if(mixGroup.length == 1 && mixGroup[0] == box)return;//直接删除
  87744. newGroups.push(mixGroup.filter(e=>e!=box));
  87745. })
  87746. this.unionGroups = newGroups;
  87747. this.needsUpdate = true
  87748. }
  87749. ,
  87750. clearClip(){
  87751. this.boxes = [];
  87752. this.unionGroups = []
  87753. this.needsUpdate = true
  87754. }
  87755. ,
  87756. updateShaderParams(){//没写完 - - 见 pointcloud clip.vs
  87757. //uniform mat4 clipBoxes[num_clipboxes];
  87758. //uniform int clipBoxGroupCount;
  87759. //uniform int mixClipIndices[clipboxGroupItemCount]; //把所有的要求都直接放到数组内
  87760. //这里需要转为Float32Array..? 参考material.setClipBoxes
  87761. let everyClipGroupCount = this.unionGroups.map(e=>e.length)
  87762. let mixClipIndices = []
  87763. this.unionGroups.forEach(e=>{
  87764. mixClipIndices.push(...e)
  87765. })
  87766. this.shaderParams = {
  87767. num_clipboxes : this.boxes.length,
  87768. clipBoxGroupCount : this.unionGroups.length,
  87769. everyClipGroupCount,
  87770. clipBoxIndexCount: mixClipIndices.length,
  87771. mixClipIndices
  87772. }
  87773. }
  87774. ,
  87775. getShaderParams(){//每次要传递参数到shader中,执行这个就好
  87776. if(this.needsUpdate){
  87777. this.updateShaderParams()
  87778. }
  87779. return this.shaderParams
  87780. }
  87781. }
  87782. */
  87783. /**
  87784. * @author mschuetz / http://mschuetz.at
  87785. *
  87786. * adapted from THREE.OrbitControls by
  87787. *
  87788. * @author qiao / https://github.com/qiao
  87789. * @author mrdoob / http://mrdoob.com
  87790. * @author alteredq / http://alteredqualia.com/
  87791. * @author WestLangley / http://github.com/WestLangley
  87792. * @author erich666 / http://erichaines.com
  87793. *
  87794. *
  87795. *
  87796. */
  87797. class OrbitControls$2 extends EventDispatcher$1 {
  87798. constructor(viewer) {
  87799. super();
  87800. this.viewer = viewer;
  87801. this.renderer = viewer.renderer;
  87802. this.scene = null;
  87803. this.sceneControls = new Scene();
  87804. this.rotationSpeed = 5;
  87805. this.fadeFactor = 20;
  87806. this.yawDelta = 0;
  87807. this.pitchDelta = 0;
  87808. this.panDelta = new Vector2(0, 0);
  87809. this.radiusDelta = 0;
  87810. this.doubleClockZoomEnabled = true;
  87811. this.tweens = [];
  87812. var drag = e => {
  87813. if (e.drag.object !== null) {
  87814. return;
  87815. }
  87816. if (e.drag.startHandled === undefined) {
  87817. e.drag.startHandled = true;
  87818. this.dispatchEvent({
  87819. type: 'start'
  87820. });
  87821. }
  87822. var ndrag = {
  87823. x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth,
  87824. y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight
  87825. };
  87826. if (e.drag.mouse === MOUSE$1.LEFT) {
  87827. this.yawDelta += ndrag.x * this.rotationSpeed;
  87828. this.pitchDelta += ndrag.y * this.rotationSpeed;
  87829. this.stopTweens();
  87830. } else if (e.drag.mouse === MOUSE$1.RIGHT) {
  87831. this.panDelta.x += ndrag.x;
  87832. this.panDelta.y += ndrag.y;
  87833. this.stopTweens();
  87834. }
  87835. };
  87836. var drop = e => {
  87837. this.dispatchEvent({
  87838. type: 'end'
  87839. });
  87840. };
  87841. var scroll = e => {
  87842. var resolvedRadius = this.scene.view.radius + this.radiusDelta;
  87843. this.radiusDelta += -e.delta * resolvedRadius * 0.1;
  87844. this.stopTweens();
  87845. };
  87846. var dblclick = e => {
  87847. if (this.doubleClockZoomEnabled) {
  87848. this.zoomToLocation(e.mouse);
  87849. }
  87850. };
  87851. var previousTouch = null;
  87852. var touchStart = e => {
  87853. previousTouch = e;
  87854. };
  87855. var touchEnd = e => {
  87856. previousTouch = e;
  87857. };
  87858. var touchMove = e => {
  87859. if (e.touches.length === 2 && previousTouch.touches.length === 2) {
  87860. var prev = previousTouch;
  87861. var curr = e;
  87862. var prevDX = prev.touches[0].pageX - prev.touches[1].pageX;
  87863. var prevDY = prev.touches[0].pageY - prev.touches[1].pageY;
  87864. var prevDist = Math.sqrt(prevDX * prevDX + prevDY * prevDY);
  87865. var currDX = curr.touches[0].pageX - curr.touches[1].pageX;
  87866. var currDY = curr.touches[0].pageY - curr.touches[1].pageY;
  87867. var currDist = Math.sqrt(currDX * currDX + currDY * currDY);
  87868. var delta = currDist / prevDist;
  87869. var resolvedRadius = this.scene.view.radius + this.radiusDelta;
  87870. var newRadius = resolvedRadius / delta;
  87871. this.radiusDelta = newRadius - resolvedRadius;
  87872. this.stopTweens();
  87873. } else if (e.touches.length === 3 && previousTouch.touches.length === 3) {
  87874. var _prev = previousTouch;
  87875. var _curr = e;
  87876. var prevMeanX = (_prev.touches[0].pageX + _prev.touches[1].pageX + _prev.touches[2].pageX) / 3;
  87877. var prevMeanY = (_prev.touches[0].pageY + _prev.touches[1].pageY + _prev.touches[2].pageY) / 3;
  87878. var currMeanX = (_curr.touches[0].pageX + _curr.touches[1].pageX + _curr.touches[2].pageX) / 3;
  87879. var currMeanY = (_curr.touches[0].pageY + _curr.touches[1].pageY + _curr.touches[2].pageY) / 3;
  87880. var _delta = {
  87881. x: (currMeanX - prevMeanX) / this.renderer.domElement.clientWidth,
  87882. y: (currMeanY - prevMeanY) / this.renderer.domElement.clientHeight
  87883. };
  87884. this.panDelta.x += _delta.x;
  87885. this.panDelta.y += _delta.y;
  87886. this.stopTweens();
  87887. }
  87888. previousTouch = e;
  87889. };
  87890. this.addEventListener('touchstart', touchStart);
  87891. this.addEventListener('touchend', touchEnd);
  87892. this.addEventListener('touchmove', touchMove);
  87893. this.addEventListener('drag', drag);
  87894. this.addEventListener('drop', drop);
  87895. this.addEventListener('mousewheel', scroll);
  87896. this.addEventListener('dblclick', dblclick);
  87897. }
  87898. setScene(scene) {
  87899. this.scene = scene;
  87900. }
  87901. stop() {
  87902. this.yawDelta = 0;
  87903. this.pitchDelta = 0;
  87904. this.radiusDelta = 0;
  87905. this.panDelta.set(0, 0);
  87906. }
  87907. zoomToLocation(mouse) {
  87908. var camera = this.scene.getActiveCamera();
  87909. var I = Utils.getMousePointCloudIntersection(mouse, camera, this.viewer, this.scene.pointclouds, {
  87910. pickClipped: true
  87911. });
  87912. if (I === null) {
  87913. return;
  87914. }
  87915. var targetRadius = 0;
  87916. {
  87917. var minimumJumpDistance = 0.2;
  87918. var domElement = this.renderer.domElement;
  87919. var ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight);
  87920. var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  87921. var lastNode = nodes[nodes.length - 1];
  87922. var radius = lastNode.getBoundingSphere(new Sphere()).radius;
  87923. targetRadius = Math.min(this.scene.view.radius, radius);
  87924. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  87925. }
  87926. var d = this.scene.view.direction.multiplyScalar(-1);
  87927. var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  87928. // TODO Unused: let controlsTargetPosition = I.location;
  87929. var animationDuration = 600;
  87930. var easing = TWEEN.Easing.Quartic.Out;
  87931. {
  87932. // animate
  87933. var value = {
  87934. x: 0
  87935. };
  87936. var tween = new TWEEN.Tween(value).to({
  87937. x: 1
  87938. }, animationDuration);
  87939. tween.easing(easing);
  87940. this.tweens.push(tween);
  87941. var startPos = this.scene.view.position.clone();
  87942. var targetPos = cameraTargetPosition.clone();
  87943. var startRadius = this.scene.view.radius;
  87944. var _targetRadius = cameraTargetPosition.distanceTo(I.location);
  87945. tween.onUpdate(() => {
  87946. var t = value.x;
  87947. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  87948. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  87949. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  87950. this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius;
  87951. this.viewer.setMoveSpeed(this.scene.view.radius);
  87952. });
  87953. tween.onComplete(() => {
  87954. this.tweens = this.tweens.filter(e => e !== tween);
  87955. });
  87956. tween.start();
  87957. }
  87958. }
  87959. stopTweens() {
  87960. this.tweens.forEach(e => e.stop());
  87961. this.tweens = [];
  87962. }
  87963. update(delta) {
  87964. var view = this.scene.view;
  87965. {
  87966. // apply rotation
  87967. var progression = Math.min(1, this.fadeFactor * delta);
  87968. var yaw = view.yaw;
  87969. var pitch = view.pitch;
  87970. var pivot = view.getPivot();
  87971. yaw -= progression * this.yawDelta;
  87972. pitch -= progression * this.pitchDelta;
  87973. view.yaw = yaw;
  87974. view.pitch = pitch;
  87975. var V = this.scene.view.direction.multiplyScalar(-view.radius);
  87976. var position = new Vector3().addVectors(pivot, V);
  87977. view.position.copy(position);
  87978. }
  87979. {
  87980. // apply pan
  87981. var _progression = Math.min(1, this.fadeFactor * delta);
  87982. var panDistance = _progression * view.radius * 3;
  87983. var px = -this.panDelta.x * panDistance;
  87984. var py = this.panDelta.y * panDistance;
  87985. view.pan(px, py);
  87986. }
  87987. {
  87988. // apply zoom
  87989. var _progression2 = Math.min(1, this.fadeFactor * delta);
  87990. // let radius = view.radius + progression * this.radiusDelta * view.radius * 0.1;
  87991. var radius = view.radius + _progression2 * this.radiusDelta;
  87992. var _V = view.direction.multiplyScalar(-radius);
  87993. var _position = new Vector3().addVectors(view.getPivot(), _V);
  87994. view.radius = radius;
  87995. view.position.copy(_position);
  87996. }
  87997. {
  87998. var speed = view.radius;
  87999. this.viewer.setMoveSpeed(speed);
  88000. }
  88001. {
  88002. // decelerate over time
  88003. var _progression3 = Math.min(1, this.fadeFactor * delta);
  88004. var attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  88005. this.yawDelta *= attenuation;
  88006. this.pitchDelta *= attenuation;
  88007. this.panDelta.multiplyScalar(attenuation);
  88008. // this.radiusDelta *= attenuation;
  88009. this.radiusDelta -= _progression3 * this.radiusDelta;
  88010. }
  88011. }
  88012. }
  88013. ;
  88014. /**
  88015. * @author mschuetz / http://mschuetz.at
  88016. *
  88017. * adapted from THREE.OrbitControls by
  88018. *
  88019. * @author qiao / https://github.com/qiao
  88020. * @author mrdoob / http://mrdoob.com
  88021. * @author alteredq / http://alteredqualia.com/
  88022. * @author WestLangley / http://github.com/WestLangley
  88023. * @author erich666 / http://erichaines.com
  88024. *
  88025. *
  88026. *
  88027. */
  88028. class FirstPersonControls$1 extends EventDispatcher$1 {
  88029. //old
  88030. constructor(viewer) {
  88031. super();
  88032. this.viewer = viewer;
  88033. this.renderer = viewer.renderer;
  88034. this.scene = null;
  88035. this.sceneControls = new Scene();
  88036. this.rotationSpeed = 200;
  88037. this.moveSpeed = 10;
  88038. this.lockElevation = false;
  88039. this.keys = {
  88040. FORWARD: ['W'.charCodeAt(0), 38],
  88041. BACKWARD: ['S'.charCodeAt(0), 40],
  88042. LEFT: ['A'.charCodeAt(0), 37],
  88043. RIGHT: ['D'.charCodeAt(0), 39],
  88044. UP: ['R'.charCodeAt(0), 33],
  88045. DOWN: ['F'.charCodeAt(0), 34]
  88046. };
  88047. this.fadeFactor = 50;
  88048. this.yawDelta = 0;
  88049. this.pitchDelta = 0;
  88050. this.translationDelta = new Vector3(0, 0, 0);
  88051. this.translationWorldDelta = new Vector3(0, 0, 0);
  88052. this.tweens = [];
  88053. var drag = e => {
  88054. if (e.drag.object !== null) {
  88055. return;
  88056. }
  88057. if (e.drag.startHandled === undefined) {
  88058. e.drag.startHandled = true;
  88059. this.dispatchEvent({
  88060. type: 'start'
  88061. });
  88062. }
  88063. var moveSpeed = this.viewer.getMoveSpeed();
  88064. var ndrag = {
  88065. x: e.drag.lastDrag.x / this.renderer.domElement.clientWidth,
  88066. y: e.drag.lastDrag.y / this.renderer.domElement.clientHeight
  88067. };
  88068. if (e.drag.mouse === MOUSE$1.LEFT) {
  88069. this.yawDelta += ndrag.x * this.rotationSpeed;
  88070. this.pitchDelta += ndrag.y * this.rotationSpeed;
  88071. } else if (e.drag.mouse === MOUSE$1.RIGHT) {
  88072. this.translationDelta.x -= ndrag.x * moveSpeed * 100;
  88073. this.translationDelta.z += ndrag.y * moveSpeed * 100;
  88074. }
  88075. };
  88076. var drop = e => {
  88077. this.dispatchEvent({
  88078. type: 'end'
  88079. });
  88080. };
  88081. var scroll = e => {
  88082. var speed = this.viewer.getMoveSpeed();
  88083. if (e.delta < 0) {
  88084. speed = speed * 0.9;
  88085. } else if (e.delta > 0) {
  88086. speed = speed / 0.9;
  88087. }
  88088. speed = Math.max(speed, 0.1);
  88089. this.viewer.setMoveSpeed(speed);
  88090. };
  88091. var dblclick = e => {
  88092. this.zoomToLocation(e.mouse);
  88093. };
  88094. this.addEventListener('drag', drag);
  88095. this.addEventListener('drop', drop);
  88096. this.addEventListener('mousewheel', scroll);
  88097. this.addEventListener('dblclick', dblclick);
  88098. }
  88099. setScene(scene) {
  88100. this.scene = scene;
  88101. }
  88102. stop() {
  88103. this.yawDelta = 0;
  88104. this.pitchDelta = 0;
  88105. this.translationDelta.set(0, 0, 0);
  88106. }
  88107. zoomToLocation(mouse) {
  88108. var camera = this.scene.getActiveCamera();
  88109. var I = Utils.getMousePointCloudIntersection(mouse, camera, this.viewer, this.scene.pointclouds);
  88110. if (I === null) {
  88111. return;
  88112. }
  88113. var targetRadius = 0;
  88114. {
  88115. var minimumJumpDistance = 0.2;
  88116. var domElement = this.renderer.domElement;
  88117. var ray = Utils.mouseToRay(mouse, camera, domElement.clientWidth, domElement.clientHeight);
  88118. var nodes = I.pointcloud.nodesOnRay(I.pointcloud.visibleNodes, ray);
  88119. var lastNode = nodes[nodes.length - 1];
  88120. var radius = lastNode.getBoundingSphere(new Sphere()).radius;
  88121. targetRadius = Math.min(this.scene.view.radius, radius);
  88122. targetRadius = Math.max(minimumJumpDistance, targetRadius);
  88123. }
  88124. var d = this.scene.view.direction.multiplyScalar(-1);
  88125. var cameraTargetPosition = new Vector3().addVectors(I.location, d.multiplyScalar(targetRadius));
  88126. // TODO Unused: let controlsTargetPosition = I.location;
  88127. var animationDuration = 600;
  88128. var easing = TWEEN.Easing.Quartic.Out;
  88129. {
  88130. // animate
  88131. var value = {
  88132. x: 0
  88133. };
  88134. var tween = new TWEEN.Tween(value).to({
  88135. x: 1
  88136. }, animationDuration);
  88137. tween.easing(easing);
  88138. this.tweens.push(tween);
  88139. var startPos = this.scene.view.position.clone();
  88140. var targetPos = cameraTargetPosition.clone();
  88141. var startRadius = this.scene.view.radius;
  88142. var _targetRadius = cameraTargetPosition.distanceTo(I.location);
  88143. tween.onUpdate(() => {
  88144. var t = value.x;
  88145. this.scene.view.position.x = (1 - t) * startPos.x + t * targetPos.x;
  88146. this.scene.view.position.y = (1 - t) * startPos.y + t * targetPos.y;
  88147. this.scene.view.position.z = (1 - t) * startPos.z + t * targetPos.z;
  88148. this.scene.view.radius = (1 - t) * startRadius + t * _targetRadius;
  88149. this.viewer.setMoveSpeed(this.scene.view.radius / 2.5);
  88150. });
  88151. tween.onComplete(() => {
  88152. this.tweens = this.tweens.filter(e => e !== tween);
  88153. });
  88154. tween.start();
  88155. }
  88156. }
  88157. update(delta) {
  88158. var view = this.scene.view;
  88159. {
  88160. // cancel move animations on user input
  88161. var changes = [this.yawDelta, this.pitchDelta, this.translationDelta.length(), this.translationWorldDelta.length()];
  88162. var changeHappens = changes.some(e => Math.abs(e) > 0.001);
  88163. if (changeHappens && this.tweens.length > 0) {
  88164. this.tweens.forEach(e => e.stop());
  88165. this.tweens = [];
  88166. }
  88167. }
  88168. {
  88169. // accelerate while input is given
  88170. var ih = this.viewer.inputHandler;
  88171. var moveForward = this.keys.FORWARD.some(e => ih.pressedKeys[e]);
  88172. var moveBackward = this.keys.BACKWARD.some(e => ih.pressedKeys[e]);
  88173. var moveLeft = this.keys.LEFT.some(e => ih.pressedKeys[e]);
  88174. var moveRight = this.keys.RIGHT.some(e => ih.pressedKeys[e]);
  88175. var moveUp = this.keys.UP.some(e => ih.pressedKeys[e]);
  88176. var moveDown = this.keys.DOWN.some(e => ih.pressedKeys[e]);
  88177. if (this.lockElevation) {
  88178. var dir = view.direction;
  88179. dir.z = 0;
  88180. dir.normalize();
  88181. if (moveForward && moveBackward) {
  88182. this.translationWorldDelta.set(0, 0, 0);
  88183. } else if (moveForward) {
  88184. this.translationWorldDelta.copy(dir.multiplyScalar(this.viewer.getMoveSpeed()));
  88185. } else if (moveBackward) {
  88186. this.translationWorldDelta.copy(dir.multiplyScalar(-this.viewer.getMoveSpeed()));
  88187. }
  88188. } else {
  88189. if (moveForward && moveBackward) {
  88190. this.translationDelta.y = 0;
  88191. } else if (moveForward) {
  88192. this.translationDelta.y = this.viewer.getMoveSpeed();
  88193. } else if (moveBackward) {
  88194. this.translationDelta.y = -this.viewer.getMoveSpeed();
  88195. }
  88196. }
  88197. if (moveLeft && moveRight) {
  88198. this.translationDelta.x = 0;
  88199. } else if (moveLeft) {
  88200. this.translationDelta.x = -this.viewer.getMoveSpeed();
  88201. } else if (moveRight) {
  88202. this.translationDelta.x = this.viewer.getMoveSpeed();
  88203. }
  88204. if (moveUp && moveDown) {
  88205. this.translationWorldDelta.z = 0;
  88206. } else if (moveUp) {
  88207. this.translationWorldDelta.z = this.viewer.getMoveSpeed();
  88208. } else if (moveDown) {
  88209. this.translationWorldDelta.z = -this.viewer.getMoveSpeed();
  88210. }
  88211. }
  88212. {
  88213. // apply rotation
  88214. var yaw = view.yaw;
  88215. var pitch = view.pitch;
  88216. yaw -= this.yawDelta * delta;
  88217. pitch -= this.pitchDelta * delta;
  88218. view.yaw = yaw;
  88219. view.pitch = pitch;
  88220. }
  88221. {
  88222. // apply translation
  88223. view.translate(this.translationDelta.x * delta, this.translationDelta.y * delta, this.translationDelta.z * delta);
  88224. view.translateWorld(this.translationWorldDelta.x * delta, this.translationWorldDelta.y * delta, this.translationWorldDelta.z * delta);
  88225. }
  88226. {
  88227. // set view target according to speed
  88228. view.radius = 3 * this.viewer.getMoveSpeed();
  88229. }
  88230. {
  88231. // decelerate over time
  88232. var attenuation = Math.max(0, 1 - this.fadeFactor * delta);
  88233. this.yawDelta *= attenuation;
  88234. this.pitchDelta *= attenuation;
  88235. this.translationDelta.multiplyScalar(attenuation);
  88236. this.translationWorldDelta.multiplyScalar(attenuation);
  88237. }
  88238. }
  88239. }
  88240. ;
  88241. OrthographicCamera.prototype.zoomTo = function (node) {
  88242. var factor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
  88243. if (!node.geometry && !node.boundingBox) {
  88244. return;
  88245. }
  88246. // TODO
  88247. //let minWS = new THREE.Vector4(node.boundingBox.min.x, node.boundingBox.min.y, node.boundingBox.min.z, 1);
  88248. //let minVS = minWS.applyMatrix4(this.matrixWorldInverse);
  88249. //let right = node.boundingBox.max.x;
  88250. //let bottom = node.boundingBox.min.y;
  88251. //let top = node.boundingBox.max.y;
  88252. this.updateProjectionMatrix();
  88253. };
  88254. PerspectiveCamera.prototype.zoomTo = function (node, factor) {
  88255. if (!node.geometry && !node.boundingSphere && !node.boundingBox) {
  88256. return;
  88257. }
  88258. if (node.geometry && node.geometry.boundingSphere === null) {
  88259. node.geometry.computeBoundingSphere();
  88260. }
  88261. node.updateMatrixWorld();
  88262. var bs;
  88263. if (node.boundingSphere) {
  88264. bs = node.boundingSphere;
  88265. } else if (node.geometry && node.geometry.boundingSphere) {
  88266. bs = node.geometry.boundingSphere;
  88267. } else {
  88268. bs = node.boundingBox.getBoundingSphere(new Sphere());
  88269. }
  88270. var _factor = factor || 1;
  88271. bs = bs.clone().applyMatrix4(node.matrixWorld);
  88272. var radius = bs.radius;
  88273. var fovr = this.fov * Math.PI / 180;
  88274. if (this.aspect < 1) {
  88275. fovr = fovr * this.aspect;
  88276. }
  88277. var distanceFactor = Math.abs(radius / Math.sin(fovr / 2)) * _factor;
  88278. var offset = this.getWorldDirection(new Vector3()).multiplyScalar(-distanceFactor);
  88279. this.position.copy(bs.center.clone().add(offset));
  88280. };
  88281. Ray.prototype.distanceToPlaneWithNegative = function (plane) {
  88282. var denominator = plane.normal.dot(this.direction);
  88283. if (denominator === 0) {
  88284. // line is coplanar, return origin
  88285. if (plane.distanceToPoint(this.origin) === 0) {
  88286. return 0;
  88287. }
  88288. // Null is preferable to undefined since undefined means.... it is undefined
  88289. return null;
  88290. }
  88291. var t = -(this.origin.dot(plane.normal) + plane.constant) / denominator;
  88292. return t;
  88293. };
  88294. var workerPool = new WorkerPool();
  88295. var version = {
  88296. major: 1,
  88297. minor: 8,
  88298. suffix: '.0'
  88299. };
  88300. var lru = new LRU();
  88301. console.log('Potree ' + version.major + '.' + version.minor + version.suffix);
  88302. var pointBudget = 1 * 1000 * 1000;
  88303. var framenumber = 0;
  88304. var numNodesLoading = 0;
  88305. var maxNodesLoading = 6; //4;
  88306. var debug = {};
  88307. exports.scriptPath = "";
  88308. if (document.currentScript && document.currentScript.src) {
  88309. exports.scriptPath = new URL(document.currentScript.src + '/..').href;
  88310. if (exports.scriptPath.slice(-1) === '/') {
  88311. exports.scriptPath = exports.scriptPath.slice(0, -1);
  88312. }
  88313. } else if (({ url: (typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) })) {
  88314. exports.scriptPath = new URL((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('potree.js', document.baseURI).href)) + "/..").href;
  88315. if (exports.scriptPath.slice(-1) === '/') {
  88316. exports.scriptPath = exports.scriptPath.slice(0, -1);
  88317. }
  88318. } else {
  88319. console.error('Potree was unable to find its script path using document.currentScript. Is Potree included with a script tag? Does your browser support this function?');
  88320. }
  88321. var resourcePath = exports.scriptPath + '/resources';
  88322. //add:
  88323. function loadFile(_x, _x2, _x3, _x4) {
  88324. return _loadFile.apply(this, arguments);
  88325. }
  88326. function _loadFile() {
  88327. _loadFile = _asyncToGenerator(function* (path, params, callback, onError) {
  88328. params = params || {};
  88329. var fetchMethod = params.fetchMethod || 'get';
  88330. delete params.fetchMethod;
  88331. if (Potree.fileServer) {
  88332. Potree.fileServer[fetchMethod](path, {
  88333. params
  88334. }).then(data => {
  88335. if (data.data) data = data.data;
  88336. if (data.data) data = data.data; //融合页面getdataset需要查找两次data
  88337. callback && callback(data);
  88338. }).catch(onError);
  88339. } else {
  88340. try {
  88341. if (Object.keys(params).length > 0) {
  88342. path += '?';
  88343. var index = 0;
  88344. for (var i in params) {
  88345. if (index > 0) path += '&';
  88346. path += i;
  88347. path += '=';
  88348. path += params[i];
  88349. index++;
  88350. }
  88351. }
  88352. var info = {};
  88353. if (fetchMethod == 'post') info.method = 'POST';
  88354. var response = yield fetch(path, info);
  88355. var text = yield response.text();
  88356. var data = params.returnText ? text : JSON.parse(text);
  88357. if (data.data) data = data.data;
  88358. callback && callback(data);
  88359. return data;
  88360. } catch (e) {
  88361. console.log('loadFile出错', e);
  88362. onError && onError(e);
  88363. }
  88364. }
  88365. //查询: http://192.168.0.26:8080/doc.html#/default/filter-%E6%BC%AB%E6%B8%B8%E7%82%B9/filterUsingGET
  88366. });
  88367. return _loadFile.apply(this, arguments);
  88368. }
  88369. function loadDatasets(_x5, _x6, _x7) {
  88370. return _loadDatasets.apply(this, arguments);
  88371. }
  88372. //目前上传平面图后如果不点击保存按钮,数据还是旧的不生效
  88373. function _loadDatasets() {
  88374. _loadDatasets = _asyncToGenerator(function* (callback, sceneCode, onError) {
  88375. //之后直接把path写进来
  88376. var path;
  88377. sceneCode = sceneCode || Potree.settings.number;
  88378. if (Potree.fileServer) {
  88379. path = "/laser/dataset/".concat(sceneCode, "/getDataSet");
  88380. } else {
  88381. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/datasets`
  88382. //现在只能加载得了本地的了
  88383. path = "".concat(Potree.settings.urls.prefix, "/laser/dataset/").concat(sceneCode, "/getDataSet");
  88384. //path = `${Potree.scriptPath}/data/${sceneCode}/getDataSet.json`
  88385. }
  88386. return loadFile(path, null, callback, onError);
  88387. });
  88388. return _loadDatasets.apply(this, arguments);
  88389. }
  88390. function loadMapEntity(_x8, _x9) {
  88391. return _loadMapEntity.apply(this, arguments);
  88392. }
  88393. function _loadMapEntity() {
  88394. _loadMapEntity = _asyncToGenerator(function* (datasetId, force) {
  88395. if (!Potree.settings.floorplanEnable && !force && Potree.fileServer) return; /* 等待平面图类型定义好会加载 */
  88396. var loaded = 0;
  88397. var needLoads = datasetId == 'all' ? viewer.scene.pointclouds.map(e => e.dataset_id) : [datasetId];
  88398. var callback = (dataset_id, floorplanType, data) => {
  88399. if (!data || data.length == 0) return console.log('平面图没有数据', dataset_id, floorplanType);
  88400. //要防止旧的比新的先获取到导致覆盖新的,因为两种type随时可能切换
  88401. if (floorplanType != Potree.settings.floorplanType[dataset_id]) return; //如果请求的floorplanType不是当前最新的floorplanType就返回
  88402. var map = viewer.mapViewer.mapLayer.maps.find(e => e.name == 'floorplan_' + dataset_id);
  88403. if (map) {
  88404. viewer.mapViewer.mapLayer.removeMap(map);
  88405. }
  88406. var mapNew = viewer.mapViewer.mapLayer.addMapEntity(data.data || data, dataset_id);
  88407. if (map) {
  88408. mapNew.visibleReasons = map.visibleReasons;
  88409. mapNew.unvisibleReasons = map.unvisibleReasons;
  88410. }
  88411. loaded++;
  88412. };
  88413. needLoads.forEach(dataset_id => {
  88414. var floorplanType = Potree.settings.floorplanType[dataset_id],
  88415. prefix = '';
  88416. if (!Potree.fileServer) {
  88417. prefix = Potree.settings.urls.prefix;
  88418. }
  88419. if (!floorplanType) return;
  88420. var path;
  88421. /* if(Potree.fileServer){
  88422. path = `/laser/tiledMap/${Potree.settings.number}/tiledMap/${floorplanType}/${dataset_id}`
  88423. }else{
  88424. path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/tiled_maps`
  88425. } */
  88426. path = "".concat(prefix, "/laser/tiledMap/").concat(Potree.settings.number, "/tiledMap/").concat(floorplanType, "/").concat(dataset_id);
  88427. Potree.settings.floorplanRequests[dataset_id] = true; //开始加载了
  88428. return loadFile(path, null, callback.bind(this, dataset_id, floorplanType));
  88429. });
  88430. });
  88431. return _loadMapEntity.apply(this, arguments);
  88432. }
  88433. function loadPanos(_x10, _x11) {
  88434. return _loadPanos.apply(this, arguments);
  88435. }
  88436. function _loadPanos() {
  88437. _loadPanos = _asyncToGenerator(function* (datasetId, callback) {
  88438. var path;
  88439. //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  88440. if (Potree.fileServer) {
  88441. path = "/laser/filter/".concat(Potree.settings.number, "/query");
  88442. } else {
  88443. //path = `${Potree.settings.urls.prefix2}/indoor/${Potree.settings.number}/api/images/filter` + query
  88444. //path = `${Potree.scriptPath}/data/${Potree.settings.number}/panos-${datasetId}.json`
  88445. path = "".concat(Potree.settings.urls.prefix, "/laser/filter/").concat(Potree.settings.number, "/query");
  88446. }
  88447. return loadFile(path, {
  88448. datasetId: datasetId
  88449. }, callback);
  88450. });
  88451. return _loadPanos.apply(this, arguments);
  88452. }
  88453. function loadPanosInfo(_x12) {
  88454. return _loadPanosInfo.apply(this, arguments);
  88455. }
  88456. function _loadPanosInfo() {
  88457. _loadPanosInfo = _asyncToGenerator(function* (callback) {
  88458. var path;
  88459. if (Potree.fileServer) {} else {
  88460. path = "".concat(Potree.scriptPath, "/data/panoEdit/vision_edit.txt");
  88461. }
  88462. return loadFile(path, null, callback);
  88463. });
  88464. return _loadPanosInfo.apply(this, arguments);
  88465. }
  88466. function loadImgVersion(_x13) {
  88467. return _loadImgVersion.apply(this, arguments);
  88468. }
  88469. //site_model
  88470. /* {
  88471. "area": 2503.30551910935,
  88472. "attributes": {},
  88473. "center": [
  88474. 113.59568277455075,
  88475. 22.366566635195288,
  88476. 12.78751625
  88477. ],
  88478. "children": [],
  88479. "geometry_hash": 1891071345,
  88480. "id": 10,
  88481. "name": "港湾一号",
  88482. "parentId": null,
  88483. "polygon": {
  88484. "coordinates": [
  88485. [
  88486. [
  88487. 113.59590810534583,
  88488. 22.36679132753878
  88489. ],
  88490. [
  88491. 113.59590810534583,
  88492. 22.366807172528629
  88493. ],
  88494. [
  88495. 113.59545610274934,
  88496. 22.366807172528629
  88497. ],
  88498. [
  88499. 113.59545610274934,
  88500. 22.36679132753878
  88501. ]
  88502. ]
  88503. ],
  88504. "type": "Polygon"
  88505. },
  88506. "type": "BUILDING",
  88507. "volume": null,
  88508. "z_max": null,
  88509. "z_min": null
  88510. }
  88511. */
  88512. function _loadImgVersion() {
  88513. _loadImgVersion = _asyncToGenerator(function* (callback) {
  88514. var path;
  88515. //let query = `?datasetId=${datasetId}` //`?lat=${center.lat}&lon=${center.lon}&radius=200000`
  88516. /* if(Potree.fileServer){
  88517. path = `/laser/filter/${Potree.settings.number}/query`
  88518. }else{ */
  88519. path = "/laser/init/getSceneNumVersion/".concat(Potree.settings.number);
  88520. //api/laser/init
  88521. //}
  88522. return loadFile(path, {
  88523. fetchMethod: 'post'
  88524. }, callback, callback);
  88525. });
  88526. return _loadImgVersion.apply(this, arguments);
  88527. }
  88528. function Log$1() {
  88529. var args = Array.from(arguments);
  88530. var params = args[args.length - 1];
  88531. if (params && params.font) {
  88532. params = params.font, args.pop();
  88533. } else params = {};
  88534. var str = '',
  88535. color = params.color || '#13f',
  88536. fontSize = params.fontSize || 12;
  88537. args.forEach((e, i) => {
  88538. i > 0 && (str += ' , ');
  88539. /* if(params.toFixed && typeof e == 'number'){
  88540. e = e.toFixed(params.toFixed)
  88541. } */
  88542. if (params.toFixed) {
  88543. e = Potree.math.toPrecision(e, params.toFixed);
  88544. }
  88545. str += e; //object可以JSON.stringify,但不是所有都行
  88546. });
  88547. console.warn("%c".concat(str), "color:".concat(color, ";font-size:").concat(fontSize, "px"));
  88548. }
  88549. function loadPointCloud$1(path, name, sceneCode, timeStamp, callback, onError) {
  88550. var loaded = function loaded(e) {
  88551. e.pointcloud.name = name;
  88552. e.pointcloud.sceneCode = sceneCode; //对应4dkk的场景码
  88553. callback(e);
  88554. };
  88555. var promise = new Promise(resolve => {
  88556. // load pointcloud
  88557. if (!path) {
  88558. // TODO: callback? comment? Hello? Bueller? Anyone?
  88559. } else if (path.indexOf('ept.json') > 0) {
  88560. EptLoader.load(path, function (geometry) {
  88561. if (!geometry) {
  88562. console.error(new Error("failed to load point cloud from URL: ".concat(path)));
  88563. } else {
  88564. var pointcloud = new ExtendPointCloudOctree(geometry);
  88565. //loaded(pointcloud);
  88566. resolve({
  88567. type: 'pointcloud_loaded',
  88568. pointcloud: pointcloud
  88569. });
  88570. }
  88571. });
  88572. } else if (path.indexOf('cloud.js') > 0) {
  88573. POCLoader.load(path, timeStamp, function (geometry) {
  88574. if (!geometry) {
  88575. //callback({type: 'loading_failed'});
  88576. console.error(new Error("failed to load point cloud from URL: ".concat(path)));
  88577. onError && onError();
  88578. } else {
  88579. var pointcloud = new ExtendPointCloudOctree(geometry);
  88580. // loaded(pointcloud);
  88581. resolve({
  88582. type: 'pointcloud_loaded',
  88583. pointcloud: pointcloud
  88584. });
  88585. }
  88586. });
  88587. } /* else if (path.indexOf('metadata.json') > 0) { //部分浏览器(如uc)不支持NodeLoader中的1n的大数据写法
  88588. Potree.OctreeLoader.load(path).then(e => {
  88589. let geometry = e.geometry;
  88590. if(!geometry){
  88591. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  88592. }else{
  88593. let pointcloud = new ExtendPointCloudOctree(geometry);
  88594. let aPosition = pointcloud.getAttribute("position");
  88595. let material = pointcloud.material;
  88596. material.elevationRange = [
  88597. aPosition.range[0][2],
  88598. aPosition.range[1][2],
  88599. ];
  88600. // loaded(pointcloud);
  88601. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  88602. }
  88603. });
  88604. OctreeLoader.load(path, function (geometry) {
  88605. if (!geometry) {
  88606. //callback({type: 'loading_failed'});
  88607. console.error(new Error(`failed to load point cloud from URL: ${path}`));
  88608. } else {
  88609. let pointcloud = new ExtendPointCloudOctree(geometry);
  88610. // loaded(pointcloud);
  88611. resolve({type: 'pointcloud_loaded', pointcloud: pointcloud});
  88612. }
  88613. });
  88614. } */else if (path.indexOf('.vpc') > 0) {
  88615. PointCloudArena4DGeometry.load(path, function (geometry) {
  88616. if (!geometry) {
  88617. //callback({type: 'loading_failed'});
  88618. console.error(new Error("failed to load point cloud from URL: ".concat(path)));
  88619. } else {
  88620. var pointcloud = new PointCloudArena4D(geometry);
  88621. // loaded(pointcloud);
  88622. resolve({
  88623. type: 'pointcloud_loaded',
  88624. pointcloud: pointcloud
  88625. });
  88626. }
  88627. });
  88628. } else {
  88629. //callback({'type': 'loading_failed'});
  88630. console.error(new Error("failed to load point cloud from URL: ".concat(path)));
  88631. }
  88632. });
  88633. if (callback) {
  88634. promise.then(pointcloud => {
  88635. loaded(pointcloud);
  88636. });
  88637. } else {
  88638. return promise;
  88639. }
  88640. }
  88641. ;
  88642. // add selectgroup
  88643. (function ($) {
  88644. $.fn.extend({
  88645. selectgroup: function selectgroup() {
  88646. var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  88647. var elGroup = $(this);
  88648. var rootID = elGroup.prop("id");
  88649. var groupID = "".concat(rootID);
  88650. var groupTitle = args.title !== undefined ? args.title : "";
  88651. var elButtons = [];
  88652. elGroup.find("option").each((index, value) => {
  88653. var buttonID = $(value).prop("id");
  88654. var label = $(value).html();
  88655. var optionValue = $(value).prop("value");
  88656. var elButton = $("\n\t\t\t\t\t<span style=\"flex-grow: 1; display: inherit\">\n\t\t\t\t\t<label for=\"".concat(buttonID, "\" class=\"ui-button\" style=\"width: 100%; padding: .4em .1em\">").concat(label, "</label>\n\t\t\t\t\t<input type=\"radio\" name=\"").concat(groupID, "\" id=\"").concat(buttonID, "\" value=\"").concat(optionValue, "\" style=\"display: none\"/>\n\t\t\t\t\t</span>\n\t\t\t\t"));
  88657. var elLabel = elButton.find("label");
  88658. var elInput = elButton.find("input");
  88659. elInput.change(() => {
  88660. elGroup.find("label").removeClass("ui-state-active");
  88661. elGroup.find("label").addClass("ui-state-default");
  88662. if (elInput.is(":checked")) {
  88663. elLabel.addClass("ui-state-active");
  88664. } else {
  88665. //elLabel.addClass("ui-state-default");
  88666. }
  88667. });
  88668. elButtons.push(elButton);
  88669. });
  88670. var elFieldset = $("\n\t\t\t\t<fieldset style=\"border: none; margin: 0px; padding: 0px\">\n\t\t\t\t\t<legend>".concat(groupTitle, "</legend>\n\t\t\t\t\t<span style=\"display: flex\">\n\n\t\t\t\t\t</span>\n\t\t\t\t</fieldset>\n\t\t\t"));
  88671. var elButtonContainer = elFieldset.find("span");
  88672. for (var elButton of elButtons) {
  88673. elButtonContainer.append(elButton);
  88674. }
  88675. elButtonContainer.find("label").each((index, value) => {
  88676. $(value).css("margin", "0px");
  88677. $(value).css("border-radius", "0px");
  88678. $(value).css("border", "1px solid black");
  88679. $(value).css("border-left", "none");
  88680. });
  88681. elButtonContainer.find("label:first").each((index, value) => {
  88682. $(value).css("border-radius", "4px 0px 0px 4px");
  88683. });
  88684. elButtonContainer.find("label:last").each((index, value) => {
  88685. $(value).css("border-radius", "0px 4px 4px 0px");
  88686. $(value).css("border-left", "none");
  88687. });
  88688. elGroup.empty();
  88689. elGroup.append(elFieldset);
  88690. }
  88691. });
  88692. })(jQuery);
  88693. //在这之后export的内容才赋值到Potree中
  88694. exports.Action = Action;
  88695. exports.Annotation = Annotation;
  88696. exports.Box3Helper = Box3Helper$1;
  88697. exports.BoxVolume = BoxVolume$1;
  88698. exports.CameraAnimation = CameraAnimation$1;
  88699. exports.CameraMode = CameraMode;
  88700. exports.ClassificationScheme = ClassificationScheme;
  88701. exports.ClipMethod = ClipMethod;
  88702. exports.ClipTask = ClipTask;
  88703. exports.ClipVolume = ClipVolume;
  88704. exports.ClippingTool = ClippingTool;
  88705. exports.ElevationGradientRepeat = ElevationGradientRepeat;
  88706. exports.Enum = Enum;
  88707. exports.EnumItem = EnumItem;
  88708. exports.EptBinaryLoader = EptBinaryLoader;
  88709. exports.EptKey = EptKey;
  88710. exports.EptLaszipLoader = EptLaszipLoader;
  88711. exports.EptLazBatcher = EptLazBatcher;
  88712. exports.EptLoader = EptLoader;
  88713. exports.EptZstandardLoader = EptZstandardLoader;
  88714. exports.EventDispatcher = EventDispatcher$1;
  88715. exports.ExtendPointCloudMaterial = ExtendPointCloudMaterial;
  88716. exports.ExtendPointCloudOctree = ExtendPointCloudOctree;
  88717. exports.ExtendScene = ExtendScene;
  88718. exports.EyeDomeLightingMaterial = EyeDomeLightingMaterial;
  88719. exports.Features = Features;
  88720. exports.FirstPersonControls = FirstPersonControls$1;
  88721. exports.GeoPackageLoader = GeoPackageLoader;
  88722. exports.Geopackage = Geopackage$1;
  88723. exports.Gradients = Gradients;
  88724. exports.HierarchicalSlider = HierarchicalSlider;
  88725. exports.Images360 = Images360;
  88726. exports.KeyCodes = KeyCodes;
  88727. exports.LRU = LRU;
  88728. exports.LRUItem = LRUItem;
  88729. exports.LengthUnits = LengthUnits;
  88730. exports.LineDraw = LineDraw;
  88731. exports.Log = Log$1;
  88732. exports.MOUSE = MOUSE$1;
  88733. exports.MapViewer = MapViewer;
  88734. exports.Measure = Measure$1;
  88735. exports.MeasuringTool = MeasuringTool;
  88736. exports.MeshDraw = MeshDraw;
  88737. exports.Message = Message;
  88738. exports.NodeLoader = NodeLoader;
  88739. exports.NormalizationEDLMaterial = NormalizationEDLMaterial;
  88740. exports.NormalizationMaterial = NormalizationMaterial;
  88741. exports.OctreeLoader = OctreeLoader;
  88742. exports.OrbitControls = OrbitControls$2;
  88743. exports.OrientedImage = OrientedImage;
  88744. exports.OrientedImageLoader = OrientedImageLoader;
  88745. exports.OrientedImages = OrientedImages;
  88746. exports.POCLoader = POCLoader;
  88747. exports.PointAttribute = PointAttribute;
  88748. exports.PointAttributeTypes = PointAttributeTypes;
  88749. exports.PointAttributes = PointAttributes;
  88750. exports.PointCloudEptGeometry = PointCloudEptGeometry;
  88751. exports.PointCloudEptGeometryNode = PointCloudEptGeometryNode;
  88752. exports.PointCloudOctreeGeometry = PointCloudOctreeGeometry;
  88753. exports.PointCloudOctreeGeometryNode = PointCloudOctreeGeometryNode;
  88754. exports.PointCloudSM = PointCloudSM;
  88755. exports.PointCloudTree = PointCloudTree;
  88756. exports.PointCloudTreeNode = PointCloudTreeNode;
  88757. exports.PointShape = PointShape$1;
  88758. exports.PointSizeType = PointSizeType;
  88759. exports.Points = Points$1;
  88760. exports.PolygonClipVolume = PolygonClipVolume;
  88761. exports.Profile = Profile;
  88762. exports.ProfileData = ProfileData;
  88763. exports.ProfileRequest = ProfileRequest;
  88764. exports.ProfileTool = ProfileTool;
  88765. exports.Renderer = Renderer;
  88766. exports.ScreenBoxSelectTool = ScreenBoxSelectTool;
  88767. exports.ShapefileLoader = ShapefileLoader;
  88768. exports.SphereVolume = SphereVolume$2;
  88769. exports.SpotLightHelper = SpotLightHelper$1;
  88770. exports.TextSprite = TextSprite$2;
  88771. exports.TransformationTool = TransformationTool;
  88772. exports.TreeType = TreeType;
  88773. exports.Utils = Utils;
  88774. exports.Version = Version;
  88775. exports.Viewer = Viewer$1;
  88776. exports.Volume = Volume$1;
  88777. exports.VolumeTool = VolumeTool;
  88778. exports.WorkerPool = WorkerPool;
  88779. exports.XHRFactory = XHRFactory;
  88780. exports.config = config$1;
  88781. exports.debug = debug;
  88782. exports.framenumber = framenumber;
  88783. exports.loadDatasets = loadDatasets;
  88784. exports.loadFile = loadFile;
  88785. exports.loadImgVersion = loadImgVersion;
  88786. exports.loadMapEntity = loadMapEntity;
  88787. exports.loadPanos = loadPanos;
  88788. exports.loadPanosInfo = loadPanosInfo;
  88789. exports.loadPointCloud = loadPointCloud$1;
  88790. exports.loadProject = loadProject;
  88791. exports.lru = lru;
  88792. exports.maxNodesLoading = maxNodesLoading;
  88793. exports.mergeEditStart = mergeEditStart;
  88794. exports.numNodesLoading = numNodesLoading;
  88795. exports.panoEditStart = panoEditStart;
  88796. exports.pointBudget = pointBudget;
  88797. exports.resourcePath = resourcePath;
  88798. exports.saveProject = saveProject;
  88799. exports.settings = settings;
  88800. exports.start = start;
  88801. exports.version = version;
  88802. exports.workerPool = workerPool;
  88803. Object.defineProperty(exports, '__esModule', { value: true });
  88804. })));
  88805. //# sourceMappingURL=potree.js.map